=0;--i) ret[i] = [];
}
for(i=n;i>=0;--i) ret[i].push(k[i]);
ret[n+1].push(Ai);
}
} else gather(Ai,ret,k);
}
}
if(k.length>n) k.pop();
return ret;
}
// 6. Coordinate matrices
numeric.cLU = function LU(A) {
var I = A[0], J = A[1], V = A[2];
var p = I.length, m=0, i,j,k,a,b,c;
for(i=0;im) m=I[i];
m++;
var L = Array(m), U = Array(m), left = numeric.rep([m],Infinity), right = numeric.rep([m],-Infinity);
var Ui, Uj,alpha;
for(k=0;k
right[i]) right[i] = j;
}
for(i=0;i right[i+1]) right[i+1] = right[i]; }
for(i=m-1;i>=1;i--) { if(left[i]=0;i--) {
while(Uj[k] > i) {
ret[i] -= Uv[k]*ret[Uj[k]];
k--;
}
ret[i] /= Uv[k];
k--;
}
return ret;
};
numeric.cgrid = function grid(n,shape) {
if(typeof n === "number") n = [n,n];
var ret = numeric.rep(n,-1);
var i,j,count;
if(typeof shape !== "function") {
switch(shape) {
case 'L':
shape = function(i,j) { return (i>=n[0]/2 || jN) N = Ai[k]; }
N++;
ret = numeric.rep([N],0);
for(k=0;k1) {
mid = floor((p+q)/2);
if(x[mid] <= x0) p = mid;
else q = mid;
}
return this._at(x0,p);
}
var n = x0.length, i, ret = Array(n);
for(i=n-1;i!==-1;--i) ret[i] = this.at(x0[i]);
return ret;
}
numeric.Spline.prototype.diff = function diff() {
var x = this.x;
var yl = this.yl;
var yr = this.yr;
var kl = this.kl;
var kr = this.kr;
var n = yl.length;
var i,dx,dy;
var zl = kl, zr = kr, pl = Array(n), pr = Array(n);
var add = numeric.add, mul = numeric.mul, div = numeric.div, sub = numeric.sub;
for(i=n-1;i!==-1;--i) {
dx = x[i+1]-x[i];
dy = sub(yr[i+1],yl[i]);
pl[i] = div(add(mul(dy, 6),mul(kl[i],-4*dx),mul(kr[i+1],-2*dx)),dx*dx);
pr[i+1] = div(add(mul(dy,-6),mul(kl[i], 2*dx),mul(kr[i+1], 4*dx)),dx*dx);
}
return new numeric.Spline(x,zl,zr,pl,pr);
}
numeric.Spline.prototype.roots = function roots() {
function sqr(x) { return x*x; }
function heval(y0,y1,k0,k1,x) {
var A = k0*2-(y1-y0);
var B = -k1*2+(y1-y0);
var t = (x+1)*0.5;
var s = t*(1-t);
return (1-t)*y0+t*y1+A*s*(1-t)+B*s*t;
}
var ret = [];
var x = this.x, yl = this.yl, yr = this.yr, kl = this.kl, kr = this.kr;
if(typeof yl[0] === "number") {
yl = [yl];
yr = [yr];
kl = [kl];
kr = [kr];
}
var m = yl.length,n=x.length-1,i,j,k,y,s,t;
var ai,bi,ci,di, ret = Array(m),ri,k0,k1,y0,y1,A,B,D,dx,cx,stops,z0,z1,zm,t0,t1,tm;
var sqrt = Math.sqrt;
for(i=0;i!==m;++i) {
ai = yl[i];
bi = yr[i];
ci = kl[i];
di = kr[i];
ri = [];
for(j=0;j!==n;j++) {
if(j>0 && bi[j]*ai[j]<0) ri.push(x[j]);
dx = (x[j+1]-x[j]);
cx = x[j];
y0 = ai[j];
y1 = bi[j+1];
k0 = ci[j]/dx;
k1 = di[j+1]/dx;
D = sqr(k0-k1+3*(y0-y1)) + 12*k1*y0;
A = k1+3*y0+2*k0-3*y1;
B = 3*(k1+k0+2*(y0-y1));
if(D<=0) {
z0 = A/B;
if(z0>x[j] && z0x[j] && z0x[j] && z10) {
t0 = t1;
z0 = z1;
continue;
}
var side = 0;
while(1) {
tm = (z0*t1-z1*t0)/(z0-z1);
if(tm <= t0 || tm >= t1) { break; }
zm = this._at(tm,j);
if(zm*z1>0) {
t1 = tm;
z1 = zm;
if(side === -1) z0*=0.5;
side = -1;
} else if(zm*z0>0) {
t0 = tm;
z0 = zm;
if(side === 1) z1*=0.5;
side = 1;
} else break;
}
ri.push(tm);
t0 = stops[k+1];
z0 = this._at(t0, j);
}
if(z1 === 0) ri.push(t1);
}
ret[i] = ri;
}
if(typeof this.yl[0] === "number") return ret[0];
return ret;
}
numeric.spline = function spline(x,y,k1,kn) {
var n = x.length, b = [], dx = [], dy = [];
var i;
var sub = numeric.sub,mul = numeric.mul,add = numeric.add;
for(i=n-2;i>=0;i--) { dx[i] = x[i+1]-x[i]; dy[i] = sub(y[i+1],y[i]); }
if(typeof k1 === "string" || typeof kn === "string") {
k1 = kn = "periodic";
}
// Build sparse tridiagonal system
var T = [[],[],[]];
switch(typeof k1) {
case "undefined":
b[0] = mul(3/(dx[0]*dx[0]),dy[0]);
T[0].push(0,0);
T[1].push(0,1);
T[2].push(2/dx[0],1/dx[0]);
break;
case "string":
b[0] = add(mul(3/(dx[n-2]*dx[n-2]),dy[n-2]),mul(3/(dx[0]*dx[0]),dy[0]));
T[0].push(0,0,0);
T[1].push(n-2,0,1);
T[2].push(1/dx[n-2],2/dx[n-2]+2/dx[0],1/dx[0]);
break;
default:
b[0] = k1;
T[0].push(0);
T[1].push(0);
T[2].push(1);
break;
}
for(i=1;i20) { throw new Error("Numerical gradient fails"); }
x0[i] = x[i]+h;
f1 = f(x0);
x0[i] = x[i]-h;
f2 = f(x0);
x0[i] = x[i];
if(isNaN(f1) || isNaN(f2)) { h/=16; continue; }
J[i] = (f1-f2)/(2*h);
t0 = x[i]-h;
t1 = x[i];
t2 = x[i]+h;
d1 = (f1-f0)/h;
d2 = (f0-f2)/h;
N = max(abs(J[i]),abs(f0),abs(f1),abs(f2),abs(t0),abs(t1),abs(t2),1e-8);
errest = min(max(abs(d1-J[i]),abs(d2-J[i]),abs(d1-d2))/N,h/N);
if(errest>eps) { h/=16; }
else break;
}
}
return J;
}
numeric.uncmin = function uncmin(f,x0,tol,gradient,maxit,callback,options) {
var grad = numeric.gradient;
if(typeof options === "undefined") { options = {}; }
if(typeof tol === "undefined") { tol = 1e-8; }
if(typeof gradient === "undefined") { gradient = function(x) { return grad(f,x); }; }
if(typeof maxit === "undefined") maxit = 1000;
x0 = numeric.clone(x0);
var n = x0.length;
var f0 = f(x0),f1,df0;
if(isNaN(f0)) throw new Error('uncmin: f(x0) is a NaN!');
var max = Math.max, norm2 = numeric.norm2;
tol = max(tol,numeric.epsilon);
var step,g0,g1,H1 = options.Hinv || numeric.identity(n);
var dot = numeric.dot, inv = numeric.inv, sub = numeric.sub, add = numeric.add, ten = numeric.tensor, div = numeric.div, mul = numeric.mul;
var all = numeric.all, isfinite = numeric.isFinite, neg = numeric.neg;
var it=0,i,s,x1,y,Hy,Hs,ys,i0,t,nstep,t1,t2;
var msg = "";
g0 = gradient(x0);
while(it= 0.1*t*df0 || isNaN(f1)) {
t *= 0.5;
++it;
continue;
}
break;
}
if(t*nstep < tol) { msg = "Line search step size smaller than tol"; break; }
if(it === maxit) { msg = "maxit reached during line search"; break; }
g1 = gradient(x1);
y = sub(g1,g0);
ys = dot(y,s);
Hy = dot(H1,y);
H1 = sub(add(H1,
mul(
(ys+dot(y,Hy))/(ys*ys),
ten(s,s) )),
div(add(ten(Hy,s),ten(s,Hy)),ys));
x0 = x1;
f0 = f1;
g0 = g1;
++it;
}
return {solution: x0, f: f0, gradient: g0, invHessian: H1, iterations:it, message: msg};
}
// 10. Ode solver (Dormand-Prince)
numeric.Dopri = function Dopri(x,y,f,ymid,iterations,msg,events) {
this.x = x;
this.y = y;
this.f = f;
this.ymid = ymid;
this.iterations = iterations;
this.events = events;
this.message = msg;
}
numeric.Dopri.prototype._at = function _at(xi,j) {
function sqr(x) { return x*x; }
var sol = this;
var xs = sol.x;
var ys = sol.y;
var k1 = sol.f;
var ymid = sol.ymid;
var n = xs.length;
var x0,x1,xh,y0,y1,yh,xi;
var floor = Math.floor,h;
var c = 0.5;
var add = numeric.add, mul = numeric.mul,sub = numeric.sub, p,q,w;
x0 = xs[j];
x1 = xs[j+1];
y0 = ys[j];
y1 = ys[j+1];
h = x1-x0;
xh = x0+c*h;
yh = ymid[j];
p = sub(k1[j ],mul(y0,1/(x0-xh)+2/(x0-x1)));
q = sub(k1[j+1],mul(y1,1/(x1-xh)+2/(x1-x0)));
w = [sqr(xi - x1) * (xi - xh) / sqr(x0 - x1) / (x0 - xh),
sqr(xi - x0) * sqr(xi - x1) / sqr(x0 - xh) / sqr(x1 - xh),
sqr(xi - x0) * (xi - xh) / sqr(x1 - x0) / (x1 - xh),
(xi - x0) * sqr(xi - x1) * (xi - xh) / sqr(x0-x1) / (x0 - xh),
(xi - x1) * sqr(xi - x0) * (xi - xh) / sqr(x0-x1) / (x1 - xh)];
return add(add(add(add(mul(y0,w[0]),
mul(yh,w[1])),
mul(y1,w[2])),
mul( p,w[3])),
mul( q,w[4]));
}
numeric.Dopri.prototype.at = function at(x) {
var i,j,k,floor = Math.floor;
if(typeof x !== "number") {
var n = x.length, ret = Array(n);
for(i=n-1;i!==-1;--i) {
ret[i] = this.at(x[i]);
}
return ret;
}
var x0 = this.x;
i = 0; j = x0.length-1;
while(j-i>1) {
k = floor(0.5*(i+j));
if(x0[k] <= x) i = k;
else j = k;
}
return this._at(x,i);
}
numeric.dopri = function dopri(x0,x1,y0,f,tol,maxit,event) {
if(typeof tol === "undefined") { tol = 1e-6; }
if(typeof maxit === "undefined") { maxit = 1000; }
var xs = [x0], ys = [y0], k1 = [f(x0,y0)], k2,k3,k4,k5,k6,k7, ymid = [];
var A2 = 1/5;
var A3 = [3/40,9/40];
var A4 = [44/45,-56/15,32/9];
var A5 = [19372/6561,-25360/2187,64448/6561,-212/729];
var A6 = [9017/3168,-355/33,46732/5247,49/176,-5103/18656];
var b = [35/384,0,500/1113,125/192,-2187/6784,11/84];
var bm = [0.5*6025192743/30085553152,
0,
0.5*51252292925/65400821598,
0.5*-2691868925/45128329728,
0.5*187940372067/1594534317056,
0.5*-1776094331/19743644256,
0.5*11237099/235043384];
var c = [1/5,3/10,4/5,8/9,1,1];
var e = [-71/57600,0,71/16695,-71/1920,17253/339200,-22/525,1/40];
var i = 0,er,j;
var h = (x1-x0)/10;
var it = 0;
var add = numeric.add, mul = numeric.mul, y1,erinf;
var max = Math.max, min = Math.min, abs = Math.abs, norminf = numeric.norminf,pow = Math.pow;
var any = numeric.any, lt = numeric.lt, and = numeric.and, sub = numeric.sub;
var e0, e1, ev;
var ret = new numeric.Dopri(xs,ys,k1,ymid,-1,"");
if(typeof event === "function") e0 = event(x0,y0);
while(x0x1) h = x1-x0;
k2 = f(x0+c[0]*h, add(y0,mul( A2*h,k1[i])));
k3 = f(x0+c[1]*h, add(add(y0,mul(A3[0]*h,k1[i])),mul(A3[1]*h,k2)));
k4 = f(x0+c[2]*h, add(add(add(y0,mul(A4[0]*h,k1[i])),mul(A4[1]*h,k2)),mul(A4[2]*h,k3)));
k5 = f(x0+c[3]*h, add(add(add(add(y0,mul(A5[0]*h,k1[i])),mul(A5[1]*h,k2)),mul(A5[2]*h,k3)),mul(A5[3]*h,k4)));
k6 = f(x0+c[4]*h,add(add(add(add(add(y0,mul(A6[0]*h,k1[i])),mul(A6[1]*h,k2)),mul(A6[2]*h,k3)),mul(A6[3]*h,k4)),mul(A6[4]*h,k5)));
y1 = add(add(add(add(add(y0,mul(k1[i],h*b[0])),mul(k3,h*b[2])),mul(k4,h*b[3])),mul(k5,h*b[4])),mul(k6,h*b[5]));
k7 = f(x0+h,y1);
er = add(add(add(add(add(mul(k1[i],h*e[0]),mul(k3,h*e[2])),mul(k4,h*e[3])),mul(k5,h*e[4])),mul(k6,h*e[5])),mul(k7,h*e[6]));
if(typeof er === "number") erinf = abs(er);
else erinf = norminf(er);
if(erinf > tol) { // reject
h = 0.2*h*pow(tol/erinf,0.25);
if(x0+h === x0) {
ret.msg = "Step size became too small";
break;
}
continue;
}
ymid[i] = add(add(add(add(add(add(y0,
mul(k1[i],h*bm[0])),
mul(k3 ,h*bm[2])),
mul(k4 ,h*bm[3])),
mul(k5 ,h*bm[4])),
mul(k6 ,h*bm[5])),
mul(k7 ,h*bm[6]));
++i;
xs[i] = x0+h;
ys[i] = y1;
k1[i] = k7;
if(typeof event === "function") {
var yi,xl = x0,xr = x0+0.5*h,xi;
e1 = event(xr,ymid[i-1]);
ev = and(lt(e0,0),lt(0,e1));
if(!any(ev)) { xl = xr; xr = x0+h; e0 = e1; e1 = event(xr,y1); ev = and(lt(e0,0),lt(0,e1)); }
if(any(ev)) {
var xc, yc, en,ei;
var side=0, sl = 1.0, sr = 1.0;
while(1) {
if(typeof e0 === "number") xi = (sr*e1*xl-sl*e0*xr)/(sr*e1-sl*e0);
else {
xi = xr;
for(j=e0.length-1;j!==-1;--j) {
if(e0[j]<0 && e1[j]>0) xi = min(xi,(sr*e1[j]*xl-sl*e0[j]*xr)/(sr*e1[j]-sl*e0[j]));
}
}
if(xi <= xl || xi >= xr) break;
yi = ret._at(xi, i-1);
ei = event(xi,yi);
en = and(lt(e0,0),lt(0,ei));
if(any(en)) {
xr = xi;
e1 = ei;
ev = en;
sr = 1.0;
if(side === -1) sl *= 0.5;
else sl = 1.0;
side = -1;
} else {
xl = xi;
e0 = ei;
sl = 1.0;
if(side === 1) sr *= 0.5;
else sr = 1.0;
side = 1;
}
}
y1 = ret._at(0.5*(x0+xi),i-1);
ret.f[i] = f(xi,yi);
ret.x[i] = xi;
ret.y[i] = yi;
ret.ymid[i-1] = y1;
ret.events = ev;
ret.iterations = it;
return ret;
}
}
x0 += h;
y0 = y1;
e0 = e1;
h = min(0.8*h*pow(tol/erinf,0.25),4*h);
}
ret.iterations = it;
return ret;
}
// 11. Ax = b
numeric.LU = function(A, fast) {
fast = fast || false;
var abs = Math.abs;
var i, j, k, absAjk, Akk, Ak, Pk, Ai;
var max;
var n = A.length, n1 = n-1;
var P = new Array(n);
if(!fast) A = numeric.clone(A);
for (k = 0; k < n; ++k) {
Pk = k;
Ak = A[k];
max = abs(Ak[k]);
for (j = k + 1; j < n; ++j) {
absAjk = abs(A[j][k]);
if (max < absAjk) {
max = absAjk;
Pk = j;
}
}
P[k] = Pk;
if (Pk != k) {
A[k] = A[Pk];
A[Pk] = Ak;
Ak = A[k];
}
Akk = Ak[k];
for (i = k + 1; i < n; ++i) {
A[i][k] /= Akk;
}
for (i = k + 1; i < n; ++i) {
Ai = A[i];
for (j = k + 1; j < n1; ++j) {
Ai[j] -= Ai[k] * Ak[j];
++j;
Ai[j] -= Ai[k] * Ak[j];
}
if(j===n1) Ai[j] -= Ai[k] * Ak[j];
}
}
return {
LU: A,
P: P
};
}
numeric.LUsolve = function LUsolve(LUP, b) {
var i, j;
var LU = LUP.LU;
var n = LU.length;
var x = numeric.clone(b);
var P = LUP.P;
var Pi, LUi, LUii, tmp;
for (i=n-1;i!==-1;--i) x[i] = b[i];
for (i = 0; i < n; ++i) {
Pi = P[i];
if (P[i] !== i) {
tmp = x[i];
x[i] = x[Pi];
x[Pi] = tmp;
}
LUi = LU[i];
for (j = 0; j < i; ++j) {
x[i] -= x[j] * LUi[j];
}
}
for (i = n - 1; i >= 0; --i) {
LUi = LU[i];
for (j = i + 1; j < n; ++j) {
x[i] -= x[j] * LUi[j];
}
x[i] /= LUi[i];
}
return x;
}
numeric.solve = function solve(A,b,fast) { return numeric.LUsolve(numeric.LU(A,fast), b); }
// 12. Linear programming
numeric.echelonize = function echelonize(A) {
var s = numeric.dim(A), m = s[0], n = s[1];
var I = numeric.identity(m);
var P = Array(m);
var i,j,k,l,Ai,Ii,Z,a;
var abs = Math.abs;
var diveq = numeric.diveq;
A = numeric.clone(A);
for(i=0;ia1) alpha = a1;
g = add(c,mul(alpha,p));
H = dot(A1,A0);
for(i=m-1;i!==-1;--i) H[i][i] += 1;
d = solve(H,div(g,alpha),true);
var t0 = div(z,dot(A,d));
var t = 1.0;
for(i=n-1;i!==-1;--i) if(t0[i]<0) t = min(t,-0.999*t0[i]);
y = sub(x,mul(d,t));
z = sub(b,dot(A,y));
if(!all(gt(z,0))) return { solution: x, message: "", iterations: count };
x = y;
if(alpha=0) unbounded = false;
else unbounded = true;
}
if(unbounded) return { solution: y, message: "Unbounded", iterations: count };
}
return { solution: x, message: "maximum iteration count exceeded", iterations:count };
}
numeric._solveLP = function _solveLP(c,A,b,tol,maxit) {
var m = c.length, n = b.length,y;
var sum = numeric.sum, log = numeric.log, mul = numeric.mul, sub = numeric.sub, dot = numeric.dot, div = numeric.div, add = numeric.add;
var c0 = numeric.rep([m],0).concat([1]);
var J = numeric.rep([n,1],-1);
var A0 = numeric.blockMatrix([[A , J ]]);
var b0 = b;
var y = numeric.rep([m],0).concat(Math.max(0,numeric.sup(numeric.neg(b)))+1);
var x0 = numeric.__solveLP(c0,A0,b0,tol,maxit,y,false);
var x = numeric.clone(x0.solution);
x.length = m;
var foo = numeric.inf(sub(b,dot(A,x)));
if(foo<0) { return { solution: NaN, message: "Infeasible", iterations: x0.iterations }; }
var ret = numeric.__solveLP(c, A, b, tol, maxit-x0.iterations, x, true);
ret.iterations += x0.iterations;
return ret;
};
numeric.solveLP = function solveLP(c,A,b,Aeq,beq,tol,maxit) {
if(typeof maxit === "undefined") maxit = 1000;
if(typeof tol === "undefined") tol = numeric.epsilon;
if(typeof Aeq === "undefined") return numeric._solveLP(c,A,b,tol,maxit);
var m = Aeq.length, n = Aeq[0].length, o = A.length;
var B = numeric.echelonize(Aeq);
var flags = numeric.rep([n],0);
var P = B.P;
var Q = [];
var i;
for(i=P.length-1;i!==-1;--i) flags[P[i]] = 1;
for(i=n-1;i!==-1;--i) if(flags[i]===0) Q.push(i);
var g = numeric.getRange;
var I = numeric.linspace(0,m-1), J = numeric.linspace(0,o-1);
var Aeq2 = g(Aeq,I,Q), A1 = g(A,J,P), A2 = g(A,J,Q), dot = numeric.dot, sub = numeric.sub;
var A3 = dot(A1,B.I);
var A4 = sub(A2,dot(A3,Aeq2)), b4 = sub(b,dot(A3,beq));
var c1 = Array(P.length), c2 = Array(Q.length);
for(i=P.length-1;i!==-1;--i) c1[i] = c[P[i]];
for(i=Q.length-1;i!==-1;--i) c2[i] = c[Q[i]];
var c4 = sub(c2,dot(c1,dot(B.I,Aeq2)));
var S = numeric._solveLP(c4,A4,b4,tol,maxit);
var x2 = S.solution;
if(x2!==x2) return S;
var x1 = dot(B.I,sub(beq,dot(Aeq2,x2)));
var x = Array(c.length);
for(i=P.length-1;i!==-1;--i) x[P[i]] = x1[i];
for(i=Q.length-1;i!==-1;--i) x[Q[i]] = x2[i];
return { solution: x, message:S.message, iterations: S.iterations };
}
numeric.MPStoLP = function MPStoLP(MPS) {
if(MPS instanceof String) { MPS.split('\n'); }
var state = 0;
var states = ['Initial state','NAME','ROWS','COLUMNS','RHS','BOUNDS','ENDATA'];
var n = MPS.length;
var i,j,z,N=0,rows = {}, sign = [], rl = 0, vars = {}, nv = 0;
var name;
var c = [], A = [], b = [];
function err(e) { throw new Error('MPStoLP: '+e+'\nLine '+i+': '+MPS[i]+'\nCurrent state: '+states[state]+'\n'); }
for(i=0;i
//
// Math.seedrandom('yipee'); Sets Math.random to a function that is
// initialized using the given explicit seed.
//
// Math.seedrandom(); Sets Math.random to a function that is
// seeded using the current time, dom state,
// and other accumulated local entropy.
// The generated seed string is returned.
//
// Math.seedrandom('yowza', true);
// Seeds using the given explicit seed mixed
// together with accumulated entropy.
//
//
// Seeds using physical random bits downloaded
// from random.org.
//
// Seeds using urandom bits from call.jsonlib.com,
// which is faster than random.org.
//
// Examples:
//
// Math.seedrandom("hello"); // Use "hello" as the seed.
// document.write(Math.random()); // Always 0.5463663768140734
// document.write(Math.random()); // Always 0.43973793770592234
// var rng1 = Math.random; // Remember the current prng.
//
// var autoseed = Math.seedrandom(); // New prng with an automatic seed.
// document.write(Math.random()); // Pretty much unpredictable.
//
// Math.random = rng1; // Continue "hello" prng sequence.
// document.write(Math.random()); // Always 0.554769432473455
//
// Math.seedrandom(autoseed); // Restart at the previous seed.
// document.write(Math.random()); // Repeat the 'unpredictable' value.
//
// Notes:
//
// Each time seedrandom('arg') is called, entropy from the passed seed
// is accumulated in a pool to help generate future seeds for the
// zero-argument form of Math.seedrandom, so entropy can be injected over
// time by calling seedrandom with explicit data repeatedly.
//
// On speed - This javascript implementation of Math.random() is about
// 3-10x slower than the built-in Math.random() because it is not native
// code, but this is typically fast enough anyway. Seeding is more expensive,
// especially if you use auto-seeding. Some details (timings on Chrome 4):
//
// Our Math.random() - avg less than 0.002 milliseconds per call
// seedrandom('explicit') - avg less than 0.5 milliseconds per call
// seedrandom('explicit', true) - avg less than 2 milliseconds per call
// seedrandom() - avg about 38 milliseconds per call
//
// LICENSE (BSD):
//
// Copyright 2010 David Bau, all rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of this module nor the names of its contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
/**
* All code is in an anonymous closure to keep the global namespace clean.
*
* @param {number=} overflow
* @param {number=} startdenom
*/
// Patched by Seb so that seedrandom.js does not pollute the Math object.
// My tests suggest that doing Math.trouble = 1 makes Math lookups about 5%
// slower.
numeric.seedrandom = { pow:Math.pow, random:Math.random };
(function (pool, math, width, chunks, significance, overflow, startdenom) {
//
// seedrandom()
// This is the seedrandom function described above.
//
math['seedrandom'] = function seedrandom(seed, use_entropy) {
var key = [];
var arc4;
// Flatten the seed string or build one from local entropy if needed.
seed = mixkey(flatten(
use_entropy ? [seed, pool] :
arguments.length ? seed :
[new Date().getTime(), pool, window], 3), key);
// Use the seed to initialize an ARC4 generator.
arc4 = new ARC4(key);
// Mix the randomness into accumulated entropy.
mixkey(arc4.S, pool);
// Override Math.random
// This function returns a random double in [0, 1) that contains
// randomness in every bit of the mantissa of the IEEE 754 value.
math['random'] = function random() { // Closure to return a random double:
var n = arc4.g(chunks); // Start with a numerator n < 2 ^ 48
var d = startdenom; // and denominator d = 2 ^ 48.
var x = 0; // and no 'extra last byte'.
while (n < significance) { // Fill up all significant digits by
n = (n + x) * width; // shifting numerator and
d *= width; // denominator and generating a
x = arc4.g(1); // new least-significant-byte.
}
while (n >= overflow) { // To avoid rounding up, before adding
n /= 2; // last byte, shift everything
d /= 2; // right using integer math until
x >>>= 1; // we have exactly the desired bits.
}
return (n + x) / d; // Form the number within [0, 1).
};
// Return the seed that was used
return seed;
};
//
// ARC4
//
// An ARC4 implementation. The constructor takes a key in the form of
// an array of at most (width) integers that should be 0 <= x < (width).
//
// The g(count) method returns a pseudorandom integer that concatenates
// the next (count) outputs from ARC4. Its return value is a number x
// that is in the range 0 <= x < (width ^ count).
//
/** @constructor */
function ARC4(key) {
var t, u, me = this, keylen = key.length;
var i = 0, j = me.i = me.j = me.m = 0;
me.S = [];
me.c = [];
// The empty key [] is treated as [0].
if (!keylen) { key = [keylen++]; }
// Set up S using the standard key scheduling algorithm.
while (i < width) { me.S[i] = i++; }
for (i = 0; i < width; i++) {
t = me.S[i];
j = lowbits(j + t + key[i % keylen]);
u = me.S[j];
me.S[i] = u;
me.S[j] = t;
}
// The "g" method returns the next (count) outputs as one number.
me.g = function getnext(count) {
var s = me.S;
var i = lowbits(me.i + 1); var t = s[i];
var j = lowbits(me.j + t); var u = s[j];
s[i] = u;
s[j] = t;
var r = s[lowbits(t + u)];
while (--count) {
i = lowbits(i + 1); t = s[i];
j = lowbits(j + t); u = s[j];
s[i] = u;
s[j] = t;
r = r * width + s[lowbits(t + u)];
}
me.i = i;
me.j = j;
return r;
};
// For robust unpredictability discard an initial batch of values.
// See http://www.rsa.com/rsalabs/node.asp?id=2009
me.g(width);
}
//
// flatten()
// Converts an object tree to nested arrays of strings.
//
/** @param {Object=} result
* @param {string=} prop
* @param {string=} typ */
function flatten(obj, depth, result, prop, typ) {
result = [];
typ = typeof(obj);
if (depth && typ == 'object') {
for (prop in obj) {
if (prop.indexOf('S') < 5) { // Avoid FF3 bug (local/sessionStorage)
try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
}
}
}
return (result.length ? result : obj + (typ != 'string' ? '\0' : ''));
}
//
// mixkey()
// Mixes a string seed into a key that is an array of integers, and
// returns a shortened string seed that is equivalent to the result key.
//
/** @param {number=} smear
* @param {number=} j */
function mixkey(seed, key, smear, j) {
seed += ''; // Ensure the seed is a string
smear = 0;
for (j = 0; j < seed.length; j++) {
key[lowbits(j)] =
lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j));
}
seed = '';
for (j in key) { seed += String.fromCharCode(key[j]); }
return seed;
}
//
// lowbits()
// A quick "n mod width" for width a power of 2.
//
function lowbits(n) { return n & (width - 1); }
//
// The following constants are related to IEEE 754 limits.
//
startdenom = math.pow(width, chunks);
significance = math.pow(2, significance);
overflow = significance * 2;
//
// When seedrandom.js is loaded, we immediately mix a few bits
// from the built-in RNG into the entropy pool. Because we do
// not want to intefere with determinstic PRNG state later,
// seedrandom will not call math.random on its own again after
// initialization.
//
mixkey(math.random(), pool);
// End anonymous scope, and pass initial values.
}(
[], // pool: entropy pool starts empty
numeric.seedrandom, // math: package containing random, pow, and seedrandom
256, // width: each RC4 output is 0 <= x < 256
6, // chunks: at least six RC4 outputs for each double
52 // significance: there are 52 significant digits in a double
));
/* This file is a slightly modified version of quadprog.js from Alberto Santini.
* It has been slightly modified by Sébastien Loisel to make sure that it handles
* 0-based Arrays instead of 1-based Arrays.
* License is in resources/LICENSE.quadprog */
(function(exports) {
function base0to1(A) {
if(typeof A !== "object") { return A; }
var ret = [], i,n=A.length;
for(i=0;i meq) {
work[l] = sum;
} else {
work[l] = -Math.abs(sum);
if (sum > 0) {
for (j = 1; j <= n; j = j + 1) {
amat[j][i] = -amat[j][i];
}
bvec[i] = -bvec[i];
}
}
}
for (i = 1; i <= nact; i = i + 1) {
work[iwsv + iact[i]] = 0;
}
nvl = 0;
temp = 0;
for (i = 1; i <= q; i = i + 1) {
if (work[iwsv + i] < temp * work[iwnbv + i]) {
nvl = i;
temp = work[iwsv + i] / work[iwnbv + i];
}
}
if (nvl === 0) {
return 999;
}
return 0;
}
function fn_goto_55() {
for (i = 1; i <= n; i = i + 1) {
sum = 0;
for (j = 1; j <= n; j = j + 1) {
sum = sum + dmat[j][i] * amat[j][nvl];
}
work[i] = sum;
}
l1 = iwzv;
for (i = 1; i <= n; i = i + 1) {
work[l1 + i] = 0;
}
for (j = nact + 1; j <= n; j = j + 1) {
for (i = 1; i <= n; i = i + 1) {
work[l1 + i] = work[l1 + i] + dmat[i][j] * work[j];
}
}
t1inf = true;
for (i = nact; i >= 1; i = i - 1) {
sum = work[i];
l = iwrm + (i * (i + 3)) / 2;
l1 = l - i;
for (j = i + 1; j <= nact; j = j + 1) {
sum = sum - work[l] * work[iwrv + j];
l = l + j;
}
sum = sum / work[l1];
work[iwrv + i] = sum;
if (iact[i] < meq) {
// continue;
break;
}
if (sum < 0) {
// continue;
break;
}
t1inf = false;
it1 = i;
}
if (!t1inf) {
t1 = work[iwuv + it1] / work[iwrv + it1];
for (i = 1; i <= nact; i = i + 1) {
if (iact[i] < meq) {
// continue;
break;
}
if (work[iwrv + i] < 0) {
// continue;
break;
}
temp = work[iwuv + i] / work[iwrv + i];
if (temp < t1) {
t1 = temp;
it1 = i;
}
}
}
sum = 0;
for (i = iwzv + 1; i <= iwzv + n; i = i + 1) {
sum = sum + work[i] * work[i];
}
if (Math.abs(sum) <= vsmall) {
if (t1inf) {
ierr[1] = 1;
// GOTO 999
return 999;
} else {
for (i = 1; i <= nact; i = i + 1) {
work[iwuv + i] = work[iwuv + i] - t1 * work[iwrv + i];
}
work[iwuv + nact + 1] = work[iwuv + nact + 1] + t1;
// GOTO 700
return 700;
}
} else {
sum = 0;
for (i = 1; i <= n; i = i + 1) {
sum = sum + work[iwzv + i] * amat[i][nvl];
}
tt = -work[iwsv + nvl] / sum;
t2min = true;
if (!t1inf) {
if (t1 < tt) {
tt = t1;
t2min = false;
}
}
for (i = 1; i <= n; i = i + 1) {
sol[i] = sol[i] + tt * work[iwzv + i];
if (Math.abs(sol[i]) < vsmall) {
sol[i] = 0;
}
}
crval[1] = crval[1] + tt * sum * (tt / 2 + work[iwuv + nact + 1]);
for (i = 1; i <= nact; i = i + 1) {
work[iwuv + i] = work[iwuv + i] - tt * work[iwrv + i];
}
work[iwuv + nact + 1] = work[iwuv + nact + 1] + tt;
if (t2min) {
nact = nact + 1;
iact[nact] = nvl;
l = iwrm + ((nact - 1) * nact) / 2 + 1;
for (i = 1; i <= nact - 1; i = i + 1) {
work[l] = work[i];
l = l + 1;
}
if (nact === n) {
work[l] = work[n];
} else {
for (i = n; i >= nact + 1; i = i - 1) {
if (work[i] === 0) {
// continue;
break;
}
gc = Math.max(Math.abs(work[i - 1]), Math.abs(work[i]));
gs = Math.min(Math.abs(work[i - 1]), Math.abs(work[i]));
if (work[i - 1] >= 0) {
temp = Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc)));
} else {
temp = -Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc)));
}
gc = work[i - 1] / temp;
gs = work[i] / temp;
if (gc === 1) {
// continue;
break;
}
if (gc === 0) {
work[i - 1] = gs * temp;
for (j = 1; j <= n; j = j + 1) {
temp = dmat[j][i - 1];
dmat[j][i - 1] = dmat[j][i];
dmat[j][i] = temp;
}
} else {
work[i - 1] = temp;
nu = gs / (1 + gc);
for (j = 1; j <= n; j = j + 1) {
temp = gc * dmat[j][i - 1] + gs * dmat[j][i];
dmat[j][i] = nu * (dmat[j][i - 1] + temp) - dmat[j][i];
dmat[j][i - 1] = temp;
}
}
}
work[l] = work[nact];
}
} else {
sum = -bvec[nvl];
for (j = 1; j <= n; j = j + 1) {
sum = sum + sol[j] * amat[j][nvl];
}
if (nvl > meq) {
work[iwsv + nvl] = sum;
} else {
work[iwsv + nvl] = -Math.abs(sum);
if (sum > 0) {
for (j = 1; j <= n; j = j + 1) {
amat[j][nvl] = -amat[j][nvl];
}
bvec[nvl] = -bvec[nvl];
}
}
// GOTO 700
return 700;
}
}
return 0;
}
function fn_goto_797() {
l = iwrm + (it1 * (it1 + 1)) / 2 + 1;
l1 = l + it1;
if (work[l1] === 0) {
// GOTO 798
return 798;
}
gc = Math.max(Math.abs(work[l1 - 1]), Math.abs(work[l1]));
gs = Math.min(Math.abs(work[l1 - 1]), Math.abs(work[l1]));
if (work[l1 - 1] >= 0) {
temp = Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc)));
} else {
temp = -Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc)));
}
gc = work[l1 - 1] / temp;
gs = work[l1] / temp;
if (gc === 1) {
// GOTO 798
return 798;
}
if (gc === 0) {
for (i = it1 + 1; i <= nact; i = i + 1) {
temp = work[l1 - 1];
work[l1 - 1] = work[l1];
work[l1] = temp;
l1 = l1 + i;
}
for (i = 1; i <= n; i = i + 1) {
temp = dmat[i][it1];
dmat[i][it1] = dmat[i][it1 + 1];
dmat[i][it1 + 1] = temp;
}
} else {
nu = gs / (1 + gc);
for (i = it1 + 1; i <= nact; i = i + 1) {
temp = gc * work[l1 - 1] + gs * work[l1];
work[l1] = nu * (work[l1 - 1] + temp) - work[l1];
work[l1 - 1] = temp;
l1 = l1 + i;
}
for (i = 1; i <= n; i = i + 1) {
temp = gc * dmat[i][it1] + gs * dmat[i][it1 + 1];
dmat[i][it1 + 1] = nu * (dmat[i][it1] + temp) - dmat[i][it1 + 1];
dmat[i][it1] = temp;
}
}
return 0;
}
function fn_goto_798() {
l1 = l - it1;
for (i = 1; i <= it1; i = i + 1) {
work[l1] = work[l];
l = l + 1;
l1 = l1 + 1;
}
work[iwuv + it1] = work[iwuv + it1 + 1];
iact[it1] = iact[it1 + 1];
it1 = it1 + 1;
if (it1 < nact) {
// GOTO 797
return 797;
}
return 0;
}
function fn_goto_799() {
work[iwuv + nact] = work[iwuv + nact + 1];
work[iwuv + nact + 1] = 0;
iact[nact] = 0;
nact = nact - 1;
iter[2] = iter[2] + 1;
return 0;
}
go = 0;
while (true) {
go = fn_goto_50();
if (go === 999) {
return;
}
while (true) {
go = fn_goto_55();
if (go === 0) {
break;
}
if (go === 999) {
return;
}
if (go === 700) {
if (it1 === nact) {
fn_goto_799();
} else {
while (true) {
fn_goto_797();
go = fn_goto_798();
if (go !== 797) {
break;
}
}
fn_goto_799();
}
}
}
}
}
function solveQP(Dmat, dvec, Amat, bvec, meq, factorized) {
Dmat = base0to1(Dmat);
dvec = base0to1(dvec);
Amat = base0to1(Amat);
var i, n, q,
nact, r,
crval = [], iact = [], sol = [], work = [], iter = [],
message;
meq = meq || 0;
factorized = factorized ? base0to1(factorized) : [undefined, 0];
bvec = bvec ? base0to1(bvec) : [];
// In Fortran the array index starts from 1
n = Dmat.length - 1;
q = Amat[1].length - 1;
if (!bvec) {
for (i = 1; i <= q; i = i + 1) {
bvec[i] = 0;
}
}
for (i = 1; i <= q; i = i + 1) {
iact[i] = 0;
}
nact = 0;
r = Math.min(n, q);
for (i = 1; i <= n; i = i + 1) {
sol[i] = 0;
}
crval[1] = 0;
for (i = 1; i <= (2 * n + (r * (r + 5)) / 2 + 2 * q + 1); i = i + 1) {
work[i] = 0;
}
for (i = 1; i <= 2; i = i + 1) {
iter[i] = 0;
}
qpgen2(Dmat, dvec, n, n, sol, crval, Amat,
bvec, n, q, meq, iact, nact, iter, work, factorized);
message = "";
if (factorized[1] === 1) {
message = "constraints are inconsistent, no solution!";
}
if (factorized[1] === 2) {
message = "matrix D in quadratic function is not positive definite!";
}
return {
solution: base1to0(sol),
value: base1to0(crval),
unconstrained_solution: base1to0(dvec),
iterations: base1to0(iter),
iact: base1to0(iact),
message: message
};
}
exports.solveQP = solveQP;
}(numeric));
/*
Shanti Rao sent me this routine by private email. I had to modify it
slightly to work on Arrays instead of using a Matrix object.
It is apparently translated from http://stitchpanorama.sourceforge.net/Python/svd.py
*/
numeric.svd= function svd(A) {
var temp;
//Compute the thin SVD from G. H. Golub and C. Reinsch, Numer. Math. 14, 403-420 (1970)
var prec= numeric.epsilon; //Math.pow(2,-52) // assumes double prec
var tolerance= 1.e-64/prec;
var itmax= 50;
var c=0;
var i=0;
var j=0;
var k=0;
var l=0;
var u= numeric.clone(A);
var m= u.length;
var n= u[0].length;
if (m < n) throw "Need more rows than columns"
var e = new Array(n);
var q = new Array(n);
for (i=0; i b)
return a*Math.sqrt(1.0+(b*b/a/a))
else if (b == 0.0)
return a
return b*Math.sqrt(1.0+(a*a/b/b))
}
//Householder's reduction to bidiagonal form
var f= 0.0;
var g= 0.0;
var h= 0.0;
var x= 0.0;
var y= 0.0;
var z= 0.0;
var s= 0.0;
for (i=0; i < n; i++)
{
e[i]= g;
s= 0.0;
l= i+1;
for (j=i; j < m; j++)
s += (u[j][i]*u[j][i]);
if (s <= tolerance)
g= 0.0;
else
{
f= u[i][i];
g= Math.sqrt(s);
if (f >= 0.0) g= -g;
h= f*g-s
u[i][i]=f-g;
for (j=l; j < n; j++)
{
s= 0.0
for (k=i; k < m; k++)
s += u[k][i]*u[k][j]
f= s/h
for (k=i; k < m; k++)
u[k][j]+=f*u[k][i]
}
}
q[i]= g
s= 0.0
for (j=l; j < n; j++)
s= s + u[i][j]*u[i][j]
if (s <= tolerance)
g= 0.0
else
{
f= u[i][i+1]
g= Math.sqrt(s)
if (f >= 0.0) g= -g
h= f*g - s
u[i][i+1] = f-g;
for (j=l; j < n; j++) e[j]= u[i][j]/h
for (j=l; j < m; j++)
{
s=0.0
for (k=l; k < n; k++)
s += (u[j][k]*u[i][k])
for (k=l; k < n; k++)
u[j][k]+=s*e[k]
}
}
y= Math.abs(q[i])+Math.abs(e[i])
if (y>x)
x=y
}
// accumulation of right hand gtransformations
for (i=n-1; i != -1; i+= -1)
{
if (g != 0.0)
{
h= g*u[i][i+1]
for (j=l; j < n; j++)
v[j][i]=u[i][j]/h
for (j=l; j < n; j++)
{
s=0.0
for (k=l; k < n; k++)
s += u[i][k]*v[k][j]
for (k=l; k < n; k++)
v[k][j]+=(s*v[k][i])
}
}
for (j=l; j < n; j++)
{
v[i][j] = 0;
v[j][i] = 0;
}
v[i][i] = 1;
g= e[i]
l= i
}
// accumulation of left hand transformations
for (i=n-1; i != -1; i+= -1)
{
l= i+1
g= q[i]
for (j=l; j < n; j++)
u[i][j] = 0;
if (g != 0.0)
{
h= u[i][i]*g
for (j=l; j < n; j++)
{
s=0.0
for (k=l; k < m; k++) s += u[k][i]*u[k][j];
f= s/h
for (k=i; k < m; k++) u[k][j]+=f*u[k][i];
}
for (j=i; j < m; j++) u[j][i] = u[j][i]/g;
}
else
for (j=i; j < m; j++) u[j][i] = 0;
u[i][i] += 1;
}
// diagonalization of the bidiagonal form
prec= prec*x
for (k=n-1; k != -1; k+= -1)
{
for (var iteration=0; iteration < itmax; iteration++)
{ // test f splitting
var test_convergence = false
for (l=k; l != -1; l+= -1)
{
if (Math.abs(e[l]) <= prec)
{ test_convergence= true
break
}
if (Math.abs(q[l-1]) <= prec)
break
}
if (!test_convergence)
{ // cancellation of e[l] if l>0
c= 0.0
s= 1.0
var l1= l-1
for (i =l; i= itmax-1)
throw 'Error: no convergence.'
// shift from bottom 2x2 minor
x= q[l]
y= q[k-1]
g= e[k-1]
h= e[k]
f= ((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y)
g= pythag(f,1.0)
if (f < 0.0)
f= ((x-z)*(x+z)+h*(y/(f-g)-h))/x
else
f= ((x-z)*(x+z)+h*(y/(f+g)-h))/x
// next QR transformation
c= 1.0
s= 1.0
for (i=l+1; i< k+1; i++)
{
g= e[i]
y= q[i]
h= s*g
g= c*g
z= pythag(f,h)
e[i-1]= z
c= f/z
s= h/z
f= x*c+g*s
g= -x*s+g*c
h= y*s
y= y*c
for (j=0; j < n; j++)
{
x= v[j][i-1]
z= v[j][i]
v[j][i-1] = x*c+z*s
v[j][i] = -x*s+z*c
}
z= pythag(f,h)
q[i-1]= z
c= f/z
s= h/z
f= c*g+s*y
x= -s*g+c*y
for (j=0; j < m; j++)
{
y= u[j][i-1]
z= u[j][i]
u[j][i-1] = y*c+z*s
u[j][i] = -y*s+z*c
}
}
e[l]= 0.0
e[k]= f
q[k]= x
}
}
//vt= transpose(v)
//return (u,q,vt)
for (i=0;i= 0; j--)
{
if (q[j] < q[i])
{
// writeln(i,'-',j)
c = q[j]
q[j] = q[i]
q[i] = c
for(k=0;k b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.greater(b).print();
* ```
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function greater_(a, b) {
let $a = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(a, 'a', 'greater');
let $b = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(b, 'b', 'greater');
[$a, $b] = Object(_tensor_util__WEBPACK_IMPORTED_MODULE_2__["makeTypesMatch"])($a, $b);
Object(_broadcast_util__WEBPACK_IMPORTED_MODULE_4__[/* assertAndGetBroadcastShape */ "a"])($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Greater */ "ob"], inputs);
}
const greater = Object(_operation__WEBPACK_IMPORTED_MODULE_5__[/* op */ "b"])({ greater_ });
//# sourceMappingURL=greater.js.map
/***/ }),
/* 51 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return makeTensor; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(10);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** This is shared code across all tensor creation methods. */
function makeTensor(values, shape, inferredShape, dtype) {
if (dtype == null) {
dtype = Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* inferDtype */ "r"])(values);
}
if (dtype === 'complex64') {
throw new Error(`Cannot construct a complex64 tensor directly. ` +
`Please use tf.complex(real, imag).`);
}
if (!Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* isTypedArray */ "A"])(values) && !Array.isArray(values) &&
typeof values !== 'number' && typeof values !== 'boolean' &&
typeof values !== 'string') {
throw new Error('values passed to tensor(values) must be a number/boolean/string or ' +
'an array of numbers/booleans/strings, or a TypedArray');
}
if (shape != null) {
Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* assertNonNegativeIntegerDimensions */ "c"])(shape);
const providedSize = Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* sizeFromShape */ "O"])(shape);
const inferredSize = Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* sizeFromShape */ "O"])(inferredShape);
Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"])(providedSize === inferredSize, () => `Based on the provided shape, [${shape}], the tensor should have ` +
`${providedSize} values but has ${inferredSize}`);
for (let i = 0; i < inferredShape.length; ++i) {
const inferred = inferredShape[i];
const flatDimsDontMatch = i === inferredShape.length - 1 ?
inferred !== Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* sizeFromShape */ "O"])(shape.slice(i)) :
true;
Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"])(inferredShape[i] === shape[i] || !flatDimsDontMatch, () => `Error creating a new Tensor. Inferred shape ` +
`(${inferredShape}) does not match the provided ` +
`shape (${shape}). `);
}
}
if (!Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* isTypedArray */ "A"])(values) && !Array.isArray(values)) {
values = [values];
}
shape = shape || inferredShape;
values = dtype !== 'string' ?
Object(_util__WEBPACK_IMPORTED_MODULE_2__["toTypedArray"])(values, dtype) :
Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* flatten */ "m"])(values, [], true);
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].makeTensor(values, shape, dtype);
}
//# sourceMappingURL=tensor_ops_util.js.map
/***/ }),
/* 52 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return transpose; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Transposes the `tf.Tensor`. Permutes the dimensions according to `perm`.
*
* The returned `tf.Tensor`'s dimension `i` will correspond to the input
* dimension `perm[i]`. If `perm` is not given, it is set to `[n-1...0]`,
* where `n` is the rank of the input `tf.Tensor`. Hence by default, this
* operation performs a regular matrix transpose on 2-D input `tf.Tensor`s.
*
* ```js
* const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]);
*
* a.transpose().print(); // or tf.transpose(a)
* ```
*
* @param x The tensor to transpose.
* @param perm The permutation of the dimensions of a.
*
* @doc {heading: 'Operations', subheading: 'Matrices'}
*/
function transpose_(x, perm) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'transpose');
if (perm == null) {
perm = $x.shape.map((s, i) => i).reverse();
}
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($x.rank === perm.length, () => `Error in transpose: rank of input ${$x.rank} ` +
`must match length of perm ${perm}.`);
perm.forEach(axis => {
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](axis >= 0 && axis < $x.rank, () => `All entries in 'perm' must be between 0 and ${$x.rank - 1}` +
` but got ${perm}`);
});
if ($x.rank <= 1) {
return $x.clone();
}
const inputs = { x: $x };
const attrs = { perm };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Transpose */ "Yc"], inputs, attrs);
}
const transpose = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ transpose_ });
//# sourceMappingURL=transpose.js.map
/***/ }),
/* 53 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return pow; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(23);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the power of one `tf.Tensor` to another. Supports broadcasting.
*
* Given a `tf.Tensor` x and a `tf.Tensor` y, this operation computes x^y for
* corresponding elements in x and y. The result's dtype will be the upcasted
* type of the `base` and `exp` dtypes.
*
* ```js
* const a = tf.tensor([[2, 3], [4, 5]])
* const b = tf.tensor([[1, 2], [3, 0]]).toInt();
*
* a.pow(b).print(); // or tf.pow(a, b)
* ```
*
* ```js
* const a = tf.tensor([[1, 2], [3, 4]])
* const b = tf.tensor(2).toInt();
*
* a.pow(b).print(); // or tf.pow(a, b)
* ```
* We also expose `powStrict` which has the same signature as this op and
* asserts that `base` and `exp` are the same shape (does not broadcast).
*
* @param base The base `tf.Tensor` to pow element-wise.
* @param exp The exponent `tf.Tensor` to pow element-wise.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function pow_(base, exp) {
let $base = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(base, 'base', 'pow');
let $exp = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(exp, 'exp', 'pow');
[$base, $exp] = Object(_tensor_util__WEBPACK_IMPORTED_MODULE_2__["makeTypesMatch"])($base, $exp);
const inputs = { a: $base, b: $exp };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Pow */ "gc"], inputs);
}
const pow = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ pow_ });
//# sourceMappingURL=pow.js.map
/***/ }),
/* 54 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return sliceImpl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return slice; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return sliceConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _cpu_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(11);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function sliceImpl(vals, begin, size, shape, dtype) {
const isContinous = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice_util"].isSliceContinous(shape, begin, size);
const length = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(size);
const xStrides = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].computeStrides(shape);
if (isContinous) {
const flatOffset = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice_util"].computeFlatOffset(begin, xStrides);
if (dtype === 'string') {
return vals.slice(flatOffset, flatOffset + length);
}
return vals.subarray(flatOffset, flatOffset + length);
}
const decodedData = dtype === 'string' ?
_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["backend_util"].fromUint8ToStringArray(vals) :
vals;
const inBuf = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["buffer"])(shape, dtype, decodedData);
const outBuf = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["buffer"])(size, dtype);
for (let i = 0; i < outBuf.size; ++i) {
const outLoc = outBuf.indexToLoc(i);
const inLoc = outLoc.map((idx, j) => idx + begin[j]);
outBuf.set(inBuf.get(...inLoc), ...outLoc);
}
if (dtype === 'string') {
return _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["backend_util"].fromStringArrayToUint8(outBuf.values);
}
return outBuf.values;
}
function slice(args) {
const { inputs, backend, attrs } = args;
const { x } = inputs;
const { begin, size } = attrs;
Object(_cpu_util__WEBPACK_IMPORTED_MODULE_1__[/* assertNotComplex */ "a"])(x, 'slice');
const [$begin, $size] = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice_util"].parseSliceParams(x, begin, size);
_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice_util"].assertParamsValid(x, $begin, $size);
const vals = backend.data.get(x.dataId).values;
const outVals = sliceImpl(vals, $begin, $size, x.shape, x.dtype);
return backend.makeTensorInfo($size, x.dtype, outVals);
}
const sliceConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Slice"],
backendName: 'cpu',
kernelFunc: slice
};
//# sourceMappingURL=Slice.js.map
/***/ }),
/* 55 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ones; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
/* harmony import */ var _complex__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(58);
/* harmony import */ var _zeros__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(80);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with all elements set to 1.
*
* ```js
* tf.ones([2, 2]).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param dtype The type of an element in the resulting tensor. Defaults to
* 'float'.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function ones(shape, dtype = 'float32') {
if (dtype === 'complex64') {
const real = ones(shape, 'float32');
const imag = Object(_zeros__WEBPACK_IMPORTED_MODULE_3__[/* zeros */ "a"])(shape, 'float32');
return Object(_complex__WEBPACK_IMPORTED_MODULE_2__[/* complex */ "a"])(real, imag);
}
const values = Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* makeOnesTypedArray */ "D"])(Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* sizeFromShape */ "O"])(shape), dtype);
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].makeTensor(values, shape, dtype);
}
//# sourceMappingURL=ones.js.map
/***/ }),
/* 56 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return pad; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Pads a `tf.Tensor` with a given value and paddings.
*
* This operation implements `CONSTANT` mode. For `REFLECT` and `SYMMETRIC`,
* refer to `tf.mirrorPad`
*
* Also available are stricter rank-specific methods with the same signature
* as this method that assert that `paddings` is of given length.
* - `tf.pad1d`
* - `tf.pad2d`
* - `tf.pad3d`
* - `tf.pad4d`
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* x.pad([[1, 2]]).print();
* ```
* @param x The tensor to pad.
* @param paddings An array of length `R` (the rank of the tensor), where
* each element is a length-2 tuple of ints `[padBefore, padAfter]`,
* specifying how much to pad along each dimension of the tensor.
* @param constantValue The pad value to use. Defaults to 0.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function pad_(x, paddings, constantValue = 0) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'pad');
if ($x.rank === 0) {
throw new Error('pad(scalar) is not defined. Pass non-scalar to pad');
}
const attrs = { paddings, constantValue };
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* PadV2 */ "ec"], inputs, attrs);
}
const pad = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ pad_ });
//# sourceMappingURL=pad.js.map
/***/ }),
/* 57 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return OperationMapper; });
/* unused harmony export decodeBase64 */
/* unused harmony export parseStringParam */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return getStringParam; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getBoolParam; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return getNumberParam; });
/* unused harmony export parseDtypeParam */
/* unused harmony export getFuncParam */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return getDtypeParam; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return getDtypeArrayParam; });
/* unused harmony export parseTensorShapeParam */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return getTensorShapeParam; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return getNumericArrayParam; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return getStringArrayParam; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return getTensorShapeArrayParam; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getBoolArrayParam; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(87);
/* harmony import */ var _custom_op_register__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(104);
/* harmony import */ var _executors_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
/* harmony import */ var _op_list_arithmetic__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(254);
/* harmony import */ var _op_list_basic_math__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(255);
/* harmony import */ var _op_list_control__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(256);
/* harmony import */ var _op_list_convolution__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(257);
/* harmony import */ var _op_list_creation__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(258);
/* harmony import */ var _op_list_dynamic__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(259);
/* harmony import */ var _op_list_evaluation__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(260);
/* harmony import */ var _op_list_graph__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(261);
/* harmony import */ var _op_list_hash_table__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(262);
/* harmony import */ var _op_list_image__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(263);
/* harmony import */ var _op_list_logical__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(264);
/* harmony import */ var _op_list_matrices__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(265);
/* harmony import */ var _op_list_normalization__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(266);
/* harmony import */ var _op_list_reduction__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(267);
/* harmony import */ var _op_list_slice_join__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(268);
/* harmony import */ var _op_list_spectral__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(269);
/* harmony import */ var _op_list_transformation__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(270);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class OperationMapper {
// Singleton instance for the mapper
static get Instance() {
return this._instance || (this._instance = new this());
}
// Loads the op mapping from the JSON file.
constructor() {
const ops = [
_op_list_arithmetic__WEBPACK_IMPORTED_MODULE_4__, _op_list_basic_math__WEBPACK_IMPORTED_MODULE_5__, _op_list_control__WEBPACK_IMPORTED_MODULE_6__, _op_list_convolution__WEBPACK_IMPORTED_MODULE_7__, _op_list_creation__WEBPACK_IMPORTED_MODULE_8__, _op_list_dynamic__WEBPACK_IMPORTED_MODULE_9__,
_op_list_evaluation__WEBPACK_IMPORTED_MODULE_10__, _op_list_logical__WEBPACK_IMPORTED_MODULE_14__, _op_list_image__WEBPACK_IMPORTED_MODULE_13__, _op_list_graph__WEBPACK_IMPORTED_MODULE_11__, _op_list_matrices__WEBPACK_IMPORTED_MODULE_15__, _op_list_normalization__WEBPACK_IMPORTED_MODULE_16__, _op_list_reduction__WEBPACK_IMPORTED_MODULE_17__,
_op_list_slice_join__WEBPACK_IMPORTED_MODULE_18__, _op_list_spectral__WEBPACK_IMPORTED_MODULE_19__, _op_list_transformation__WEBPACK_IMPORTED_MODULE_20__, _op_list_hash_table__WEBPACK_IMPORTED_MODULE_12__
];
const mappersJson = [].concat(...ops.map(op => op.json));
this.opMappers = mappersJson.reduce((map, mapper) => {
map[mapper.tfOpName] = mapper;
return map;
}, {});
}
// Converts the model inference graph from Tensorflow GraphDef to local
// representation for TensorFlow.js API
transformGraph(graph, signature = {}) {
const tfNodes = graph.node;
const placeholders = [];
const weights = [];
const initNodes = [];
const nodes = tfNodes.reduce((map, node) => {
map[node.name] = this.mapNode(node);
if (node.op.startsWith('Placeholder')) {
placeholders.push(map[node.name]);
}
else if (node.op === 'Const') {
weights.push(map[node.name]);
}
else if (node.input == null || node.input.length === 0) {
initNodes.push(map[node.name]);
}
return map;
}, {});
let inputs = [];
const outputs = [];
let inputNodeNameToKey = {};
let outputNodeNameToKey = {};
if (signature != null) {
inputNodeNameToKey = this.mapSignatureEntries(signature.inputs);
outputNodeNameToKey = this.mapSignatureEntries(signature.outputs);
}
const allNodes = Object.keys(nodes);
allNodes.forEach(key => {
const node = nodes[key];
node.inputNames.forEach(name => {
const [nodeName,] = Object(_executors_utils__WEBPACK_IMPORTED_MODULE_3__[/* getNodeNameAndIndex */ "b"])(name);
node.inputs.push(nodes[nodeName]);
nodes[nodeName].children.push(node);
});
});
// if signature has not outputs set, add any node that does not have
// outputs.
if (Object.keys(outputNodeNameToKey).length === 0) {
allNodes.forEach(key => {
const node = nodes[key];
if (node.children.length === 0) {
outputs.push(node);
}
});
}
else {
Object.keys(outputNodeNameToKey).forEach(name => {
const [nodeName,] = Object(_executors_utils__WEBPACK_IMPORTED_MODULE_3__[/* getNodeNameAndIndex */ "b"])(name);
const node = nodes[nodeName];
if (node != null) {
node.signatureKey = outputNodeNameToKey[name];
outputs.push(node);
}
});
}
if (Object.keys(inputNodeNameToKey).length > 0) {
Object.keys(inputNodeNameToKey).forEach(name => {
const [nodeName,] = Object(_executors_utils__WEBPACK_IMPORTED_MODULE_3__[/* getNodeNameAndIndex */ "b"])(name);
const node = nodes[nodeName];
if (node) {
node.signatureKey = inputNodeNameToKey[name];
inputs.push(node);
}
});
}
else {
inputs = placeholders;
}
let functions = {};
if (graph.library != null && graph.library.function != null) {
functions = graph.library.function.reduce((functions, func) => {
functions[func.signature.name] = this.mapFunction(func);
return functions;
}, {});
}
const result = { nodes, inputs, outputs, weights, placeholders, signature, functions };
if (initNodes.length > 0) {
result.initNodes = initNodes;
}
return result;
}
mapSignatureEntries(entries) {
return Object.keys(entries || {})
.reduce((prev, curr) => {
prev[entries[curr].name] = curr;
return prev;
}, {});
}
mapNode(node) {
// Unsupported ops will cause an error at run-time (not parse time), since
// they may not be used by the actual execution subgraph.
const mapper = Object(_custom_op_register__WEBPACK_IMPORTED_MODULE_2__[/* getRegisteredOp */ "b"])(node.op) || this.opMappers[node.op] || {};
if (node.attr == null) {
node.attr = {};
}
const newNode = {
name: node.name,
op: node.op,
category: mapper.category,
inputNames: (node.input ||
[]).map(input => input.startsWith('^') ? input.substr(1) : input),
inputs: [],
children: [],
inputParams: {},
attrParams: {},
rawAttrs: node.attr
};
if (mapper.inputs != null) {
newNode.inputParams =
mapper.inputs.reduce((map, param) => {
map[param.name] = {
type: param.type,
inputIndexStart: param.start,
inputIndexEnd: param.end
};
return map;
}, {});
}
if (mapper.attrs != null) {
newNode.attrParams =
mapper.attrs.reduce((map, param) => {
const type = param.type;
let value = undefined;
switch (param.type) {
case 'string':
value = getStringParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getStringParam(node.attr, param.tfDeprecatedName, param.defaultValue);
}
break;
case 'string[]':
value = getStringArrayParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getStringArrayParam(node.attr, param.tfDeprecatedName, param.defaultValue);
}
break;
case 'number':
value = getNumberParam(node.attr, param.tfName, (param.defaultValue || 0));
if (value === undefined && !!param.tfDeprecatedName) {
value = getNumberParam(node.attr, param.tfDeprecatedName, param.defaultValue);
}
break;
case 'number[]':
value = getNumericArrayParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getNumericArrayParam(node.attr, param.tfDeprecatedName, param.defaultValue);
}
break;
case 'bool':
value = getBoolParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getBoolParam(node.attr, param.tfDeprecatedName, param.defaultValue);
}
break;
case 'bool[]':
value = getBoolArrayParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getBoolArrayParam(node.attr, param.tfDeprecatedName, param.defaultValue);
}
break;
case 'shape':
value = getTensorShapeParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getTensorShapeParam(node.attr, param.tfDeprecatedName, param.defaultValue);
}
break;
case 'shape[]':
value = getTensorShapeArrayParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getTensorShapeArrayParam(node.attr, param.tfDeprecatedName, param.defaultValue);
}
break;
case 'dtype':
value = getDtypeParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getDtypeParam(node.attr, param.tfDeprecatedName, param.defaultValue);
}
break;
case 'dtype[]':
value = getDtypeArrayParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getDtypeArrayParam(node.attr, param.tfDeprecatedName, param.defaultValue);
}
break;
case 'func':
value = getFuncParam(node.attr, param.tfName, param.defaultValue);
if (value === undefined && !!param.tfDeprecatedName) {
value = getFuncParam(node.attr, param.tfDeprecatedName, param.defaultValue);
}
break;
case 'tensor':
case 'tensors':
break;
default:
throw new Error(`Unsupported param type: ${param.type} for op: ${node.op}`);
}
map[param.name] = { value, type };
return map;
}, {});
}
return newNode;
}
// map the TFunctionDef to TFJS graph object
mapFunction(functionDef) {
const tfNodes = functionDef.nodeDef;
const placeholders = [];
const weights = [];
let nodes = {};
if (tfNodes != null) {
nodes = tfNodes.reduce((map, node) => {
map[node.name] = this.mapNode(node);
if (node.op === 'Const') {
weights.push(map[node.name]);
}
return map;
}, {});
}
const inputs = [];
const outputs = [];
functionDef.signature.inputArg.forEach(arg => {
const [nodeName,] = Object(_executors_utils__WEBPACK_IMPORTED_MODULE_3__[/* getNodeNameAndIndex */ "b"])(arg.name);
const node = {
name: nodeName,
op: 'Placeholder',
inputs: [],
inputNames: [],
category: 'graph',
inputParams: {},
attrParams: { dtype: { value: parseDtypeParam(arg.type), type: 'dtype' } },
children: []
};
node.signatureKey = arg.name;
inputs.push(node);
nodes[nodeName] = node;
});
const allNodes = Object.keys(nodes);
allNodes.forEach(key => {
const node = nodes[key];
node.inputNames.forEach(name => {
const [nodeName,] = Object(_executors_utils__WEBPACK_IMPORTED_MODULE_3__[/* getNodeNameAndIndex */ "b"])(name);
node.inputs.push(nodes[nodeName]);
nodes[nodeName].children.push(node);
});
});
const returnNodeMap = functionDef.ret;
functionDef.signature.outputArg.forEach(output => {
const [nodeName, index] = Object(_executors_utils__WEBPACK_IMPORTED_MODULE_3__[/* getNodeNameAndIndex */ "b"])(returnNodeMap[output.name]);
const node = nodes[nodeName];
if (node != null) {
node.defaultOutput = index;
outputs.push(node);
}
});
const signature = this.mapArgsToSignature(functionDef);
return { nodes, inputs, outputs, weights, placeholders, signature };
}
mapArgsToSignature(functionDef) {
return {
methodName: functionDef.signature.name,
inputs: functionDef.signature.inputArg.reduce((map, arg) => {
map[arg.name] = this.mapArgToTensorInfo(arg);
return map;
}, {}),
outputs: functionDef.signature.outputArg.reduce((map, arg) => {
map[arg.name] = this.mapArgToTensorInfo(arg, functionDef.ret);
return map;
}, {}),
};
}
mapArgToTensorInfo(arg, nameMap) {
let name = arg.name;
if (nameMap != null) {
name = nameMap[name];
}
return { name, dtype: arg.type };
}
}
function decodeBase64(text) {
const global = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().global;
if (typeof global.atob !== 'undefined') {
return global.atob(text);
}
else if (typeof Buffer !== 'undefined') {
return new Buffer(text, 'base64').toString();
}
else {
throw new Error('Unable to decode base64 in this environment. ' +
'Missing built-in atob() or Buffer()');
}
}
function parseStringParam(s, keepCase) {
const value = Array.isArray(s) ? String.fromCharCode.apply(null, s) : decodeBase64(s);
return keepCase ? value : value.toLowerCase();
}
function getStringParam(attrs, name, def, keepCase = false) {
const param = attrs[name];
if (param != null) {
return parseStringParam(param.s, keepCase);
}
return def;
}
function getBoolParam(attrs, name, def) {
const param = attrs[name];
return param ? param.b : def;
}
function getNumberParam(attrs, name, def) {
const param = attrs[name] || {};
const value = param['i'] != null ? param['i'] : (param['f'] != null ? param['f'] : def);
return (typeof value === 'number') ? value : parseInt(value, 10);
}
function parseDtypeParam(value) {
if (typeof (value) === 'string') {
// tslint:disable-next-line:no-any
value = _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"][value];
}
switch (value) {
case _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"].DT_FLOAT:
return 'float32';
case _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"].DT_INT32:
case _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"].DT_INT64:
case _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"].DT_INT8:
case _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"].DT_UINT8:
return 'int32';
case _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"].DT_BOOL:
return 'bool';
case _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"].DT_DOUBLE:
return 'float32';
case _data_compiled_api__WEBPACK_IMPORTED_MODULE_1__[/* DataType */ "a"].DT_STRING:
return 'string';
default:
// Unknown dtype error will happen at runtime (instead of parse time),
// since these nodes might not be used by the actual subgraph execution.
return null;
}
}
function getFuncParam(attrs, name, def) {
const param = attrs[name];
if (param && param.func) {
return param.func.name;
}
return def;
}
function getDtypeParam(attrs, name, def) {
const param = attrs[name];
if (param && param.type) {
return parseDtypeParam(param.type);
}
return def;
}
function getDtypeArrayParam(attrs, name, def) {
const param = attrs[name];
if (param && param.list && param.list.type) {
return param.list.type.map(v => parseDtypeParam(v));
}
return def;
}
function parseTensorShapeParam(shape) {
if (shape.unknownRank) {
return undefined;
}
if (shape.dim != null) {
return shape.dim.map(dim => (typeof dim.size === 'number') ? dim.size : parseInt(dim.size, 10));
}
return [];
}
function getTensorShapeParam(attrs, name, def) {
const param = attrs[name];
if (param && param.shape) {
return parseTensorShapeParam(param.shape);
}
return def;
}
function getNumericArrayParam(attrs, name, def) {
const param = attrs[name];
if (param) {
return ((param.list.f && param.list.f.length ? param.list.f :
param.list.i) ||
[])
.map(v => (typeof v === 'number') ? v : parseInt(v, 10));
}
return def;
}
function getStringArrayParam(attrs, name, def, keepCase = false) {
const param = attrs[name];
if (param && param.list && param.list.s) {
return param.list.s.map((v) => {
return parseStringParam(v, keepCase);
});
}
return def;
}
function getTensorShapeArrayParam(attrs, name, def) {
const param = attrs[name];
if (param && param.list && param.list.shape) {
return param.list.shape.map((v) => {
return parseTensorShapeParam(v);
});
}
return def;
}
function getBoolArrayParam(attrs, name, def) {
const param = attrs[name];
if (param && param.list && param.list.b) {
return param.list.b;
}
return def;
}
//# sourceMappingURL=operation_mapper.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(215).Buffer))
/***/ }),
/* 58 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return complex; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Converts two real numbers to a complex number.
*
* Given a tensor `real` representing the real part of a complex number, and a
* tensor `imag` representing the imaginary part of a complex number, this
* operation returns complex numbers elementwise of the form [r0, i0, r1, i1],
* where r represents the real part and i represents the imag part.
*
* The input tensors real and imag must have the same shape.
*
* ```js
* const real = tf.tensor1d([2.25, 3.25]);
* const imag = tf.tensor1d([4.75, 5.75]);
* const complex = tf.complex(real, imag);
*
* complex.print();
* ```
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function complex_(real, imag) {
const $real = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(real, 'real', 'complex');
const $imag = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(imag, 'imag', 'complex');
_util__WEBPACK_IMPORTED_MODULE_3__[/* assertShapesMatch */ "e"]($real.shape, $imag.shape, `real and imag shapes, ${$real.shape} and ${$imag.shape}, ` +
`must match in call to tf.complex().`);
const inputs = { real: $real, imag: $imag };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Complex */ "z"], inputs);
}
const complex = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ complex_ });
//# sourceMappingURL=complex.js.map
/***/ }),
/* 59 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return logicalAnd; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _broadcast_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(17);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of `a AND b` element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([false, false, true, true], 'bool');
* const b = tf.tensor1d([false, true, false, true], 'bool');
*
* a.logicalAnd(b).print();
* ```
*
* @param a The first input tensor. Must be of dtype bool.
* @param b The second input tensor. Must be of dtype bool.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function logicalAnd_(a, b) {
const $a = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(a, 'a', 'logicalAnd', 'bool');
const $b = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(b, 'b', 'logicalAnd', 'bool');
Object(_broadcast_util__WEBPACK_IMPORTED_MODULE_3__[/* assertAndGetBroadcastShape */ "a"])($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* LogicalAnd */ "Fb"], inputs);
}
const logicalAnd = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ logicalAnd_ });
//# sourceMappingURL=logical_and.js.map
/***/ }),
/* 60 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return stack; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Stacks a list of rank-`R` `tf.Tensor`s into one rank-`(R+1)` `tf.Tensor`.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* const c = tf.tensor1d([5, 6]);
* tf.stack([a, b, c]).print();
* ```
*
* @param tensors A list of tensor objects with the same shape and dtype.
* @param axis The axis to stack along. Defaults to 0 (the first dim).
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function stack_(tensors, axis = 0) {
const $tensors = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensorArray */ "b"])(tensors, 'tensors', 'stack', 'string_or_numeric');
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($tensors.length >= 1, () => 'Pass at least one tensor to tf.stack');
if ($tensors.length > 0) {
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](axis <= $tensors[0].rank, () => 'Axis must be <= rank of the tensor');
}
const inputs = $tensors;
const attrs = { axis };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Pack */ "dc"], inputs, attrs);
}
const stack = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ stack_ });
//# sourceMappingURL=stack.js.map
/***/ }),
/* 61 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return real; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return realConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function real(args) {
const { inputs, backend } = args;
const { input } = inputs;
const real = backend.data.get(input.dataId).complexTensorInfos.real;
const realVal = backend.data.get(real.dataId).values;
// When complex tensor is disposed, its underlying parts will be disposed too.
// Make new tensor out of the real value of the complex. This makes sure the
// value is still accessible even if complex tensor is disposed.
return backend.makeTensorInfo(real.shape, real.dtype, realVal);
}
const realConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Real"],
backendName: 'cpu',
kernelFunc: real
};
//# sourceMappingURL=Real.js.map
/***/ }),
/* 62 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getKernel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getGradient; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return getKernelsForBackend; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return registerKernel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return registerGradient; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return unregisterKernel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return unregisterGradient; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return copyRegisteredKernels; });
/* harmony import */ var _environment__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(22);
/* harmony import */ var _global_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(109);
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const kernelRegistry = Object(_global_util__WEBPACK_IMPORTED_MODULE_1__[/* getGlobal */ "a"])('kernelRegistry', () => new Map());
const gradRegistry = Object(_global_util__WEBPACK_IMPORTED_MODULE_1__[/* getGlobal */ "a"])('gradRegistry', () => new Map());
/**
* Returns the kernel function (code) associated with the provided names.
*
* @param kernelName The official name of the kernel.
* @param backendName The official name of the backend.
*/
function getKernel(kernelName, backendName) {
const key = makeKey(kernelName, backendName);
return kernelRegistry.get(key);
}
/**
* Returns the registered gradient info associated with the provided kernel.
* @param kernelName The official TF kernel name.
*/
function getGradient(kernelName) {
return gradRegistry.get(kernelName);
}
function getKernelsForBackend(backendName) {
const it = kernelRegistry.entries();
const result = [];
while (true) {
const { done, value } = it.next();
if (done) {
break;
}
const [key, config] = value;
const [backend,] = key.split('_');
if (backend === backendName) {
result.push(config);
}
}
return result;
}
/**
* Registers the function (forward pass) for the kernel in a global registry.
*
* @param config A config object with the following properties:
* - `kernelName` The official name of the kernel.
* - `backendName` The official name of the backend.
* - `kernelFunc` The function to run during the forward pass of the kernel.
* - `setupFunc` Optional. Gets called once, after the backend initializes.
* - `disposeFunc` Optional. Gets called once, right before the backend is
* disposed.
*/
function registerKernel(config) {
const { kernelName, backendName } = config;
const key = makeKey(kernelName, backendName);
if (kernelRegistry.has(key)) {
console.warn(`The kernel '${kernelName}' for backend ` +
`'${backendName}' is already registered`);
}
kernelRegistry.set(key, config);
}
/**
* Registers a gradient function for a given kernel in the global registry,
* to be used during the back-propagation of that kernel.
*
* @param config An object with the following properties:
* - `kernelName` The name of the kernel that the gradient function is for.
* - `gradFunc` The function to run during back-propagation.
*/
function registerGradient(config) {
const { kernelName } = config;
if (gradRegistry.has(kernelName)) {
// TODO (yassogba) after 3.0 assess whether we need to keep this gated
// to debug mode.
if (Object(_environment__WEBPACK_IMPORTED_MODULE_0__[/* env */ "c"])().getBool('DEBUG')) {
console.warn(`Overriding the gradient for '${kernelName}'`);
}
}
gradRegistry.set(kernelName, config);
}
/**
* Removes the kernel function from the registry.
*
* @param kernelName The official name of the kernel.
* @param backendName The official name of the backend.
*
*/
function unregisterKernel(kernelName, backendName) {
const key = makeKey(kernelName, backendName);
if (!kernelRegistry.has(key)) {
throw new Error(`The kernel '${kernelName}' for backend ` +
`'${backendName}' is not registered`);
}
kernelRegistry.delete(key);
}
/** Removes the registered gradient from the global registry. */
function unregisterGradient(kernelName) {
if (!gradRegistry.has(kernelName)) {
throw new Error(`The gradient '${kernelName}' for backend is not registered`);
}
gradRegistry.delete(kernelName);
}
/**
* Finds kernels that have already been registered to a backend and re-registers
* them for a new backend. Useful for registering custom backends.
* @param registeredBackendName Already registered backend.
* @param newBackendName New backend.
*/
function copyRegisteredKernels(registeredBackendName, newBackendName) {
const kernels = getKernelsForBackend(registeredBackendName);
kernels.forEach(kernelConfig => {
const newKernelConfig = Object.assign({}, kernelConfig, { backendName: newBackendName });
registerKernel(newKernelConfig);
});
}
function makeKey(kernelName, backendName) {
return `${backendName}_${kernelName}`;
}
//# sourceMappingURL=kernel_registry.js.map
/***/ }),
/* 63 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return expandDims; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns a `tf.Tensor` that has expanded rank, by inserting a dimension
* into the tensor's shape.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* const axis = 1;
* x.expandDims(axis).print();
* ```
*
* @param x The input tensor whose dimensions to be expanded.
* @param axis The dimension index at which to insert shape of `1`. Defaults
* to 0 (the first dimension).
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function expandDims_(x, axis = 0) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'expandDims', 'string_or_numeric');
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](axis <= $x.rank, () => 'Axis must be <= rank of the tensor');
const inputs = { input: $x };
const attrs = { dim: axis };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* ExpandDims */ "bb"], inputs, attrs);
}
const expandDims = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ expandDims_ });
//# sourceMappingURL=expand_dims.js.map
/***/ }),
/* 64 */
/***/ (function(module, exports) {
module.exports = function() {
throw new Error("define cannot be used indirect");
};
/***/ }),
/* 65 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return conv2d; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _conv_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(31);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes a 2D convolution over the input x.
*
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, inDepth, outDepth]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `dilations` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function conv2d_(x, filter, strides, pad, dataFormat = 'NHWC', dilations = [1, 1], dimRoundingMode) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'conv2d');
const $filter = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(filter, 'filter', 'conv2d');
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = Object(_reshape__WEBPACK_IMPORTED_MODULE_6__[/* reshape */ "a"])($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](x4D.rank === 4, () => `Error in conv2d: input must be rank 4, but got rank ${x4D.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($filter.rank === 4, () => `Error in conv2d: filter must be rank 4, but got rank ` +
`${$filter.rank}.`);
if (dimRoundingMode != null) {
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](_util__WEBPACK_IMPORTED_MODULE_3__[/* isInt */ "v"](pad), () => `Error in conv2d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inDepth = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](inDepth === $filter.shape[2], () => `Error in conv2d: depth of input (${inDepth}) must match ` +
`input depth for filter ${$filter.shape[2]}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](_conv_util__WEBPACK_IMPORTED_MODULE_4__[/* eitherStridesOrDilationsAreOne */ "h"](strides, dilations), () => 'Error in conv2D: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
const inputs = { x: x4D, filter: $filter };
const attrs = { strides, pad, dataFormat, dilations, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Conv2D */ "C"], inputs, attrs);
if (reshapedTo4D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_6__[/* reshape */ "a"])(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const conv2d = Object(_operation__WEBPACK_IMPORTED_MODULE_5__[/* op */ "b"])({ conv2d_ });
//# sourceMappingURL=conv2d.js.map
/***/ }),
/* 66 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return greaterEqual; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(23);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2);
/* harmony import */ var _broadcast_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(17);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of (a >= b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.greaterEqual(b).print();
* ```
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function greaterEqual_(a, b) {
let $a = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(a, 'a', 'greaterEqual');
let $b = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(b, 'b', 'greaterEqual');
[$a, $b] = Object(_tensor_util__WEBPACK_IMPORTED_MODULE_2__["makeTypesMatch"])($a, $b);
Object(_broadcast_util__WEBPACK_IMPORTED_MODULE_4__[/* assertAndGetBroadcastShape */ "a"])($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* GreaterEqual */ "pb"], inputs);
}
const greaterEqual = Object(_operation__WEBPACK_IMPORTED_MODULE_5__[/* op */ "b"])({ greaterEqual_ });
//# sourceMappingURL=greater_equal.js.map
/***/ }),
/* 67 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return lessEqual; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(23);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2);
/* harmony import */ var _broadcast_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(17);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of (a <= b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.lessEqual(b).print();
* ```
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function lessEqual_(a, b) {
let $a = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(a, 'a', 'lessEqual');
let $b = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(b, 'b', 'lessEqual');
[$a, $b] = Object(_tensor_util__WEBPACK_IMPORTED_MODULE_2__["makeTypesMatch"])($a, $b);
Object(_broadcast_util__WEBPACK_IMPORTED_MODULE_4__[/* assertAndGetBroadcastShape */ "a"])($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* LessEqual */ "Ab"], inputs);
}
const lessEqual = Object(_operation__WEBPACK_IMPORTED_MODULE_5__[/* op */ "b"])({ lessEqual_ });
//# sourceMappingURL=less_equal.js.map
/***/ }),
/* 68 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return addImpl; });
/* unused harmony export addComplexImpl */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return add; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return addConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(27);
/* harmony import */ var _utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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 = Object(_utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__[/* createSimpleBinaryKernelImpl */ "a"])(((a, b) => a + b));
const addComplexImpl = Object(_utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__[/* createComplexBinaryKernelImpl */ "b"])(((aReal, aImag, bReal, bImag) => {
return { real: aReal + bReal, imag: aImag + bImag };
}));
const add = Object(_utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__[/* binaryKernelFunc */ "a"])(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Add"], addImpl, addComplexImpl);
const addConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Add"],
backendName: 'cpu',
kernelFunc: add
};
//# sourceMappingURL=Add.js.map
/***/ }),
/* 69 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return multiplyImpl; });
/* unused harmony export multiplyComplexImpl */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return multiply; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return multiplyConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(27);
/* harmony import */ var _utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const multiplyImpl = Object(_utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__[/* createSimpleBinaryKernelImpl */ "a"])(((aValue, bValue) => aValue * bValue));
const multiplyComplexImpl = Object(_utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__[/* createComplexBinaryKernelImpl */ "b"])(((aReal, aImag, bReal, bImag) => {
return {
real: aReal * bReal - aImag * bImag,
imag: aReal * bImag + aImag * bReal
};
}));
const multiply = Object(_utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__[/* binaryKernelFunc */ "a"])(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Multiply"], multiplyImpl, multiplyComplexImpl);
const multiplyConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Multiply"],
backendName: 'cpu',
kernelFunc: multiply
};
//# sourceMappingURL=Multiply.js.map
/***/ }),
/* 70 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return clone; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a new tensor with the same values and shape as the specified
* tensor.
*
* ```js
* const x = tf.tensor([1, 2]);
*
* x.clone().print();
* ```
*
* @param x The tensor to clone.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function clone_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'clone', 'string_or_numeric');
const inputs = { x: $x };
// Note this op is called tf.identity in python. Hence the kernel name used
// here.
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Identity */ "rb"], inputs);
}
const clone = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ clone_ });
//# sourceMappingURL=clone.js.map
/***/ }),
/* 71 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return sigmoid; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes sigmoid element-wise, `1 / (1 + exp(-x))`
*
* ```js
* const x = tf.tensor1d([0, -1, 2, -3]);
*
* x.sigmoid().print(); // or tf.sigmoid(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function sigmoid_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'sigmoid');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Sigmoid */ "Bc"], inputs);
}
const sigmoid = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ sigmoid_ });
//# sourceMappingURL=sigmoid.js.map
/***/ }),
/* 72 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return max; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the maximum of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and an
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.max().print(); // or tf.max(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.max(axis).print(); // or tf.max(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function max_(x, axis = null, keepDims = false) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'max');
const inputs = { x: $x };
const attrs = { reductionIndices: axis, keepDims };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Max */ "Ib"], inputs, attrs);
}
const max = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ max_ });
//# sourceMappingURL=max.js.map
/***/ }),
/* 73 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return createSimpleUnaryImpl; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Template that creates implementation for unary op.
*/
function createSimpleUnaryImpl(op) {
return (values, dtype, attrs) => {
const newValues = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].getTypedArrayFromDType(dtype, values.length);
for (let i = 0; i < values.length; ++i) {
newValues[i] = op(values[i], attrs);
}
return newValues;
};
}
//# sourceMappingURL=unary_impl.js.map
/***/ }),
/* 74 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return deepMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return deepZip; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return zipToList; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return deepMapAndAwaitAll; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return isIterable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return canTensorify; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* Apply a mapping function to a nested structure in a recursive manner.
*
* The result of the mapping is an object with the same nested structure (i.e.,
* of arrays and dicts) as the input, except that some subtrees are replaced,
* according to the results of the mapping function.
*
* Mappings are memoized. Thus, if the nested structure contains the same
* object in multiple positions, the output will contain the same mapped object
* in those positions. Cycles are not supported, however.
*
* @param input: The object to which to apply the mapping function.
* @param mapFn: A function that expects a single node of the object tree, and
* returns a `DeepMapResult`. The `DeepMapResult` either provides a
* replacement value for that node (i.e., replacing the subtree), or indicates
* that the node should be processed recursively.
*/
function deepMap(input, mapFn) {
return deepMapInternal(input, mapFn);
}
/**
* @param seen: A Map of known object mappings (i.e., memoized results of
* `mapFn()`)
* @param containedIn: An set containing objects on the reference path currently
* being processed (used to detect cycles).
*/
function deepMapInternal(input, mapFn, seen = new Map(), containedIn = new Set()) {
if (input == null) {
return null;
}
if (containedIn.has(input)) {
throw new Error('Circular references are not supported.');
}
if (seen.has(input)) {
return seen.get(input);
}
const result = mapFn(input);
if (result.recurse && result.value !== null) {
throw new Error('A deep map function may not return both a value and recurse=true.');
}
if (!result.recurse) {
seen.set(input, result.value);
return result.value;
}
else if (isIterable(input)) {
// tslint:disable-next-line:no-any
const mappedIterable = Array.isArray(input) ? [] : {};
containedIn.add(input);
for (const k in input) {
const child = input[k];
const childResult = deepMapInternal(child, mapFn, seen, containedIn);
mappedIterable[k] = childResult;
}
containedIn.delete(input);
return mappedIterable;
}
else {
throw new Error(`Can't recurse into non-iterable type: ${input}`);
}
}
// TODO(soergel, kangyizhang) Reconsider naming of deepZip() to avoid confusion
// with zip()
/**
* Zip nested structures together in a recursive manner.
*
* This has the effect of transposing or pivoting data, e.g. converting it from
* a row-major representation to a column-major representation.
*
* For example, `deepZip([{a: 1, b: 2}, {a: 3, b: 4}])` returns
* `{a: [1, 3], b: [2, 4]}`.
*
* The inputs should all have the same nested structure (i.e., of arrays and
* dicts). The result is a single object with the same nested structure, where
* the leaves are arrays collecting the values of the inputs at that location
* (or, optionally, the result of a custom function applied to those arrays).
*
* @param inputs: An array of the objects to zip together.
* @param zipFn: (optional) A function that expects an array of elements at a
* single node of the object tree, and returns a `DeepMapResult`. The
* `DeepMapResult` either provides a result value for that node (i.e.,
* representing the subtree), or indicates that the node should be processed
* recursively. The default zipFn recurses as far as possible and places
* arrays at the leaves.
*/
function deepZip(inputs, zipFn = zipToList) {
return deepZipInternal(inputs, zipFn);
}
/**
* @param containedIn: An set containing objects on the reference path currently
* being processed (used to detect cycles).
*/
function deepZipInternal(inputs, zipFn, containedIn = new Set()) {
// The recursion follows the structure of input 0; it's assumed that all the
// other inputs have the same structure.
const input = inputs[0];
if (containedIn.has(input)) {
throw new Error('Circular references are not supported.');
}
const result = zipFn(inputs);
if (result.recurse && result.value !== null) {
throw new Error('A deep zip function may not return both a value and recurse=true.');
}
if (!result.recurse) {
return result.value;
}
else if (isIterable(input)) {
// tslint:disable-next-line:no-any
const mappedIterable = Array.isArray(input) ? [] : {};
containedIn.add(input);
for (const k in input) {
const children = inputs.map(x => x[k]);
const childResult = deepZipInternal(children, zipFn, containedIn);
mappedIterable[k] = childResult;
}
containedIn.delete(input);
return mappedIterable;
}
else {
throw new Error(`Can't recurse into non-iterable type: ${input}`);
}
}
// tslint:disable-next-line:no-any
function zipToList(x) {
if (x === null) {
return null;
}
// TODO(soergel): validate array type?
if (isIterable(x[0])) {
return { value: null, recurse: true };
}
else {
return { value: x, recurse: false };
}
}
/**
* Apply an async mapping function to a nested structure in a recursive manner.
*
* This first creates a nested structure of Promises, and then awaits all of
* those, resulting in a single Promise for a resolved nested structure.
*
* The result of the mapping is an object with the same nested structure (i.e.,
* of arrays and dicts) as the input, except that some subtrees are replaced,
* according to the results of the mapping function.
*
* Mappings are memoized. Thus, if the nested structure contains the same
* object in multiple positions, the output will contain the same mapped object
* in those positions. Cycles are not supported, however.
*
* @param input: The object to which to apply the mapping function.
* @param mapFn: A function that expects a single node of the object tree, and
* returns a `DeepMapAsyncResult`. The `DeepMapAsyncResult` either provides
* a `Promise` for a replacement value for that node (i.e., replacing the
* subtree), or indicates that the node should be processed recursively. Note
* that the decision whether or not to recurse must be made immediately; only
* the mapped value may be promised.
*/
async function deepMapAndAwaitAll(input, mapFn) {
const seen = new Map();
// First do a normal deepMap, collecting Promises in 'seen' as a side effect.
deepMapInternal(input, mapFn, seen);
// Replace the Promises in 'seen' in place.
// Note TypeScript provides no async map iteration, and regular map iteration
// is broken too, so sadly we have to do Array.from() to make it work.
// (There's no advantage to Promise.all(), and that would be tricky anyway.)
for (const key of Array.from(seen.keys())) {
const value = seen.get(key);
if (_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].isPromise(value)) {
const mappedValue = await value;
seen.set(key, mappedValue);
}
}
// Normal deepMap again, this time filling in the resolved values.
// It's unfortunate that we have to do two passes.
// TODO(soergel): test performance and think harder about a fast solution.
const result = deepMapInternal(input, mapFn, seen);
return result;
}
/**
* Determine whether the argument is iterable.
*
* @returns true if the argument is an array or any non-Tensor object.
*/
// tslint:disable-next-line:no-any
function isIterable(obj) {
return obj != null && (!ArrayBuffer.isView(obj)) &&
(Array.isArray(obj) ||
(typeof obj === 'object' && !(obj instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"])));
}
/**
* Determine whether the argument can be converted to Tensor.
*
* Tensors, primitives, arrays, and TypedArrays all qualify; anything else does
* not.
*
* @returns true if the argument can be converted to Tensor.
*/
// tslint:disable-next-line:no-any
function canTensorify(obj) {
return obj == null || isPrimitive(obj) || Array.isArray(obj) ||
(typeof obj === 'object' && (obj instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"])) ||
_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].isTypedArray(obj);
}
/**
* Returns true if the given `value` is a primitive type. Otherwise returns
* false. This is equivalant to node util.isPrimitive
*/
function isPrimitive(value) {
return (value === null ||
(typeof value !== 'object' && typeof value !== 'function'));
}
//# sourceMappingURL=deep_map.js.map
/***/ }),
/* 75 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return log; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes natural logarithm of the input `tf.Tensor` element-wise: `ln(x)`
*
* ```js
* const x = tf.tensor1d([1, 2, Math.E]);
*
* x.log().print(); // or tf.log(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function log_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'log');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Log */ "Cb"], inputs);
}
const log = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ log_ });
//# sourceMappingURL=log.js.map
/***/ }),
/* 76 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return split; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Splits a `tf.Tensor` into sub tensors.
*
* If `numOrSizeSplits` is a number, splits `x` along dimension `axis`
* into `numOrSizeSplits` smaller tensors.
* Requires that `numOrSizeSplits` evenly divides `x.shape[axis]`.
*
* If `numOrSizeSplits` is a number array, splits `x` into
* `numOrSizeSplits.length` pieces. The shape of the `i`-th piece has the
* same size as `x` except along dimension `axis` where the size is
* `numOrSizeSplits[i]`.
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8], [2, 4]);
* const [a, b] = tf.split(x, 2, 1);
* a.print();
* b.print();
*
* const [c, d, e] = tf.split(x, [1, 2, 1], 1);
* c.print();
* d.print();
* e.print();
* ```
*
* @param x The input tensor to split.
* @param numOrSizeSplits Either an integer indicating the number of
* splits along the axis or an array of integers containing the sizes of
* each output tensor along the axis. If a number then it must evenly divide
* `x.shape[axis]`; otherwise the sum of sizes must match `x.shape[axis]`.
* Can contain one -1 indicating that dimension is to be inferred.
* @param axis The dimension along which to split. Defaults to 0 (the first
* dim).
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function split_(x, numOrSizeSplits, axis = 0) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'split');
const inputs = { x: $x };
const attr = { numOrSizeSplits, axis };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* SplitV */ "Lc"], inputs, attr);
}
const split = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ split_ });
//# sourceMappingURL=split.js.map
/***/ }),
/* 77 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return tensor1d; });
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
/* harmony import */ var _tensor_ops_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(51);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates rank-1 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor1d` as it makes the code more readable.
*
* ```js
* tf.tensor1d([1, 2, 3]).print();
* ```
*
* @param values The values of the tensor. Can be array of numbers,
* or a `TypedArray`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor1d(values, dtype) {
Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* assertNonNull */ "d"])(values);
const inferredShape = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* inferShape */ "c"])(values, dtype);
if (inferredShape.length !== 1) {
throw new Error('tensor1d() requires values to be a flat/TypedArray');
}
const shape = null;
return Object(_tensor_ops_util__WEBPACK_IMPORTED_MODULE_2__[/* makeTensor */ "a"])(values, shape, inferredShape, dtype);
}
//# sourceMappingURL=tensor1d.js.map
/***/ }),
/* 78 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return cast; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return castConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(27);
/* harmony import */ var _utils_zeros_impl__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(214);
/* harmony import */ var _Complex__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(38);
/* harmony import */ var _Identity__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(42);
/* harmony import */ var _Real__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(61);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function cast(args) {
const { inputs, backend, attrs } = args;
const { x } = inputs;
const { dtype } = attrs;
// Casting to complex64.
if (dtype === 'complex64') {
if (x.dtype === 'complex64') {
return Object(_Identity__WEBPACK_IMPORTED_MODULE_4__[/* identity */ "a"])({ inputs: { x }, backend });
}
const zerosTensorInfo = Object(_utils_zeros_impl__WEBPACK_IMPORTED_MODULE_2__[/* zeros */ "a"])(backend, x.shape, x.dtype);
const floatX = cast({ inputs: { x }, backend, attrs: { dtype: 'float32' } });
const result = Object(_Complex__WEBPACK_IMPORTED_MODULE_3__[/* complex */ "a"])({ inputs: { real: floatX, imag: zerosTensorInfo }, backend });
backend.disposeIntermediateTensorInfo(zerosTensorInfo);
backend.disposeIntermediateTensorInfo(floatX);
return result;
}
// Casting from complex64
if (x.dtype === 'complex64') {
const realPart = Object(_Real__WEBPACK_IMPORTED_MODULE_5__[/* real */ "a"])({ inputs: { input: x }, backend });
const result = cast({ inputs: { x: realPart }, backend, attrs: { dtype } });
backend.disposeIntermediateTensorInfo(realPart);
return result;
}
if (!_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].hasEncodingLoss(x.dtype, dtype)) {
// We don't change the underlying data, since we cast to higher
// precision.
const result = Object(_Identity__WEBPACK_IMPORTED_MODULE_4__[/* identity */ "a"])({ inputs: { x }, backend });
return { dataId: result.dataId, shape: result.shape, dtype };
}
if (dtype === 'int32') {
const values = backend.data.get(x.dataId).values;
const resultValues = Int32Array.from(values);
return backend.makeTensorInfo(x.shape, 'int32', resultValues);
}
if (dtype === 'bool') {
// This is essentially the result of notEqual(x, 0). We avoid using
// kernel notEqual to avoid circular dependency, i.e. binary_utils ->
// cast -> notEqual -> binary_utils.
const xVals = backend.data.get(x.dataId).values;
const zero = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].toTypedArray([0], x.dtype);
const [resultData, resultShape] = Object(_utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__[/* createSimpleBinaryKernelImpl */ "a"])((a, b) => (a !== b) ? 1 : 0)(x.shape, [], xVals, zero, 'bool');
return backend.makeTensorInfo(resultShape, 'bool', resultData);
}
throw new Error(`Error in Cast: failed to cast ${x.dtype} to ${dtype}`);
}
const castConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Cast"],
backendName: 'cpu',
kernelFunc: cast
};
//# sourceMappingURL=Cast.js.map
/***/ }),
/* 79 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ nonMaxSuppressionV3Impl; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ nonMaxSuppressionV4Impl; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* binding */ nonMaxSuppressionV5Impl; });
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/backends/non_max_suppression_util.js
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Inserts a value into a sorted array. This method allows duplicate, meaning it
* allows inserting duplicate value, in which case, the element will be inserted
* at the lowest index of the value.
* @param arr The array to modify.
* @param element The element to insert.
* @param comparator Optional. If no comparator is specified, elements are
* compared using array_util.defaultComparator, which is suitable for Strings
* and Numbers in ascending arrays. If the array contains multiple instances of
* the target value, the left-most instance will be returned. To provide a
* comparator, it should take 2 arguments to compare and return a negative,
* zero, or a positive number.
*/
function binaryInsert(arr, element, comparator) {
const index = binarySearch(arr, element, comparator);
const insertionPoint = index < 0 ? -(index + 1) : index;
arr.splice(insertionPoint, 0, element);
}
/**
* Searches the array for the target using binary search, returns the index
* of the found element, or position to insert if element not found. If no
* comparator is specified, elements are compared using array_
* util.defaultComparator, which is suitable for Strings and Numbers in
* ascending arrays. If the array contains multiple instances of the target
* value, the left-most instance will be returned.
* @param arr The array to be searched in.
* @param target The target to be searched for.
* @param comparator Should take 2 arguments to compare and return a negative,
* zero, or a positive number.
* @return Lowest index of the target value if found, otherwise the insertion
* point where the target should be inserted, in the form of
* (-insertionPoint - 1).
*/
function binarySearch(arr, target, comparator) {
return binarySearch_(arr, target, comparator || defaultComparator);
}
/**
* Compares its two arguments for order.
* @param a The first element to be compared.
* @param b The second element to be compared.
* @return A negative number, zero, or a positive number as the first
* argument is less than, equal to, or greater than the second.
*/
function defaultComparator(a, b) {
return a > b ? 1 : a < b ? -1 : 0;
}
function binarySearch_(arr, target, comparator) {
let left = 0;
let right = arr.length;
let middle = 0;
let found = false;
while (left < right) {
middle = left + ((right - left) >>> 1);
const compareResult = comparator(target, arr[middle]);
if (compareResult > 0) {
left = middle + 1;
}
else {
right = middle;
// If compareResult is 0, the value is found. We record it is found,
// and then keep looking because there may be duplicate.
found = !compareResult;
}
}
return found ? left : -left - 1;
}
//# sourceMappingURL=non_max_suppression_util.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/backends/non_max_suppression_impl.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function nonMaxSuppressionV3Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) {
return nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, 0 /* softNmsSigma */);
}
function nonMaxSuppressionV4Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize) {
return nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, 0 /* softNmsSigma */, false /* returnScoresTensor */, padToMaxOutputSize /* padToMaxOutputSize */, true
/* returnValidOutputs */ );
}
function nonMaxSuppressionV5Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
return nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma, true /* returnScoresTensor */);
}
function nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma, returnScoresTensor = false, padToMaxOutputSize = false, returnValidOutputs = false) {
// The list is sorted in ascending order, so that we can always pop the
// candidate with the largest score in O(1) time.
const candidates = [];
for (let i = 0; i < scores.length; i++) {
if (scores[i] > scoreThreshold) {
candidates.push({ score: scores[i], boxIndex: i, suppressBeginIndex: 0 });
}
}
candidates.sort(ascendingComparator);
// If softNmsSigma is 0, the outcome of this algorithm is exactly same as
// before.
const scale = softNmsSigma > 0 ? (-0.5 / softNmsSigma) : 0.0;
const selectedIndices = [];
const selectedScores = [];
while (selectedIndices.length < maxOutputSize && candidates.length > 0) {
const candidate = candidates.pop();
const { score: originalScore, boxIndex, suppressBeginIndex } = candidate;
if (originalScore < scoreThreshold) {
break;
}
// Overlapping boxes are likely to have similar scores, therefore we
// iterate through the previously selected boxes backwards in order to
// see if candidate's score should be suppressed. We use
// suppressBeginIndex to track and ensure a candidate can be suppressed
// by a selected box no more than once. Also, if the overlap exceeds
// iouThreshold, we simply ignore the candidate.
let ignoreCandidate = false;
for (let j = selectedIndices.length - 1; j >= suppressBeginIndex; --j) {
const iou = intersectionOverUnion(boxes, boxIndex, selectedIndices[j]);
if (iou >= iouThreshold) {
ignoreCandidate = true;
break;
}
candidate.score =
candidate.score * suppressWeight(iouThreshold, scale, iou);
if (candidate.score <= scoreThreshold) {
break;
}
}
// At this point, if `candidate.score` has not dropped below
// `scoreThreshold`, then we know that we went through all of the
// previous selections and can safely update `suppressBeginIndex` to the
// end of the selected array. Then we can re-insert the candidate with
// the updated score and suppressBeginIndex back in the candidate list.
// If on the other hand, `candidate.score` has dropped below the score
// threshold, we will not add it back to the candidates list.
candidate.suppressBeginIndex = selectedIndices.length;
if (!ignoreCandidate) {
// Candidate has passed all the tests, and is not suppressed, so
// select the candidate.
if (candidate.score === originalScore) {
selectedIndices.push(boxIndex);
selectedScores.push(candidate.score);
}
else if (candidate.score > scoreThreshold) {
// Candidate's score is suppressed but is still high enough to be
// considered, so add back to the candidates list.
binaryInsert(candidates, candidate, ascendingComparator);
}
}
}
// NonMaxSuppressionV4 feature: padding output to maxOutputSize.
const validOutputs = selectedIndices.length;
const elemsToPad = maxOutputSize - validOutputs;
if (padToMaxOutputSize && elemsToPad > 0) {
selectedIndices.push(...new Array(elemsToPad).fill(0));
selectedScores.push(...new Array(elemsToPad).fill(0.0));
}
const result = { selectedIndices };
if (returnScoresTensor) {
result['selectedScores'] = selectedScores;
}
if (returnValidOutputs) {
result['validOutputs'] = validOutputs;
}
return result;
}
function intersectionOverUnion(boxes, i, j) {
const iCoord = boxes.subarray(i * 4, i * 4 + 4);
const jCoord = boxes.subarray(j * 4, j * 4 + 4);
const yminI = Math.min(iCoord[0], iCoord[2]);
const xminI = Math.min(iCoord[1], iCoord[3]);
const ymaxI = Math.max(iCoord[0], iCoord[2]);
const xmaxI = Math.max(iCoord[1], iCoord[3]);
const yminJ = Math.min(jCoord[0], jCoord[2]);
const xminJ = Math.min(jCoord[1], jCoord[3]);
const ymaxJ = Math.max(jCoord[0], jCoord[2]);
const xmaxJ = Math.max(jCoord[1], jCoord[3]);
const areaI = (ymaxI - yminI) * (xmaxI - xminI);
const areaJ = (ymaxJ - yminJ) * (xmaxJ - xminJ);
if (areaI <= 0 || areaJ <= 0) {
return 0.0;
}
const intersectionYmin = Math.max(yminI, yminJ);
const intersectionXmin = Math.max(xminI, xminJ);
const intersectionYmax = Math.min(ymaxI, ymaxJ);
const intersectionXmax = Math.min(xmaxI, xmaxJ);
const intersectionArea = Math.max(intersectionYmax - intersectionYmin, 0.0) *
Math.max(intersectionXmax - intersectionXmin, 0.0);
return intersectionArea / (areaI + areaJ - intersectionArea);
}
// A Gaussian penalty function, this method always returns values in [0, 1].
// The weight is a function of similarity, the more overlap two boxes are, the
// smaller the weight is, meaning highly overlapping boxe will be significantly
// penalized. On the other hand, a non-overlapping box will not be penalized.
function suppressWeight(iouThreshold, scale, iou) {
const weight = Math.exp(scale * iou * iou);
return iou <= iouThreshold ? weight : 0.0;
}
function ascendingComparator(c1, c2) {
// For objects with same scores, we make the object with the larger index go
// first. In an array that pops from the end, this means that the object with
// the smaller index will be popped first. This ensures the same output as
// the TensorFlow python version.
return (c1.score - c2.score) ||
((c1.score === c2.score) && (c2.boxIndex - c1.boxIndex));
}
//# sourceMappingURL=non_max_suppression_impl.js.map
/***/ }),
/* 80 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return zeros; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
/* harmony import */ var _complex__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(58);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with all elements set to 0.
*
* ```js
* tf.zeros([2, 2]).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param dtype The type of an element in the resulting tensor. Can
* be 'float32', 'int32' or 'bool'. Defaults to 'float'.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function zeros(shape, dtype = 'float32') {
if (dtype === 'complex64') {
const real = zeros(shape, 'float32');
const imag = zeros(shape, 'float32');
return Object(_complex__WEBPACK_IMPORTED_MODULE_2__[/* complex */ "a"])(real, imag);
}
const values = Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* makeZerosTypedArray */ "F"])(Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* sizeFromShape */ "O"])(shape), dtype);
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].makeTensor(values, shape, dtype);
}
//# sourceMappingURL=zeros.js.map
/***/ }),
/* 81 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return relu; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes rectified linear element-wise: `max(x, 0)`.
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.relu().print(); // or tf.relu(x)
* ```
* @param x The input tensor. If the dtype is `bool`, the output dtype will be
* `int32'.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function relu_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'relu');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Relu */ "nc"], inputs);
}
const relu = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ relu_ });
//# sourceMappingURL=relu.js.map
/***/ }),
/* 82 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return step; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes step of the input `tf.Tensor` element-wise: `x > 0 ? 1 : alpha * x`
*
* ```js
* const x = tf.tensor1d([0, 2, -1, -3]);
*
* x.step(.5).print(); // or tf.step(x, .5)
* ```
* @param x The input tensor.
* @param alpha The gradient when input is negative.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function step_(x, alpha = 0.0) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'step');
const inputs = { x: $x };
const attrs = { alpha };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Step */ "Pc"], inputs, attrs);
}
const step = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ step_ });
//# sourceMappingURL=step.js.map
/***/ }),
/* 83 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return unstack; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Unstacks a `tf.Tensor` of rank-`R` into a list of rank-`(R-1)` `tf.Tensor`s.
*
* ```js
* const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* tf.unstack(a).forEach(tensor => tensor.print());
* ```
*
* @param x A tensor object.
* @param axis The axis to unstack along. Defaults to 0 (the first dim).
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function unstack_(x, axis = 0) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'unstack', 'string_or_numeric');
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](axis >= -$x.shape.length && axis < $x.shape.length, () => `Axis = ${axis} is not in [-${$x.shape.length}, ${$x.shape.length})`);
const inputs = { value: $x };
const attrs = { axis };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Unpack */ "ad"], inputs, attrs);
}
const unstack = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ unstack_ });
//# sourceMappingURL=unstack.js.map
/***/ }),
/* 84 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ batchNorm; });
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/engine.js + 2 modules
var engine = __webpack_require__(5);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/kernel_names.js
var kernel_names = __webpack_require__(3);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/tensor_util_env.js
var tensor_util_env = __webpack_require__(2);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/util_base.js
var util_base = __webpack_require__(8);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/reshape.js
var reshape = __webpack_require__(7);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/batchnorm_util.js
function xAs4D(x) {
let x4D;
if (x.rank === 0 || x.rank === 1) {
x4D = Object(reshape["a" /* reshape */])(x, [1, 1, 1, x.size]);
}
else if (x.rank === 2) {
x4D = Object(reshape["a" /* reshape */])(x, [1, 1, x.shape[0], x.shape[1]]);
}
else if (x.rank === 3) {
x4D = Object(reshape["a" /* reshape */])(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
}
else {
x4D = x;
}
return x4D;
}
//# sourceMappingURL=batchnorm_util.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/operation.js
var operation = __webpack_require__(4);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/batchnorm.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Batch normalization.
*
* As described in
* [http://arxiv.org/abs/1502.03167](http://arxiv.org/abs/1502.03167).
*
* Mean, variance, scale, and offset can be of two shapes:
* - The same shape as the input.
* - In the common case, the depth dimension is the last dimension of x, so
* the values would be an `tf.Tensor1D` of shape [depth].
*
* Also available are stricter rank-specific methods with the same signature
* as this method that assert that parameters passed are of given rank
* - `tf.batchNorm2d`
* - `tf.batchNorm3d`
* - `tf.batchNorm4d`
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function batchNorm_(x, mean, variance, offset, scale, varianceEpsilon) {
if (varianceEpsilon == null) {
varianceEpsilon = 0.001;
}
const $x = Object(tensor_util_env["a" /* convertToTensor */])(x, 'x', 'batchNorm');
const $mean = Object(tensor_util_env["a" /* convertToTensor */])(mean, 'mean', 'batchNorm');
const $variance = Object(tensor_util_env["a" /* convertToTensor */])(variance, 'variance', 'batchNorm');
let $scale;
if (scale != null) {
$scale = Object(tensor_util_env["a" /* convertToTensor */])(scale, 'scale', 'batchNorm');
}
let $offset;
if (offset != null) {
$offset = Object(tensor_util_env["a" /* convertToTensor */])(offset, 'offset', 'batchNorm');
}
util_base["b" /* assert */]($mean.rank === $variance.rank, () => 'Batch normalization gradient requires mean and variance to have ' +
'equal ranks.');
util_base["b" /* assert */]($offset == null || $mean.rank === $offset.rank, () => 'Batch normalization gradient requires mean and offset to have ' +
'equal ranks.');
util_base["b" /* assert */]($scale == null || $mean.rank === $scale.rank, () => 'Batch normalization gradient requires mean and scale to have ' +
'equal ranks.');
const x4D = xAs4D($x);
const inputs = {
x: x4D,
scale: $scale,
offset: $offset,
mean: $mean,
variance: $variance
};
const attrs = { varianceEpsilon };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = engine["a" /* ENGINE */].runKernel(kernel_names["jb" /* FusedBatchNorm */], inputs, attrs);
return Object(reshape["a" /* reshape */])(res, $x.shape);
}
const batchNorm = Object(operation["b" /* op */])({ batchNorm_ });
//# sourceMappingURL=batchnorm.js.map
/***/ }),
/* 85 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return tile; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Construct a tensor by repeating it the number of times given by reps.
*
* This operation creates a new tensor by replicating `input` `reps`
* times. The output tensor's i'th dimension has `input.shape[i] *
* reps[i]` elements, and the values of `input` are replicated
* `reps[i]` times along the i'th dimension. For example, tiling
* `[a, b, c, d]` by `[2]` produces `[a, b, c, d, a, b, c, d]`.
*
* ```js
* const a = tf.tensor1d([1, 2]);
*
* a.tile([2]).print(); // or a.tile([2])
* ```
*
* ```js
* const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* a.tile([1, 2]).print(); // or a.tile([1, 2])
* ```
* @param x The tensor to tile.
* @param reps Determines the number of replications per dimension.
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function tile_(x, reps) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'tile', 'string_or_numeric');
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($x.rank === reps.length, () => `Error in transpose: rank of input ${$x.rank} ` +
`must match length of reps ${reps}.`);
const inputs = { x: $x };
const attrs = { reps };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Tile */ "Vc"], inputs, attrs);
}
const tile = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ tile_ });
//# sourceMappingURL=tile.js.map
/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {
// A library of seedable RNGs implemented in Javascript.
//
// Usage:
//
// var seedrandom = require('seedrandom');
// var random = seedrandom(1); // or any seed.
// var x = random(); // 0 <= x < 1. Every bit is random.
// var x = random.quick(); // 0 <= x < 1. 32 bits of randomness.
// alea, a 53-bit multiply-with-carry generator by Johannes Baagøe.
// Period: ~2^116
// Reported to pass all BigCrush tests.
var alea = __webpack_require__(281);
// xor128, a pure xor-shift generator by George Marsaglia.
// Period: 2^128-1.
// Reported to fail: MatrixRank and LinearComp.
var xor128 = __webpack_require__(282);
// xorwow, George Marsaglia's 160-bit xor-shift combined plus weyl.
// Period: 2^192-2^32
// Reported to fail: CollisionOver, SimpPoker, and LinearComp.
var xorwow = __webpack_require__(283);
// xorshift7, by François Panneton and Pierre L'ecuyer, takes
// a different approach: it adds robustness by allowing more shifts
// than Marsaglia's original three. It is a 7-shift generator
// with 256 bits, that passes BigCrush with no systmatic failures.
// Period 2^256-1.
// No systematic BigCrush failures reported.
var xorshift7 = __webpack_require__(284);
// xor4096, by Richard Brent, is a 4096-bit xor-shift with a
// very long period that also adds a Weyl generator. It also passes
// BigCrush with no systematic failures. Its long period may
// be useful if you have many generators and need to avoid
// collisions.
// Period: 2^4128-2^32.
// No systematic BigCrush failures reported.
var xor4096 = __webpack_require__(285);
// Tyche-i, by Samuel Neves and Filipe Araujo, is a bit-shifting random
// number generator derived from ChaCha, a modern stream cipher.
// https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf
// Period: ~2^127
// No systematic BigCrush failures reported.
var tychei = __webpack_require__(286);
// The original ARC4-based prng included in this library.
// Period: ~2^1600
var sr = __webpack_require__(287);
sr.alea = alea;
sr.xor128 = xor128;
sr.xorwow = xorwow;
sr.xorshift7 = xorshift7;
sr.xor4096 = xor4096;
sr.tychei = tychei;
module.exports = sr;
/***/ }),
/* 87 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DataType; });
/* unused harmony export SaverDef */
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/** DataType enum. */
var DataType;
(function (DataType) {
DataType[DataType["DT_INVALID"] = 0] = "DT_INVALID";
DataType[DataType["DT_FLOAT"] = 1] = "DT_FLOAT";
DataType[DataType["DT_DOUBLE"] = 2] = "DT_DOUBLE";
DataType[DataType["DT_INT32"] = 3] = "DT_INT32";
DataType[DataType["DT_UINT8"] = 4] = "DT_UINT8";
DataType[DataType["DT_INT16"] = 5] = "DT_INT16";
DataType[DataType["DT_INT8"] = 6] = "DT_INT8";
DataType[DataType["DT_STRING"] = 7] = "DT_STRING";
DataType[DataType["DT_COMPLEX64"] = 8] = "DT_COMPLEX64";
DataType[DataType["DT_INT64"] = 9] = "DT_INT64";
DataType[DataType["DT_BOOL"] = 10] = "DT_BOOL";
DataType[DataType["DT_QINT8"] = 11] = "DT_QINT8";
DataType[DataType["DT_QUINT8"] = 12] = "DT_QUINT8";
DataType[DataType["DT_QINT32"] = 13] = "DT_QINT32";
DataType[DataType["DT_BFLOAT16"] = 14] = "DT_BFLOAT16";
DataType[DataType["DT_FLOAT_REF"] = 101] = "DT_FLOAT_REF";
DataType[DataType["DT_DOUBLE_REF"] = 102] = "DT_DOUBLE_REF";
DataType[DataType["DT_INT32_REF"] = 103] = "DT_INT32_REF";
DataType[DataType["DT_UINT8_REF"] = 104] = "DT_UINT8_REF";
DataType[DataType["DT_INT16_REF"] = 105] = "DT_INT16_REF";
DataType[DataType["DT_INT8_REF"] = 106] = "DT_INT8_REF";
DataType[DataType["DT_STRING_REF"] = 107] = "DT_STRING_REF";
DataType[DataType["DT_COMPLEX64_REF"] = 108] = "DT_COMPLEX64_REF";
DataType[DataType["DT_INT64_REF"] = 109] = "DT_INT64_REF";
DataType[DataType["DT_BOOL_REF"] = 110] = "DT_BOOL_REF";
DataType[DataType["DT_QINT8_REF"] = 111] = "DT_QINT8_REF";
DataType[DataType["DT_QUINT8_REF"] = 112] = "DT_QUINT8_REF";
DataType[DataType["DT_QINT32_REF"] = 113] = "DT_QINT32_REF";
DataType[DataType["DT_BFLOAT16_REF"] = 114] = "DT_BFLOAT16_REF";
})(DataType || (DataType = {}));
var SaverDef;
(function (SaverDef) {
/** CheckpointFormatVersion enum. */
let CheckpointFormatVersion;
(function (CheckpointFormatVersion) {
CheckpointFormatVersion[CheckpointFormatVersion["LEGACY"] = 0] = "LEGACY";
CheckpointFormatVersion[CheckpointFormatVersion["V1"] = 1] = "V1";
CheckpointFormatVersion[CheckpointFormatVersion["V2"] = 2] = "V2";
})(CheckpointFormatVersion = SaverDef.CheckpointFormatVersion || (SaverDef.CheckpointFormatVersion = {}));
})(SaverDef || (SaverDef = {}));
//# sourceMappingURL=compiled_api.js.map
/***/ }),
/* 88 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return mean; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the mean of elements across dimensions of a `tf.Tensor`.
*
* Reduces `x` along the dimensions given in `axis`. Unless `keepDims` is
* true, the rank of the `tf.Tensor` is reduced by 1 for each entry in `axis`.
* If `keepDims` is true, the reduced dimensions are retained with length 1.
* If `axis` has no entries, all dimensions are reduced, and a `tf.Tensor` with
* a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.mean().print(); // or tf.mean(a)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.mean(axis).print(); // or tf.mean(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function mean_(x, axis = null, keepDims = false) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'mean');
const inputs = { x: $x };
const attrs = { axis, keepDims };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Mean */ "Pb"], inputs, attrs);
}
const mean = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ mean_ });
//# sourceMappingURL=mean.js.map
/***/ }),
/* 89 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Rank; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return upcastType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return sumOutType; });
/**
* @license
* Copyright 2017 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
var Rank;
(function (Rank) {
Rank["R0"] = "R0";
Rank["R1"] = "R1";
Rank["R2"] = "R2";
Rank["R3"] = "R3";
Rank["R4"] = "R4";
Rank["R5"] = "R5";
Rank["R6"] = "R6";
})(Rank || (Rank = {}));
// Looks for upcasting types. Used, for example, in operations with mixed dtype
// inputs.
var UpcastInt32AndMap;
(function (UpcastInt32AndMap) {
UpcastInt32AndMap["float32"] = "float32";
UpcastInt32AndMap["int32"] = "int32";
UpcastInt32AndMap["bool"] = "int32";
UpcastInt32AndMap["complex64"] = "complex64";
})(UpcastInt32AndMap || (UpcastInt32AndMap = {}));
var UpcastBoolAndMap;
(function (UpcastBoolAndMap) {
UpcastBoolAndMap["float32"] = "float32";
UpcastBoolAndMap["int32"] = "int32";
UpcastBoolAndMap["bool"] = "bool";
UpcastBoolAndMap["complex64"] = "complex64";
})(UpcastBoolAndMap || (UpcastBoolAndMap = {}));
var UpcastFloat32AndMap;
(function (UpcastFloat32AndMap) {
UpcastFloat32AndMap["float32"] = "float32";
UpcastFloat32AndMap["int32"] = "float32";
UpcastFloat32AndMap["bool"] = "float32";
UpcastFloat32AndMap["complex64"] = "complex64";
})(UpcastFloat32AndMap || (UpcastFloat32AndMap = {}));
var UpcastComplex64AndMap;
(function (UpcastComplex64AndMap) {
UpcastComplex64AndMap["float32"] = "complex64";
UpcastComplex64AndMap["int32"] = "complex64";
UpcastComplex64AndMap["bool"] = "complex64";
UpcastComplex64AndMap["complex64"] = "complex64";
})(UpcastComplex64AndMap || (UpcastComplex64AndMap = {}));
const upcastTypeMap = {
'float32': UpcastFloat32AndMap,
'int32': UpcastInt32AndMap,
'bool': UpcastBoolAndMap,
'complex64': UpcastComplex64AndMap
};
function upcastType(typeA, typeB) {
if (typeA === 'string' || typeB === 'string') {
if (typeA === 'string' && typeB === 'string') {
return 'string';
}
throw new Error(`Can not upcast ${typeA} with ${typeB}`);
}
return upcastTypeMap[typeA][typeB];
}
/** Returns the output type after summation. */
function sumOutType(type) {
return upcastType(type, 'int32');
}
//# sourceMappingURL=types.js.map
/***/ }),
/* 90 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return maximum; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(23);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2);
/* harmony import */ var _broadcast_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(17);
/* harmony import */ var _cast__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(12);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the max of a and b (`a > b ? a : b`) element-wise.
* Supports broadcasting.
*
* We also expose `tf.maximumStrict` which has the same signature as this op and
* asserts that `a` and `b` are the same shape (does not broadcast).
*
* ```js
* const a = tf.tensor1d([1, 4, 3, 16]);
* const b = tf.tensor1d([1, 2, 9, 4]);
*
* a.maximum(b).print(); // or tf.maximum(a, b)
* ```
*
* ```js
* // Broadcast maximum a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(5);
*
* a.maximum(b).print(); // or tf.maximum(a, b)
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function maximum_(a, b) {
let $a = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(a, 'a', 'maximum');
let $b = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(b, 'b', 'maximum');
[$a, $b] = Object(_tensor_util__WEBPACK_IMPORTED_MODULE_2__["makeTypesMatch"])($a, $b);
if ($a.dtype === 'bool') {
$a = Object(_cast__WEBPACK_IMPORTED_MODULE_5__[/* cast */ "a"])($a, 'int32');
$b = Object(_cast__WEBPACK_IMPORTED_MODULE_5__[/* cast */ "a"])($b, 'int32');
}
Object(_broadcast_util__WEBPACK_IMPORTED_MODULE_4__[/* assertAndGetBroadcastShape */ "a"])($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Maximum */ "Ob"], inputs);
}
const maximum = Object(_operation__WEBPACK_IMPORTED_MODULE_6__[/* op */ "b"])({ maximum_ });
//# sourceMappingURL=maximum.js.map
/***/ }),
/* 91 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return batchToSpaceND; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* This operation reshapes the "batch" dimension 0 into `M + 1` dimensions of
* shape `blockShape + [batch]`, interleaves these blocks back into the grid
* defined by the spatial dimensions `[1, ..., M]`, to obtain a result with
* the same rank as the input. The spatial dimensions of this intermediate
* result are then optionally cropped according to `crops` to produce the
* output. This is the reverse of `tf.spaceToBatchND`. See below for a precise
* description.
*
* ```js
* const x = tf.tensor4d([1, 2, 3, 4], [4, 1, 1, 1]);
* const blockShape = [2, 2];
* const crops = [[0, 0], [0, 0]];
*
* x.batchToSpaceND(blockShape, crops).print();
* ```
*
* @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +
* remainingShape`, where spatialShape has `M` dimensions.
* @param blockShape A 1-D array. Must have shape `[M]`, all values must
* be >= 1.
* @param crops A 2-D array. Must have shape `[M, 2]`, all values must be >= 0.
* `crops[i] = [cropStart, cropEnd]` specifies the amount to crop from input
* dimension `i + 1`, which corresponds to spatial dimension `i`. It is required
* that `cropStart[i] + cropEnd[i] <= blockShape[i] * inputShape[i + 1]`
*
* This operation is equivalent to the following steps:
*
* 1. Reshape `x` to `reshaped` of shape: `[blockShape[0], ...,
* blockShape[M-1], batch / prod(blockShape), x.shape[1], ...,
* x.shape[N-1]]`
*
* 2. Permute dimensions of `reshaped`to produce `permuted` of shape `[batch /
* prod(blockShape),x.shape[1], blockShape[0], ..., x.shape[M],
* blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`
*
* 3. Reshape `permuted` to produce `reshapedPermuted` of shape `[batch /
* prod(blockShape),x.shape[1] * blockShape[0], ..., x.shape[M] *
* blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`
*
* 4. Crop the start and end of dimensions `[1, ..., M]` of `reshapedPermuted`
* according to `crops` to produce the output of shape: `[batch /
* prod(blockShape),x.shape[1] * blockShape[0] - crops[0,0] - crops[0,1],
* ..., x.shape[M] * blockShape[M-1] - crops[M-1,0] -
* crops[M-1,1],x.shape[M+1], ..., x.shape[N-1]]`
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function batchToSpaceND_(x, blockShape, crops) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'batchToSpaceND');
const prod = blockShape.reduce((a, b) => a * b);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($x.rank >= 1 + blockShape.length, () => `input rank is ${$x.rank} but should be > than blockShape.length ${blockShape.length}`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](crops.length === blockShape.length, () => `crops.length is ${crops.length} but should be equal to blockShape.length ${blockShape.length}`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($x.shape[0] % prod === 0, () => `input tensor batch is ${$x.shape[0]} but is not divisible by the product of ` +
`the elements of blockShape ${blockShape.join(' * ')} === ${prod}`);
const inputs = { x: $x };
const attrs = { blockShape, crops };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* BatchToSpaceND */ "t"], inputs, attrs);
}
const batchToSpaceND = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ batchToSpaceND_ });
//# sourceMappingURL=batch_to_space_nd.js.map
/***/ }),
/* 92 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return depthwiseConv2d; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Depthwise 2D convolution.
*
* Given a 4D `input` array and a `filter` array of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]` containing
* `inChannels` convolutional filters of depth 1, this op applies a
* different filter to each input channel (expanding from 1 channel to
* `channelMultiplier` channels for each), then concatenates the results
* together. The output has `inChannels * channelMultiplier` channels.
*
* See
* [https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d](
* https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)
* for more details.
*
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter tensor, rank 4, of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`. If strides is a single number, then `strideHeight ==
* strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels]. Only "NHWC" is currently supported.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function depthwiseConv2d_(x, filter, strides, pad, dataFormat = 'NHWC', dilations = [1, 1], dimRoundingMode) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'depthwiseConv2d');
const $filter = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(filter, 'filter', 'depthwiseConv2d');
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](x4D.rank === 4, () => `Error in depthwiseConv2d: input must be rank 4, but got ` +
`rank ${x4D.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($filter.rank === 4, () => `Error in depthwiseConv2d: filter must be rank 4, but got rank ` +
`${$filter.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](x4D.shape[3] === $filter.shape[2], () => `Error in depthwiseConv2d: number of input channels ` +
`(${x4D.shape[3]}) must match the inChannels dimension in ` +
`filter ${$filter.shape[2]}.`);
if (dimRoundingMode != null) {
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](_util__WEBPACK_IMPORTED_MODULE_3__[/* isInt */ "v"](pad), () => `Error in depthwiseConv2d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x4D, filter: $filter };
const attrs = { strides, pad, dataFormat, dilations, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* DepthwiseConv2dNative */ "O"], inputs, attrs);
if (reshapedTo4D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const depthwiseConv2d = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ depthwiseConv2d_ });
//# sourceMappingURL=depthwise_conv2d.js.map
/***/ }),
/* 93 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return equal; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(23);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2);
/* harmony import */ var _broadcast_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(17);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of (a == b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.equal(b).print();
* ```
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function equal_(a, b) {
let $a = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(a, 'a', 'equal');
let $b = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(b, 'b', 'equal');
[$a, $b] = Object(_tensor_util__WEBPACK_IMPORTED_MODULE_2__["makeTypesMatch"])($a, $b);
Object(_broadcast_util__WEBPACK_IMPORTED_MODULE_4__[/* assertAndGetBroadcastShape */ "a"])($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Equal */ "Y"], inputs);
}
const equal = Object(_operation__WEBPACK_IMPORTED_MODULE_5__[/* op */ "b"])({ equal_ });
//# sourceMappingURL=equal.js.map
/***/ }),
/* 94 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return gather; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Gather slices from tensor `x`'s axis `axis` according to `indices`.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* const indices = tf.tensor1d([1, 3, 3], 'int32');
*
* x.gather(indices).print();
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
* const indices = tf.tensor1d([1, 1, 0], 'int32');
*
* x.gather(indices).print();
* ```
* @param x The input tensor whose slices to be gathered.
* @param indices The indices of the values to extract.
* @param axis The axis over which to select values. Defaults to 0.
* @param batchDims Optional. The number of batch dimensions. It must be less
* than or equal to rank(indices). Defaults to 0.
* The output tensor will have shape of
* `x.shape[:axis] + indices.shape[batchDims:] + x.shape[axis + 1:]`
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function gather_(x, indices, axis = 0, batchDims = 0) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'gather');
const $indices = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(indices, 'indices', 'gather', 'int32');
const inputs = { x: $x, indices: $indices };
const attrs = { axis, batchDims };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* GatherV2 */ "nb"], inputs, attrs);
}
const gather = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ gather_ });
//# sourceMappingURL=gather.js.map
/***/ }),
/* 95 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return logicalNot; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of `NOT x` element-wise.
*
* ```js
* const a = tf.tensor1d([false, true], 'bool');
*
* a.logicalNot().print();
* ```
*
* @param x The input tensor. Must be of dtype 'bool'.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function logicalNot_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'logicalNot', 'bool');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* LogicalNot */ "Gb"], inputs);
}
const logicalNot = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ logicalNot_ });
//# sourceMappingURL=logical_not.js.map
/***/ }),
/* 96 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return spaceToBatchND; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* This operation divides "spatial" dimensions `[1, ..., M]` of the input into
* a grid of blocks of shape `blockShape`, and interleaves these blocks with
* the "batch" dimension (0) such that in the output, the spatial
* dimensions `[1, ..., M]` correspond to the position within the grid,
* and the batch dimension combines both the position within a spatial block
* and the original batch position. Prior to division into blocks,
* the spatial dimensions of the input are optionally zero padded
* according to `paddings`. See below for a precise description.
*
* ```js
* const x = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
* const blockShape = [2, 2];
* const paddings = [[0, 0], [0, 0]];
*
* x.spaceToBatchND(blockShape, paddings).print();
* ```
*
* @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +
* remainingShape`, where spatialShape has `M` dimensions.
* @param blockShape A 1-D array. Must have shape `[M]`, all values must
* be >= 1.
* @param paddings A 2-D array. Must have shape `[M, 2]`, all values must be >=
* 0. `paddings[i] = [padStart, padEnd]` specifies the amount to zero-pad
* from input dimension `i + 1`, which corresponds to spatial dimension `i`. It
* is required that
* `(inputShape[i + 1] + padStart + padEnd) % blockShape[i] === 0`
*
* This operation is equivalent to the following steps:
*
* 1. Zero-pad the start and end of dimensions `[1, ..., M]` of the input
* according to `paddings` to produce `padded` of shape paddedShape.
*
* 2. Reshape `padded` to `reshapedPadded` of shape:
* `[batch] + [paddedShape[1] / blockShape[0], blockShape[0], ...,
* paddedShape[M] / blockShape[M-1], blockShape[M-1]] + remainingShape`
*
* 3. Permute dimensions of `reshapedPadded` to produce `permutedReshapedPadded`
* of shape: `blockShape + [batch] + [paddedShape[1] / blockShape[0], ...,
* paddedShape[M] / blockShape[M-1]] + remainingShape`
*
* 4. Reshape `permutedReshapedPadded` to flatten `blockShape` into the
* batch dimension, producing an output tensor of shape:
* `[batch * prod(blockShape)] + [paddedShape[1] / blockShape[0], ...,
* paddedShape[M] / blockShape[M-1]] + remainingShape`
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function spaceToBatchND_(x, blockShape, paddings) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'spaceToBatchND');
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($x.rank >= 1 + blockShape.length, () => `input rank ${$x.rank} should be > than [blockShape] ${blockShape.length}`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](paddings.length === blockShape.length, () => `paddings.shape[0] ${paddings.length} must be equal to [blockShape] ${blockShape.length}`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($x.shape.reduce((a, b, i) => {
if (i > 0 && i <= blockShape.length) {
return a &&
((b + paddings[i - 1][0] + paddings[i - 1][1]) %
blockShape[i - 1] ===
0);
}
return a;
}, true), () => `input spatial dimensions ${$x.shape.slice(1)} with paddings ${paddings.toString()} must be divisible by blockShapes ${blockShape.toString()}`);
const inputs = { x: $x };
const attrs = { blockShape, paddings };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* SpaceToBatchND */ "Ic"], inputs, attrs);
}
const spaceToBatchND = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ spaceToBatchND_ });
//# sourceMappingURL=space_to_batch_nd.js.map
/***/ }),
/* 97 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return squeeze; });
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Removes dimensions of size 1 from the shape of a `tf.Tensor`.
*
* ```js
* const x = tf.tensor([1, 2, 3, 4], [1, 1, 4]);
* x.squeeze().print();
* ```
*
* @param x The input tensor to be squeezed.
* @param axis An optional list of numbers. If specified, only
* squeezes the dimensions listed. The dimension index starts at 0. It
* is an error to squeeze a dimension that is not 1.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function squeeze_(x, axis) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* convertToTensor */ "a"])(x, 'x', 'squeeze');
return Object(_reshape__WEBPACK_IMPORTED_MODULE_3__[/* reshape */ "a"])($x, Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* squeezeShape */ "Q"])($x.shape, axis).newShape);
}
const squeeze = Object(_operation__WEBPACK_IMPORTED_MODULE_2__[/* op */ "b"])({ squeeze_ });
//# sourceMappingURL=squeeze.js.map
/***/ }),
/* 98 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return bincountImpl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return bincountReduceImpl; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function bincountImpl(xVals, weightsVals, weightsDtype, weightsShape, size) {
const weightsSize = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(weightsShape);
const outVals = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].makeZerosTypedArray(size, weightsDtype);
for (let i = 0; i < xVals.length; i++) {
const value = xVals[i];
if (value < 0) {
throw new Error('Input x must be non-negative!');
}
if (value >= size) {
continue;
}
if (weightsSize > 0) {
outVals[value] += weightsVals[i];
}
else {
outVals[value] += 1;
}
}
return outVals;
}
function bincountReduceImpl(xBuf, weightsBuf, size, binaryOutput = false) {
const numRows = xBuf.shape[0];
const numCols = xBuf.shape[1];
const outBuf = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["buffer"])([numRows, size], weightsBuf.dtype);
for (let i = 0; i < numRows; i++) {
for (let j = 0; j < numCols; j++) {
const value = xBuf.get(i, j);
if (value < 0) {
throw new Error('Input x must be non-negative!');
}
if (value >= size) {
continue;
}
if (binaryOutput) {
outBuf.set(1, i, value);
}
else {
if (weightsBuf.size > 0) {
outBuf.set(outBuf.get(i, value) + weightsBuf.get(i, j), i, value);
}
else {
outBuf.set(outBuf.get(i, value) + 1, i, value);
}
}
}
}
return outBuf;
}
//# sourceMappingURL=Bincount_impl.js.map
/***/ }),
/* 99 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return subImpl; });
/* unused harmony export subComplexImpl */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return sub; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return subConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(27);
/* harmony import */ var _utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const subImpl = Object(_utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__[/* createSimpleBinaryKernelImpl */ "a"])(((aValue, bValue) => aValue - bValue));
const subComplexImpl = Object(_utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__[/* createComplexBinaryKernelImpl */ "b"])(((aReal, aImag, bReal, bImag) => {
return { real: aReal - bReal, imag: aImag - bImag };
}));
const sub = Object(_utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__[/* binaryKernelFunc */ "a"])(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Sub"], subImpl, subComplexImpl);
const subConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Sub"],
backendName: 'cpu',
kernelFunc: sub
};
//# sourceMappingURL=Sub.js.map
/***/ }),
/* 100 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return tensor; });
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _tensor_ops_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(51);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with the provided values, shape and dtype.
*
* ```js
* // Pass an array of values to create a vector.
* tf.tensor([1, 2, 3, 4]).print();
* ```
*
* ```js
* // Pass a nested array of values to make a matrix or a higher
* // dimensional tensor.
* tf.tensor([[1, 2], [3, 4]]).print();
* ```
*
* ```js
* // Pass a flat array and specify a shape yourself.
* tf.tensor([1, 2, 3, 4], [2, 2]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`. If the values are strings,
* they will be encoded as utf-8 and kept as `Uint8Array[]`.
* @param shape The shape of the tensor. Optional. If not provided,
* it is inferred from `values`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor(values, shape, dtype) {
const inferredShape = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* inferShape */ "c"])(values, dtype);
return Object(_tensor_ops_util__WEBPACK_IMPORTED_MODULE_1__[/* makeTensor */ "a"])(values, shape, inferredShape, dtype);
}
//# sourceMappingURL=tensor.js.map
/***/ }),
/* 101 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return broadcastTo; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _clone__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(70);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Broadcast an array to a compatible shape NumPy-style.
*
* The tensor's shape is compared to the broadcast shape from end to beginning.
* Ones are prepended to the tensor's shape until is has the same length as
* the broadcast shape. If input.shape[i]==shape[i], the (i+1)-th axis is
* already broadcast-compatible. If input.shape[i]==1 and shape[i]==N, then
* the input tensor is tiled N times along that axis (using tf.tile).
*
* @param input The tensor that is to be broadcasted.
* @param shape The input is to be broadcast to this shape.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function broadcastTo_(x, shape) {
let input = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'broadcastTo', 'x');
const xShape = input.shape;
if (shape.some(d => !(d > 0) || d % 1 !== 0)) {
throw new Error(`broadcastTo(): Invalid broadcast shape [${shape}].`);
}
if (shape.length < input.rank) {
throw new Error(`broadcastTo(): shape.length=${shape.length} < input.rank=${input.rank}.`);
}
if (shape.length > input.rank) {
const newShape = input.shape.slice();
while (newShape.length < shape.length) {
newShape.unshift(1);
}
input = Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])(input, newShape);
}
const inputShape = input.shape;
const reps = Array.from(shape);
for (let i = shape.length - 1; i >= 0; i--) {
if (inputShape[i] === shape[i]) {
reps[i] = 1;
}
else if (input.shape[i] !== 1) {
throw new Error(`broadcastTo(): [${xShape}] cannot be broadcast to [${shape}].`);
}
}
const axes = reps.map((n, i) => n > 1 ? i : -1).filter(i => i >= 0);
if (axes.length === 0) {
return Object(_clone__WEBPACK_IMPORTED_MODULE_3__[/* clone */ "a"])(input);
}
// TODO call broadcastTo kernel directly once backends implement broadcstTo
const inputs = { x: input };
const attrs = { reps };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Tile */ "Vc"], inputs, attrs);
}
const broadcastTo = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ broadcastTo_ });
//# sourceMappingURL=broadcast_to.js.map
/***/ }),
/* 102 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return MPRandGauss; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return RandGamma; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return UniformRandom; });
/* unused harmony export jarqueBeraNormalityTest */
/* unused harmony export expectArrayInMeanStdRange */
/* harmony import */ var seedrandom__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(86);
/* harmony import */ var seedrandom__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(seedrandom__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _test_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(139);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// https://en.wikipedia.org/wiki/Marsaglia_polar_method
class MPRandGauss {
constructor(mean, stdDeviation, dtype, truncated, seed) {
this.mean = mean;
this.stdDev = stdDeviation;
this.dtype = dtype;
this.nextVal = NaN;
this.truncated = truncated;
if (this.truncated) {
this.upper = this.mean + this.stdDev * 2;
this.lower = this.mean - this.stdDev * 2;
}
const seedValue = seed ? seed : Math.random();
this.random = seedrandom__WEBPACK_IMPORTED_MODULE_0__["alea"](seedValue.toString());
}
/** Returns next sample from a Gaussian distribution. */
nextValue() {
if (!isNaN(this.nextVal)) {
const value = this.nextVal;
this.nextVal = NaN;
return value;
}
let resultX, resultY;
let isValid = false;
while (!isValid) {
let v1, v2, s;
do {
v1 = 2 * this.random() - 1;
v2 = 2 * this.random() - 1;
s = v1 * v1 + v2 * v2;
} while (s >= 1 || s === 0);
const mul = Math.sqrt(-2.0 * Math.log(s) / s);
resultX = this.mean + this.stdDev * v1 * mul;
resultY = this.mean + this.stdDev * v2 * mul;
if (!this.truncated || this.isValidTruncated(resultX)) {
isValid = true;
}
}
if (!this.truncated || this.isValidTruncated(resultY)) {
this.nextVal = this.convertValue(resultY);
}
return this.convertValue(resultX);
}
/** Handles proper rounding for non-floating-point numbers. */
convertValue(value) {
if (this.dtype == null || this.dtype === 'float32') {
return value;
}
return Math.round(value);
}
/** Returns true if less than 2-standard-deviations from the mean. */
isValidTruncated(value) {
return value <= this.upper && value >= this.lower;
}
}
// Marsaglia, George, and Wai Wan Tsang. 2000. "A Simple Method for Generating
// Gamma Variables."
class RandGamma {
constructor(alpha, beta, dtype, seed) {
this.alpha = alpha;
this.beta = 1 / beta; // convert rate to scale parameter
this.dtype = dtype;
const seedValue = seed ? seed : Math.random();
this.randu = seedrandom__WEBPACK_IMPORTED_MODULE_0__["alea"](seedValue.toString());
this.randn = new MPRandGauss(0, 1, dtype, false, this.randu());
if (alpha < 1) {
this.d = alpha + (2 / 3);
}
else {
this.d = alpha - (1 / 3);
}
this.c = 1 / Math.sqrt(9 * this.d);
}
/** Returns next sample from a gamma distribution. */
nextValue() {
let x2, v0, v1, x, u, v;
while (true) {
do {
x = this.randn.nextValue();
v = 1 + (this.c * x);
} while (v <= 0);
v *= v * v;
x2 = x * x;
v0 = 1 - (0.331 * x2 * x2);
v1 = (0.5 * x2) + (this.d * (1 - v + Math.log(v)));
u = this.randu();
if (u < v0 || Math.log(u) < v1) {
break;
}
}
v = (1 / this.beta) * this.d * v;
if (this.alpha < 1) {
v *= Math.pow(this.randu(), 1 / this.alpha);
}
return this.convertValue(v);
}
/** Handles proper rounding for non-floating-point numbers. */
convertValue(value) {
if (this.dtype === 'float32') {
return value;
}
return Math.round(value);
}
}
class UniformRandom {
constructor(min = 0, max = 1, dtype, seed) {
/** Handles proper rounding for non floating point numbers. */
this.canReturnFloat = () => (this.dtype == null || this.dtype === 'float32');
this.min = min;
this.range = max - min;
this.dtype = dtype;
if (seed == null) {
seed = Math.random();
}
if (typeof seed === 'number') {
seed = seed.toString();
}
if (!this.canReturnFloat() && this.range <= 1) {
throw new Error(`The difference between ${min} - ${max} <= 1 and dtype is not float`);
}
this.random = seedrandom__WEBPACK_IMPORTED_MODULE_0__["alea"](seed);
}
convertValue(value) {
if (this.canReturnFloat()) {
return value;
}
return Math.round(value);
}
nextValue() {
return this.convertValue(this.min + this.range * this.random());
}
}
function jarqueBeraNormalityTest(values) {
// https://en.wikipedia.org/wiki/Jarque%E2%80%93Bera_test
const n = values.length;
const s = skewness(values);
const k = kurtosis(values);
const jb = n / 6 * (Math.pow(s, 2) + 0.25 * Math.pow(k - 3, 2));
// JB test requires 2-degress of freedom from Chi-Square @ 0.95:
// http://www.itl.nist.gov/div898/handbook/eda/section3/eda3674.htm
const CHI_SQUARE_2DEG = 5.991;
if (jb > CHI_SQUARE_2DEG) {
throw new Error(`Invalid p-value for JB: ${jb}`);
}
}
function expectArrayInMeanStdRange(actual, expectedMean, expectedStdDev, epsilon) {
if (epsilon == null) {
epsilon = Object(_test_util__WEBPACK_IMPORTED_MODULE_1__["testEpsilon"])();
}
const actualMean = mean(actual);
Object(_test_util__WEBPACK_IMPORTED_MODULE_1__["expectNumbersClose"])(actualMean, expectedMean, epsilon);
Object(_test_util__WEBPACK_IMPORTED_MODULE_1__["expectNumbersClose"])(standardDeviation(actual, actualMean), expectedStdDev, epsilon);
}
function mean(values) {
let sum = 0;
for (let i = 0; i < values.length; i++) {
sum += values[i];
}
return sum / values.length;
}
function standardDeviation(values, mean) {
let squareDiffSum = 0;
for (let i = 0; i < values.length; i++) {
const diff = values[i] - mean;
squareDiffSum += diff * diff;
}
return Math.sqrt(squareDiffSum / values.length);
}
function kurtosis(values) {
// https://en.wikipedia.org/wiki/Kurtosis
const valuesMean = mean(values);
const n = values.length;
let sum2 = 0;
let sum4 = 0;
for (let i = 0; i < n; i++) {
const v = values[i] - valuesMean;
sum2 += Math.pow(v, 2);
sum4 += Math.pow(v, 4);
}
return (1 / n) * sum4 / Math.pow((1 / n) * sum2, 2);
}
function skewness(values) {
// https://en.wikipedia.org/wiki/Skewness
const valuesMean = mean(values);
const n = values.length;
let sum2 = 0;
let sum3 = 0;
for (let i = 0; i < n; i++) {
const v = values[i] - valuesMean;
sum2 += Math.pow(v, 2);
sum3 += Math.pow(v, 3);
}
return (1 / n) * sum3 / Math.pow((1 / (n - 1)) * sum2, 3 / 2);
}
//# sourceMappingURL=rand_util.js.map
/***/ }),
/* 103 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || new Function("return this")();
} catch (e) {
// This works if the window reference is available
if (typeof window === "object") g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 104 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return registerOp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getRegisteredOp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return deregisterOp; });
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const CUSTOM_OPS = {};
/**
* Register an Op for graph model executor. This allow you to register
* TensorFlow custom op or override existing op.
*
* Here is an example of registering a new MatMul Op.
* ```js
* const customMatmul = (node) =>
* tf.matMul(
* node.inputs[0], node.inputs[1],
* node.attrs['transpose_a'], node.attrs['transpose_b']);
*
* tf.registerOp('MatMul', customMatmul);
* ```
* The inputs and attrs of the node object is based on the TensorFlow op
* registry.
*
* @param name The Tensorflow Op name.
* @param opFunc An op function which is called with the current graph node
* during execution and needs to return a tensor or a list of tensors. The node
* has the following attributes:
* - attr: A map from attribute name to its value
* - inputs: A list of input tensors
*
* @doc {heading: 'Models', subheading: 'Op Registry'}
*/
function registerOp(name, opFunc) {
const opMapper = {
tfOpName: name,
category: 'custom',
inputs: [],
attrs: [],
customExecutor: opFunc
};
CUSTOM_OPS[name] = opMapper;
}
/**
* Retrieve the OpMapper object for the registered op.
*
* @param name The Tensorflow Op name.
*
* @doc {heading: 'Models', subheading: 'Op Registry'}
*/
function getRegisteredOp(name) {
return CUSTOM_OPS[name];
}
/**
* Deregister the Op for graph model executor.
*
* @param name The Tensorflow Op name.
*
* @doc {heading: 'Models', subheading: 'Op Registry'}
*/
function deregisterOp(name) {
delete CUSTOM_OPS[name];
}
//# sourceMappingURL=register.js.map
/***/ }),
/* 105 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return min; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the minimum value from the input.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the array is reduced by 1 for each entry in `axes`.
* If `keepDims` is true, the reduced dimensions are retained with length 1.
* If `axes` has no entries, all dimensions are reduced, and an array with a
* single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.min().print(); // or tf.min(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.min(axis).print(); // or tf.min(x, axis)
* ```
*
* @param x The input Tensor.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function min_(x, axis = null, keepDims = false) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'min');
const inputs = { x: $x };
const attrs = { axis, keepDims };
// tslint:disable-next-line: no-unnecessary-type-assertion
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Min */ "Qb"], inputs, attrs);
}
const min = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ min_ });
//# sourceMappingURL=min.js.map
/***/ }),
/* 106 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return oneHot; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a one-hot `tf.Tensor`. The locations represented by `indices` take
* value `onValue` (defaults to 1), while all other locations take value
* `offValue` (defaults to 0). If `indices` is rank `R`, the output has rank
* `R+1` with the last axis of size `depth`.
*
* ```js
* tf.oneHot(tf.tensor1d([0, 1], 'int32'), 3).print();
* ```
*
* @param indices `tf.Tensor` of indices with dtype `int32`.
* @param depth The depth of the one hot dimension.
* @param onValue A number used to fill in the output when the index matches
* the location.
* @param offValue A number used to fill in the output when the index does
* not match the location.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function oneHot_(indices, depth, onValue = 1, offValue = 0) {
if (depth < 2) {
throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`);
}
const $indices = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(indices, 'indices', 'oneHot', 'int32');
const inputs = { indices: $indices };
const attrs = { depth, onValue, offValue };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* OneHot */ "bc"], inputs, attrs);
}
const oneHot = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ oneHot_ });
//# sourceMappingURL=one_hot.js.map
/***/ }),
/* 107 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return real; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the real part of a complex (or real) tensor.
*
* Given a tensor input, this operation returns a tensor of type float that is
* the real part of each element in input considered as a complex number.
*
* If the input is real, it simply makes a clone.
*
* ```js
* const x = tf.complex([-2.25, 3.25], [4.75, 5.75]);
* tf.real(x).print();
* ```
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function real_(input) {
const $input = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(input, 'input', 'real');
const inputs = { input: $input };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Real */ "kc"], inputs);
}
const real = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ real_ });
//# sourceMappingURL=real.js.map
/***/ }),
/* 108 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ifft; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Inverse fast Fourier transform.
*
* Computes the inverse 1-dimensional discrete Fourier transform over the
* inner-most dimension of input.
*
* ```js
* const real = tf.tensor1d([1, 2, 3]);
* const imag = tf.tensor1d([1, 2, 3]);
* const x = tf.complex(real, imag);
*
* x.ifft().print(); // tf.spectral.ifft(x).print();
* ```
* @param input The complex input to compute an ifft over.
*
* @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}
*/
function ifft_(input) {
Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"])(input.dtype === 'complex64', () => `The dtype for tf.spectral.ifft() must be complex64 ` +
`but got ${input.dtype}.`);
const inputs = { input };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* IFFT */ "qb"], inputs);
}
const ifft = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ ifft_ });
//# sourceMappingURL=ifft.js.map
/***/ }),
/* 109 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global, process) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getGlobalNamespace; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return getGlobal; });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Note that the identifier globalNameSpace is scoped to this module, but will
// always resolve to the same global object regardless of how the module is
// resolved.
// tslint:disable-next-line:no-any
let globalNameSpace;
// tslint:disable-next-line:no-any
function getGlobalNamespace() {
if (globalNameSpace == null) {
// tslint:disable-next-line:no-any
let ns;
if (typeof (window) !== 'undefined') {
ns = window;
}
else if (typeof (global) !== 'undefined') {
ns = global;
}
else if (typeof (process) !== 'undefined') {
ns = process;
}
else if (typeof (self) !== 'undefined') {
ns = self;
}
else {
throw new Error('Could not find a global object');
}
globalNameSpace = ns;
}
return globalNameSpace;
}
// tslint:disable-next-line:no-any
function getGlobalMap() {
const ns = getGlobalNamespace();
if (ns._tfGlobals == null) {
ns._tfGlobals = new Map();
}
return ns._tfGlobals;
}
/**
* Returns a globally accessible 'singleton' object.
*
* @param key the name of the object
* @param init a function to initialize to initialize this object
* the first time it is fetched.
*/
function getGlobal(key, init) {
const globalMap = getGlobalMap();
if (globalMap.has(key)) {
return globalMap.get(key);
}
else {
const singleton = init();
globalMap.set(key, singleton);
return globalMap.get(key);
}
}
//# sourceMappingURL=global_util.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(103), __webpack_require__(142)))
/***/ }),
/* 110 */
/***/ (function(module, exports) {
module.exports = function(module) {
if (!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
if (!module.children) module.children = [];
Object.defineProperty(module, "loaded", {
enumerable: true,
get: function() {
return module.l;
}
});
Object.defineProperty(module, "id", {
enumerable: true,
get: function() {
return module.i;
}
});
module.webpackPolyfill = 1;
}
return module;
};
/***/ }),
/* 111 */
/***/ (function(module, exports) {
/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */
module.exports = __webpack_amd_options__;
/* WEBPACK VAR INJECTION */}.call(this, {}))
/***/ }),
/* 112 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validateUpdateShape", function() { return validateUpdateShape; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validateInput", function() { return validateInput; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "calculateShapes", function() { return calculateShapes; });
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
/**
* Check whether updates.shape = indices.shape[:batchDim] +
* shape[sliceDim:]
*
* @param x The input tensor.
*/
function validateUpdateShape(shape, indices, updates) {
const sliceDim = (indices.rank > 1) ? indices.shape[indices.rank - 1] : 1;
const batchDim = (indices.rank > 1) ? indices.rank - 1 : 1;
const shapeError = 'Must have updates.shape = indices.shape[:batchDim] + ' +
`shape[sliceDim:], got updates.shape: ${updates.shape}` +
`, indices.shape: ${indices.shape}, shape: ${shape}` +
`, sliceDim: ${sliceDim}, and batchDim: ${batchDim}.`;
if (updates.rank < batchDim) {
throw new Error(shapeError + ` update.rank < ${batchDim}. `);
}
if (shape.length < sliceDim + (updates.rank - batchDim)) {
throw new Error(shapeError +
` Output shape length < ${sliceDim + (updates.rank - batchDim)}`);
}
if (updates.rank !== batchDim + shape.length - sliceDim) {
throw new Error(shapeError + ` update.rank != ${batchDim + shape.length - sliceDim}`);
}
for (let d = 0; d < batchDim; ++d) {
if (updates.shape[d] !== indices.shape[d]) {
throw new Error(shapeError +
` updates.shape[${d}] (${updates.shape[d]}) != indices.shape[${d}] (${indices.shape[d]}).`);
}
}
for (let d = 0; d < updates.rank - batchDim; ++d) {
if (updates.shape[d + batchDim] !== shape[d + sliceDim]) {
throw new Error(shapeError +
` updates.shape[${d + batchDim}] (${updates.shape[d + batchDim]}) != shape[${d + batchDim}] (${shape[d + batchDim]})`);
}
}
}
/**
* Validate scatter nd inputs.
*
* @param update The tensor contains the update values.
* @param indices The tensor contains the indices for the update values.
* @param shape The shape of the output tensor.
*/
function validateInput(updates, indices, shape) {
if (indices.rank < 1) {
throw new Error('tf.scatterND() expects the indices to be rank 1 or higher,' +
` but the rank was ${indices.rank}.`);
}
if (updates.rank < 1) {
throw new Error('tf.scatterND() expects the updates to be rank 1 or higher,' +
` but the rank was ${updates.rank}.`);
}
if (indices.dtype !== 'int32') {
throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${indices.dtype}`);
}
if (shape.length < 1) {
throw new Error(`Output rank must be greater or equal to 1, but got shape: ${shape}`);
}
if (shape.length === 0) {
if (indices.size === 0) {
throw new Error(`Indices specified for empty output. indices shape: ${indices.shape}`);
}
if (updates.size === 0) {
throw new Error(`Updates specified for empty output. updates shape: ${updates.shape}`);
}
}
validateUpdateShape(shape, indices, updates);
}
/**
* Calculate the shape information for the output.
*
* @param update The tensor contains the update values.
* @param indices The tensor contains the indices for the update values.
* @param shape The shape of the output tensor.
*
* @returns ScatterShapeInfo
*/
function calculateShapes(updates, indices, shape) {
// Calculate the number of dimensions in indices
const indicesRank = indices.shape.length;
const sliceRank = (indicesRank > 1) ? indices.shape[indicesRank - 1] : 1;
// Calculate the number of elements that make up each slice of our updated
// tensor. This allows us to work with flattened tensors and copy over whole
// slices at a time.
const totalNd = shape.length;
let sliceSize = 1;
for (let i = sliceRank; i < totalNd; ++i) {
sliceSize *= shape[i];
}
const safeSliceDim = (sliceRank < 1) ? 1 : sliceRank;
const numUpdates = Object(_util__WEBPACK_IMPORTED_MODULE_0__[/* sizeFromShape */ "O"])(indices.shape) / safeSliceDim;
const strides = [...Object(_util__WEBPACK_IMPORTED_MODULE_0__[/* computeStrides */ "j"])(shape.slice(0, sliceRank)), 1];
const outputSize = Object(_util__WEBPACK_IMPORTED_MODULE_0__[/* sizeFromShape */ "O"])(shape);
return { sliceRank, numUpdates, sliceSize, strides, outputSize };
}
//# sourceMappingURL=scatter_nd_util.js.map
/***/ }),
/* 113 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "assertParamsValid", function() { return assertParamsValid; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "maskToAxes", function() { return maskToAxes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "computeOutShape", function() { return computeOutShape; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stridesWithElidedDims", function() { return stridesWithElidedDims; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNormalizedAxes", function() { return getNormalizedAxes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startIndicesWithElidedDims", function() { return startIndicesWithElidedDims; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stopIndicesWithElidedDims", function() { return stopIndicesWithElidedDims; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stridesForAxis", function() { return stridesForAxis; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startForAxis", function() { return startForAxis; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stopForAxis", function() { return stopForAxis; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSliceContinous", function() { return isSliceContinous; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "computeFlatOffset", function() { return computeFlatOffset; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseSliceParams", function() { return parseSliceParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sliceInfo", function() { return sliceInfo; });
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
/**
* @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 assertParamsValid(input, begin, size) {
const inputRank = input.shape.length;
_util__WEBPACK_IMPORTED_MODULE_0__[/* assert */ "b"](inputRank === begin.length, () => `Error in slice${inputRank}D: Length of begin ${begin} must ` +
`match the rank of the array (${inputRank}).`);
_util__WEBPACK_IMPORTED_MODULE_0__[/* assert */ "b"](inputRank === size.length, () => `Error in slice${inputRank}D: Length of size ${size} must ` +
`match the rank of the array (${inputRank}).`);
for (let i = 0; i < inputRank; ++i) {
_util__WEBPACK_IMPORTED_MODULE_0__[/* assert */ "b"](begin[i] + size[i] <= input.shape[i], () => `Error in slice${inputRank}D: begin[${i}] + size[${i}] ` +
`(${begin[i] + size[i]}) would overflow input.shape[${i}] (${input.shape[i]})`);
}
}
/** Converts a binary mask to an array of axes. Used in stridedSlice(). */
function maskToAxes(mask) {
const axes = [];
let axis = 0;
while (mask > 0) {
if (mask & 1) {
axes.push(axis);
}
mask /= 2;
axis++;
}
return axes;
}
/** Computes the output shape given the strided slice params. */
function computeOutShape(begin, end, strides) {
const size = [];
for (let axis = 0; axis < begin.length; axis++) {
size[axis] = Math.ceil((end[axis] - begin[axis]) / strides[axis]);
}
return size;
}
// Creates full selection at the elided dimensions. If the dimension matches
// the ellipsis mask, override the current stride value. Otherwise, insert.
function stridesWithElidedDims(strides, ellipsisInsertionIndex, numElidedAxes, inputShape) {
const newStrides = [...strides];
for (let i = newStrides.length; i < inputShape.length; i++) {
newStrides.push(1);
}
for (let i = 0; i < numElidedAxes; i++) {
if (i === 0) {
newStrides[ellipsisInsertionIndex] = 1;
}
else {
newStrides.splice(ellipsisInsertionIndex, 0 /* num elements to delete */, 1 /* element to add */);
newStrides.pop();
}
}
return newStrides;
}
function unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, normalizedAxis) {
if (normalizedAxis <= ellipsisInsertionIndex) {
return normalizedAxis;
}
return normalizedAxis - (numElidedAxes - 1);
}
function getElidedAxes(numElidedAxes, ellipsisInsertionIndex) {
const elidedAxes = [];
for (let i = 0; i < numElidedAxes; i++) {
elidedAxes.push(ellipsisInsertionIndex + i);
}
return elidedAxes;
}
// Normalize the start, end and strides.
function getNormalizedAxes(inputShape, ellipsisAxes, numInterpolatedAxes, begin, end, strides, beginMask, endMask, ellipsisMask) {
const inputRank = inputShape.length;
let normalizedBegin = new Array(inputRank), normalizedEnd = new Array(inputRank), normalizedStrides = new Array(inputRank);
if (ellipsisAxes.length && numInterpolatedAxes > 0) {
const fullIndex = ellipsisAxes[0];
// The ellipsis applies to the masked index as well as any dimensions
// that are interpolated.
const numElidedAxes = numInterpolatedAxes + 1;
normalizedBegin = startIndicesWithElidedDims(beginMask, fullIndex, numElidedAxes, begin, inputShape);
normalizedEnd = stopIndicesWithElidedDims(endMask, fullIndex, numElidedAxes, end, inputShape);
normalizedStrides =
stridesWithElidedDims(strides, fullIndex, numElidedAxes, inputShape);
}
else {
for (let axis = 0; axis < inputRank; axis++) {
normalizedBegin[axis] = startForAxis(beginMask, begin, strides, inputShape, axis, ellipsisMask);
normalizedEnd[axis] =
stopForAxis(endMask, end, strides, inputShape, axis, ellipsisMask);
normalizedStrides[axis] = stridesForAxis(strides, axis, ellipsisMask);
}
}
return {
begin: normalizedBegin,
end: normalizedEnd,
strides: normalizedStrides
};
}
// Creates full selection at the elided dimensions. If the dimension matches
// the ellipsis mask, override the current start value. Otherwise, insert.
function startIndicesWithElidedDims(beginMask, ellipsisInsertionIndex, numElidedAxes, originalBegin, inputShape) {
const newIndices = [...inputShape];
const elidedAxes = getElidedAxes(numElidedAxes, ellipsisInsertionIndex);
for (let axis = 0; axis < newIndices.length; axis++) {
if (elidedAxes.indexOf(axis) > -1) {
newIndices[axis] = 0;
}
else {
const originalAxis = unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, axis);
let originalValue = originalBegin[originalAxis];
if (beginMask & 1 << originalAxis) {
originalValue = 0;
}
newIndices[axis] = originalValue;
}
}
return newIndices;
}
// Creates full selection at the elided dimensions. If the dimension matches
// the ellipsis mask, override the current stop value. Otherwise, insert.
function stopIndicesWithElidedDims(endMask, ellipsisInsertionIndex, numElidedAxes, originalEnd, inputShape) {
const newIndices = [...inputShape];
const elidedAxes = getElidedAxes(numElidedAxes, ellipsisInsertionIndex);
for (let axis = 0; axis < newIndices.length; axis++) {
if (elidedAxes.indexOf(axis) > -1) {
newIndices[axis] = Number.MAX_SAFE_INTEGER;
}
else {
const originalAxis = unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, axis);
let originalValue = originalEnd[originalAxis];
if (endMask & 1 << originalAxis) {
originalValue = Number.MAX_SAFE_INTEGER;
}
newIndices[axis] = originalValue;
}
}
for (let i = 0; i < newIndices.length; i++) {
// Handle negative indices
const axisSize = inputShape[i];
if (newIndices[i] < 0) {
newIndices[i] += axisSize;
}
newIndices[i] = _util__WEBPACK_IMPORTED_MODULE_0__[/* clamp */ "i"](0, newIndices[i], inputShape[i]);
}
return newIndices;
}
function stridesForAxis(strides, axis, ellipsisMask) {
let stride = strides[axis];
if (ellipsisMask & (1 << axis) || stride == null) {
stride = 1;
}
return stride;
}
function startForAxis(beginMask, startIndices, strides, inputShape, axis, ellipsisMask) {
// Begin with the specified index
let start = startIndices[axis];
const stride = strides[axis] || 1;
// Check the axis bit from right of masked axes, or the begin index is not set
// for the axis.
if (beginMask & 1 << axis || ellipsisMask & 1 << axis || start == null) {
if (stride > 0) {
// Forward iteration - use the first element. These values will get
// clamped below (Note: We could have set them to 0 and axis_size-1, but
// use lowest() and max() to maintain symmetry with StopForAxis())
start = Number.MIN_SAFE_INTEGER;
}
else {
// Backward iteration - use the last element.
start = Number.MAX_SAFE_INTEGER;
}
}
// Handle negative indices
const axisSize = inputShape[axis];
if (start < 0) {
start += axisSize;
}
// Clamping
start = _util__WEBPACK_IMPORTED_MODULE_0__[/* clamp */ "i"](0, start, axisSize - 1);
return start;
}
function stopForAxis(endMask, stopIndices, strides, inputShape, axis, ellipsisMask) {
// Begin with the specified index
let stop = stopIndices[axis];
const stride = strides[axis] || 1;
// Check the axis bit from right of masked axes, or if the stop index is not
// set for this axis.
if (endMask & (1 << axis) || ellipsisMask & (1 << axis) || stop == null) {
if (stride > 0) {
// Forward iteration - use the last element. These values will get
// clamped below
stop = Number.MAX_SAFE_INTEGER;
}
else {
// Backward iteration - use the first element.
stop = Number.MIN_SAFE_INTEGER;
}
}
// Handle negative indices
const axisSize = inputShape[axis];
if (stop < 0) {
stop += axisSize;
}
// Clamping
// Because the end index points one past the last element, we need slightly
// different clamping ranges depending on the direction.
if (stride > 0) {
// Forward iteration
stop = _util__WEBPACK_IMPORTED_MODULE_0__[/* clamp */ "i"](0, stop, axisSize);
}
else {
// Backward iteration
stop = _util__WEBPACK_IMPORTED_MODULE_0__[/* clamp */ "i"](-1, stop, axisSize - 1);
}
return stop;
}
/**
* Returns true if the slice occupies a continous set of elements in the
* 'flat' space.
*/
function isSliceContinous(shape, begin, size) {
// Index of the first axis that has size > 1.
let firstNonOneAxis = size.length;
for (let i = 0; i < size.length; i++) {
if (size[i] > 1) {
firstNonOneAxis = i;
break;
}
}
for (let i = firstNonOneAxis + 1; i < size.length; i++) {
if (begin[i] > 0 || size[i] !== shape[i]) {
return false;
}
}
return true;
}
function computeFlatOffset(begin, strides) {
let flatOffset = begin.length > 0 ? begin[begin.length - 1] : 1;
for (let i = 0; i < begin.length - 1; i++) {
flatOffset += begin[i] * strides[i];
}
return flatOffset;
}
function parseSliceParams(x, begin, size) {
// The following logic allows for more ergonomic calls.
let begin_;
const xRank = x.shape.length;
if (typeof begin === 'number') {
begin_ = [begin, ...new Array(xRank - 1).fill(0)];
}
else if (begin.length < xRank) {
begin_ = begin.concat(new Array(xRank - begin.length).fill(0));
}
else {
begin_ = begin.slice();
}
begin_.forEach(d => {
_util__WEBPACK_IMPORTED_MODULE_0__[/* assert */ "b"](d !== -1, () => 'slice() does not support negative begin indexing.');
});
let size_;
if (size == null) {
size_ = new Array(xRank).fill(-1);
}
else if (typeof size === 'number') {
size_ = [size, ...new Array(xRank - 1).fill(-1)];
}
else if (size.length < xRank) {
size_ = size.concat(new Array(xRank - size.length).fill(-1));
}
else {
size_ = size;
}
size_ = size_.map((d, i) => {
if (d >= 0) {
return d;
}
else {
_util__WEBPACK_IMPORTED_MODULE_0__[/* assert */ "b"](d === -1, () => `Negative size values should be exactly -1 but got ` +
`${d} for the slice() size at index ${i}.`);
return x.shape[i] - begin_[i];
}
});
return [begin_, size_];
}
function sliceInfo(xShape, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask) {
// make a copy because it may be modified further down.
let $begin = begin.slice();
let $end = end.slice();
let $strides = strides;
if (strides == null) {
$strides = new Array($begin.length);
}
const ellipsisAxes = maskToAxes(ellipsisMask);
if (ellipsisAxes.length > 1) {
throw new Error('Multiple ellipses in slice is not allowed.');
}
if (ellipsisMask !== 0 && newAxisMask !== 0) {
throw new Error('Using both ellipsisMask and newAxisMask is not yet supported.');
}
if (ellipsisMask !== 0 && shrinkAxisMask !== 0) {
throw new Error('Using both ellipsisMask and shrinkAxisMask is not yet supported.');
}
const numInterpolatedAxes = xShape.length - $begin.length;
// Expand the dims of x based on the newAxisMask.
const expandAxes = maskToAxes(newAxisMask);
const newShape = xShape.slice();
expandAxes.forEach(axis => {
$begin[axis] = 0;
$end[axis] = 1;
newShape.splice(axis, 0, 1);
});
const { begin: normalizedBegin, end: normalizedEnd, strides: normalizedStrides } = getNormalizedAxes(newShape, ellipsisAxes, numInterpolatedAxes, $begin, $end, $strides, beginMask, endMask, ellipsisMask);
$begin = normalizedBegin;
$end = normalizedEnd;
$strides = normalizedStrides;
const shrinkAxes = maskToAxes(shrinkAxisMask);
// Adjust the ends based on the shrink mask.
shrinkAxes.forEach(axis => {
$end[axis] = $begin[axis] + 1;
$strides[axis] = 1;
});
// Figure out the output shape.
const size = computeOutShape($begin, $end, $strides);
// Remove the axes based on shrinkMask.
const outShape = size.filter((_, axis) => shrinkAxes.indexOf(axis) === -1);
const nonStrided = $strides.every(v => v === 1);
return { nonStrided, $begin, $end, $strides, size, newShape, outShape };
}
//# sourceMappingURL=slice_util.js.map
/***/ }),
/* 114 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return floorDiv; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(23);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.
* The result is rounded with floor function.
*
*
* ```js
* const a = tf.tensor1d([1, 4, 9, 16]);
* const b = tf.tensor1d([1, 2, 3, 4]);
*
* a.floorDiv(b).print(); // or tf.div(a, b)
* ```
*
* ```js
* // Broadcast div a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(2);
*
* a.floorDiv(b).print(); // or tf.floorDiv(a, b)
* ```
*
* @param a The first tensor as the numerator.
* @param b The second tensor as the denominator. Must have the same dtype as
* `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function floorDiv_(a, b) {
let $a = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(a, 'a', 'floorDiv');
let $b = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(b, 'b', 'floorDiv');
[$a, $b] = Object(_tensor_util__WEBPACK_IMPORTED_MODULE_2__["makeTypesMatch"])($a, $b);
const inputs = { a: $a, b: $b };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* FloorDiv */ "hb"], inputs);
}
const floorDiv = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ floorDiv_ });
//# sourceMappingURL=floorDiv.js.map
/***/ }),
/* 115 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return fill; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(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.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` filled with a scalar value.
*
* ```js
* tf.fill([2, 2], 4).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param value The scalar value to fill the tensor with.
* @param dtype The type of an element in the resulting tensor. Defaults to
* 'float'.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function fill(shape, value, dtype) {
const attrs = { shape, value, dtype };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Fill */ "eb"], {}, attrs);
}
//# sourceMappingURL=fill.js.map
/***/ }),
/* 116 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return avgPool; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _cast__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(12);
/* harmony import */ var _conv_util__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(31);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the 2D average pooling of an image.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad The type of padding algorithm:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function avgPool_(x, filterSize, strides, pad, dimRoundingMode) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'avgPool', 'float32');
const dilations = 1;
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](_conv_util__WEBPACK_IMPORTED_MODULE_5__[/* eitherStridesOrDilationsAreOne */ "h"](strides, dilations), () => 'Error in avgPool: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = Object(_reshape__WEBPACK_IMPORTED_MODULE_7__[/* reshape */ "a"])($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](x4D.rank === 4, () => `Error in avgPool: x must be rank 4 but got rank ${x4D.rank}.`);
if (dimRoundingMode != null) {
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](_util__WEBPACK_IMPORTED_MODULE_3__[/* isInt */ "v"](pad), () => `Error in avgPool: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x4D };
const attrs = { filterSize, strides, pad, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
let res = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* AvgPool */ "o"], inputs, attrs);
res = Object(_cast__WEBPACK_IMPORTED_MODULE_4__[/* cast */ "a"])(res, $x.dtype);
if (reshapedTo4D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_7__[/* reshape */ "a"])(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const avgPool = Object(_operation__WEBPACK_IMPORTED_MODULE_6__[/* op */ "b"])({ avgPool_ });
//# sourceMappingURL=avg_pool.js.map
/***/ }),
/* 117 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return cos; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes cos of the input `tf.Tensor` element-wise: `cos(x)`
*
* ```js
* const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);
*
* x.cos().print(); // or tf.cos(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function cos_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'cos');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Cos */ "I"], inputs);
}
const cos = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ cos_ });
//# sourceMappingURL=cos.js.map
/***/ }),
/* 118 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return cumsum; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the cumulative sum of a `tf.Tensor` along `axis`.
*
* ```js
* const x = tf.tensor([1, 2, 3, 4]);
* x.cumsum().print();
* ```
* ```js
* const x = tf.tensor([[1, 2], [3, 4]]);
* x.cumsum().print();
* ```
*
* @param x The input tensor to be summed.
* @param axis The axis along which to sum. Optional. Defaults to 0.
* @param exclusive Whether to perform exclusive cumulative sum. Optional.
* Defaults to false. If set to true then the sum of each tensor entry
* does not include its own value, but only the values previous to it
* along the specified axis.
* @param reverse Whether to sum in the opposite direction. Optional.
* Defaults to false.
*
* @doc {heading: 'Operations', subheading: 'Scan'}
*/
function cumsum_(x, axis = 0, exclusive = false, reverse = false) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'cumsum');
const inputs = { x: $x };
const attrs = { axis, exclusive, reverse };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Cumsum */ "L"], inputs, attrs);
}
const cumsum = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ cumsum_ });
//# sourceMappingURL=cumsum.js.map
/***/ }),
/* 119 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return elu; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes exponential linear element-wise: `x > 0 ? e ^ x - 1 : 0`.
*
* ```js
* const x = tf.tensor1d([-1, 1, -3, 2]);
*
* x.elu().print(); // or tf.elu(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function elu_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'elu');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Elu */ "W"], inputs);
}
const elu = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ elu_ });
//# sourceMappingURL=elu.js.map
/***/ }),
/* 120 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return floor; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes floor of input `tf.Tensor` element-wise: `floor(x)`.
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3]);
*
* x.floor().print(); // or tf.floor(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function floor_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'floor');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Floor */ "gb"], inputs);
}
const floor = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ floor_ });
//# sourceMappingURL=floor.js.map
/***/ }),
/* 121 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return imag; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the imaginary part of a complex (or real) tensor.
*
* Given a tensor input, this operation returns a tensor of type float that is
* the imaginary part of each element in input considered as a complex number.
* If input is real, a tensor of all zeros is returned.
*
* ```js
* const x = tf.complex([-2.25, 3.25], [4.75, 5.75]);
* tf.imag(x).print();
* ```
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function imag_(input) {
const $input = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(input, 'input', 'imag');
const inputs = { input: $input };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Imag */ "sb"], inputs);
}
const imag = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ imag_ });
//# sourceMappingURL=imag.js.map
/***/ }),
/* 122 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return leakyRelu; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes leaky rectified linear element-wise.
*
* See
* [http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf](
* http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf)
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.leakyRelu(0.1).print(); // or tf.leakyRelu(x, 0.1)
* ```
* @param x The input tensor.
* @param alpha The scaling factor for negative values, defaults to 0.2.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function leakyRelu_(x, alpha = 0.2) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'leakyRelu');
const inputs = { x: $x };
const attrs = { alpha };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* LeakyRelu */ "yb"], inputs, attrs);
}
const leakyRelu = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ leakyRelu_ });
//# sourceMappingURL=leaky_relu.js.map
/***/ }),
/* 123 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return less; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(23);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2);
/* harmony import */ var _broadcast_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(17);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of (a < b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.less(b).print();
* ```
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function less_(a, b) {
let $a = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(a, 'a', 'less');
let $b = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(b, 'b', 'less');
[$a, $b] = Object(_tensor_util__WEBPACK_IMPORTED_MODULE_2__["makeTypesMatch"])($a, $b);
Object(_broadcast_util__WEBPACK_IMPORTED_MODULE_4__[/* assertAndGetBroadcastShape */ "a"])($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Less */ "zb"], inputs);
}
const less = Object(_operation__WEBPACK_IMPORTED_MODULE_5__[/* op */ "b"])({ less_ });
//# sourceMappingURL=less.js.map
/***/ }),
/* 124 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return logSumExp; });
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
/* harmony import */ var _add__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(13);
/* harmony import */ var _axis_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(39);
/* harmony import */ var _exp__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(41);
/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(75);
/* harmony import */ var _max__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(72);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(7);
/* harmony import */ var _sub__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(14);
/* harmony import */ var _sum__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(19);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the log(sum(exp(elements across the reduction dimensions)).
*
* Reduces the input along the dimensions given in `axis`. Unless `keepDims`
* is true, the rank of the array is reduced by 1 for each entry in `axis`.
* If `keepDims` is true, the reduced dimensions are retained with length 1.
* If `axis` has no entries, all dimensions are reduced, and an array with a
* single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.logSumExp().print(); // or tf.logSumExp(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.logSumExp(axis).print(); // or tf.logSumExp(a, axis)
* ```
* @param x The input tensor.
* @param axis The dimension(s) to reduce. If null (the default),
* reduces all dimensions.
* @param keepDims If true, retains reduced dimensions with length
* of 1. Defaults to false.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function logSumExp_(x, axis = null, keepDims = false) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* convertToTensor */ "a"])(x, 'x', 'logSumExp');
const axes = Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* parseAxisParam */ "I"])(axis, $x.shape);
const xMax = Object(_max__WEBPACK_IMPORTED_MODULE_6__[/* max */ "a"])($x, axes, true /* keepDims */);
const a = Object(_sub__WEBPACK_IMPORTED_MODULE_9__[/* sub */ "a"])($x, xMax);
const b = Object(_exp__WEBPACK_IMPORTED_MODULE_4__[/* exp */ "a"])(a);
const c = Object(_sum__WEBPACK_IMPORTED_MODULE_10__[/* sum */ "a"])(b, axes);
const d = Object(_log__WEBPACK_IMPORTED_MODULE_5__[/* log */ "a"])(c);
const res = Object(_add__WEBPACK_IMPORTED_MODULE_2__[/* add */ "a"])(Object(_reshape__WEBPACK_IMPORTED_MODULE_8__[/* reshape */ "a"])(xMax, d.shape), d);
if (keepDims) {
const newShape = Object(_axis_util__WEBPACK_IMPORTED_MODULE_3__[/* expandShapeToKeepDim */ "e"])(res.shape, axes);
return Object(_reshape__WEBPACK_IMPORTED_MODULE_8__[/* reshape */ "a"])(res, newShape);
}
return res;
}
const logSumExp = Object(_operation__WEBPACK_IMPORTED_MODULE_7__[/* op */ "b"])({ logSumExp_ });
//# sourceMappingURL=log_sum_exp.js.map
/***/ }),
/* 125 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return logicalOr; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _broadcast_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(17);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of `a OR b` element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([false, false, true, true], 'bool');
* const b = tf.tensor1d([false, true, false, true], 'bool');
*
* a.logicalOr(b).print();
* ```
* @param a The first input tensor. Must be of dtype bool.
* @param b The second input tensor. Must be of dtype bool.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function logicalOr_(a, b) {
const $a = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(a, 'a', 'logicalOr', 'bool');
const $b = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(b, 'b', 'logicalOr', 'bool');
Object(_broadcast_util__WEBPACK_IMPORTED_MODULE_3__[/* assertAndGetBroadcastShape */ "a"])($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* LogicalOr */ "Hb"], inputs);
}
const logicalOr = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ logicalOr_ });
//# sourceMappingURL=logical_or.js.map
/***/ }),
/* 126 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return maxPool; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _conv_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(31);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the 2D max pooling of an image.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in dilated pooling. Defaults to `[1, 1]`. If `dilations` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function maxPool_(x, filterSize, strides, pad, dimRoundingMode) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'maxPool');
const dilations = 1;
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = Object(_reshape__WEBPACK_IMPORTED_MODULE_6__[/* reshape */ "a"])($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](x4D.rank === 4, () => `Error in maxPool: input must be rank 4 but got rank ${x4D.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](_conv_util__WEBPACK_IMPORTED_MODULE_4__[/* eitherStridesOrDilationsAreOne */ "h"](strides, dilations), () => 'Error in maxPool: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
if (dimRoundingMode != null) {
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](_util__WEBPACK_IMPORTED_MODULE_3__[/* isInt */ "v"](pad), () => `Error in maxPool: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x4D };
const attrs = { filterSize, strides, pad, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* MaxPool */ "Jb"], inputs, attrs);
if (reshapedTo4D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_6__[/* reshape */ "a"])(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const maxPool = Object(_operation__WEBPACK_IMPORTED_MODULE_5__[/* op */ "b"])({ maxPool_ });
//# sourceMappingURL=max_pool.js.map
/***/ }),
/* 127 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return minimum; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(23);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2);
/* harmony import */ var _broadcast_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(17);
/* harmony import */ var _cast__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(12);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the min of a and b (`a < b ? a : b`) element-wise.
* Supports broadcasting.
*
* We also expose `minimumStrict` which has the same signature as this op and
* asserts that `a` and `b` are the same shape (does not broadcast).
*
* ```js
* const a = tf.tensor1d([1, 4, 3, 16]);
* const b = tf.tensor1d([1, 2, 9, 4]);
*
* a.minimum(b).print(); // or tf.minimum(a, b)
* ```
*
* ```js
* // Broadcast minimum a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(5);
*
* a.minimum(b).print(); // or tf.minimum(a, b)
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function minimum_(a, b) {
let $a = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(a, 'a', 'minimum');
let $b = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(b, 'b', 'minimum');
[$a, $b] = Object(_tensor_util__WEBPACK_IMPORTED_MODULE_2__["makeTypesMatch"])($a, $b);
if ($a.dtype === 'bool') {
$a = Object(_cast__WEBPACK_IMPORTED_MODULE_5__[/* cast */ "a"])($a, 'int32');
$b = Object(_cast__WEBPACK_IMPORTED_MODULE_5__[/* cast */ "a"])($b, 'int32');
}
Object(_broadcast_util__WEBPACK_IMPORTED_MODULE_4__[/* assertAndGetBroadcastShape */ "a"])($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Minimum */ "Rb"], inputs);
}
const minimum = Object(_operation__WEBPACK_IMPORTED_MODULE_6__[/* op */ "b"])({ minimum_ });
//# sourceMappingURL=minimum.js.map
/***/ }),
/* 128 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return notEqual; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(23);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2);
/* harmony import */ var _broadcast_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(17);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of (a != b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([0, 2, 3]);
*
* a.notEqual(b).print();
* ```
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function notEqual_(a, b) {
let $a = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(a, 'a', 'notEqual');
let $b = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(b, 'b', 'notEqual');
[$a, $b] = Object(_tensor_util__WEBPACK_IMPORTED_MODULE_2__["makeTypesMatch"])($a, $b);
Object(_broadcast_util__WEBPACK_IMPORTED_MODULE_4__[/* assertAndGetBroadcastShape */ "a"])($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* NotEqual */ "ac"], inputs);
}
const notEqual = Object(_operation__WEBPACK_IMPORTED_MODULE_5__[/* op */ "b"])({ notEqual_ });
//# sourceMappingURL=not_equal.js.map
/***/ }),
/* 129 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return prelu; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes leaky rectified linear element-wise with parametric alphas.
*
* `x < 0 ? alpha * x : f(x) = x`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
* const alpha = tf.scalar(0.1);
*
* x.prelu(alpha).print(); // or tf.prelu(x, alpha)
* ```
* @param x The input tensor.
* @param alpha Scaling factor for negative values.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function prelu_(x, alpha) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'prelu');
const $alpha = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(alpha, 'alpha', 'prelu');
const inputs = { x: $x, alpha: $alpha };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Prelu */ "hc"], inputs);
}
const prelu = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ prelu_ });
//# sourceMappingURL=prelu.js.map
/***/ }),
/* 130 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return relu6; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes rectified linear 6 element-wise: `min(max(x, 0), 6)`.
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 8]);
*
* x.relu6().print(); // or tf.relu6(x)
* ```
* @param x The input tensor. If the dtype is `bool`, the output dtype will be
* `int32'.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function relu6_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'relu6');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Relu6 */ "oc"], inputs);
}
const relu6 = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ relu6_ });
//# sourceMappingURL=relu6.js.map
/***/ }),
/* 131 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return fft; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Fast Fourier transform.
*
* Computes the 1-dimensional discrete Fourier transform over the inner-most
* dimension of input.
*
* ```js
* const real = tf.tensor1d([1, 2, 3]);
* const imag = tf.tensor1d([1, 2, 3]);
* const x = tf.complex(real, imag);
*
* x.fft().print(); // tf.spectral.fft(x).print();
* ```
* @param input The complex input to compute an fft over.
*
* @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}
*/
function fft_(input) {
Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"])(input.dtype === 'complex64', () => `The dtype for tf.spectral.fft() must be complex64 ` +
`but got ${input.dtype}.`);
const inputs = { input };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* FFT */ "db"], inputs);
}
const fft = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ fft_ });
//# sourceMappingURL=fft.js.map
/***/ }),
/* 132 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return rfft; });
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
/* harmony import */ var _complex__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(58);
/* harmony import */ var _concat__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(32);
/* harmony import */ var _imag__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(121);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/* harmony import */ var _real__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(107);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7);
/* harmony import */ var _slice__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(28);
/* harmony import */ var _split__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(76);
/* harmony import */ var _zeros__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(80);
/* harmony import */ var _zeros_like__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(20);
/* harmony import */ var _fft__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(131);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Real value input fast Fourier transform.
*
* Computes the 1-dimensional discrete Fourier transform over the
* inner-most dimension of the real input.
*
* ```js
* const real = tf.tensor1d([1, 2, 3]);
*
* real.rfft().print();
* ```
* @param input The real value input to compute an rfft over.
*
* @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}
*/
function rfft_(input, fftLength) {
Object(_util__WEBPACK_IMPORTED_MODULE_0__[/* assert */ "b"])(input.dtype === 'float32', () => `The dtype for rfft() must be real value but got ${input.dtype}`);
let innerDimensionSize = input.shape[input.shape.length - 1];
const batch = input.size / innerDimensionSize;
let adjustedInput;
if (fftLength != null && fftLength < innerDimensionSize) {
// Need to crop
const begin = input.shape.map(v => 0);
const size = input.shape.map(v => v);
size[input.shape.length - 1] = fftLength;
adjustedInput = Object(_slice__WEBPACK_IMPORTED_MODULE_7__[/* slice */ "a"])(input, begin, size);
innerDimensionSize = fftLength;
}
else if (fftLength != null && fftLength > innerDimensionSize) {
// Need to pad with zeros
const zerosShape = input.shape.map(v => v);
zerosShape[input.shape.length - 1] = fftLength - innerDimensionSize;
adjustedInput = Object(_concat__WEBPACK_IMPORTED_MODULE_2__[/* concat */ "a"])([input, Object(_zeros__WEBPACK_IMPORTED_MODULE_9__[/* zeros */ "a"])(zerosShape)], input.shape.length - 1);
innerDimensionSize = fftLength;
}
else {
adjustedInput = input;
}
// Complement the input with zero imaginary numbers.
const zerosInput = Object(_zeros_like__WEBPACK_IMPORTED_MODULE_10__[/* zerosLike */ "a"])(adjustedInput);
const complexInput = Object(_reshape__WEBPACK_IMPORTED_MODULE_6__[/* reshape */ "a"])(Object(_complex__WEBPACK_IMPORTED_MODULE_1__[/* complex */ "a"])(adjustedInput, zerosInput), [batch, innerDimensionSize]);
const ret = Object(_fft__WEBPACK_IMPORTED_MODULE_11__[/* fft */ "a"])(complexInput);
// Exclude complex conjugations. These conjugations are put symmetrically.
const half = Math.floor(innerDimensionSize / 2) + 1;
const realValues = Object(_real__WEBPACK_IMPORTED_MODULE_5__[/* real */ "a"])(ret);
const imagValues = Object(_imag__WEBPACK_IMPORTED_MODULE_3__[/* imag */ "a"])(ret);
const realComplexConjugate = Object(_split__WEBPACK_IMPORTED_MODULE_8__[/* split */ "a"])(realValues, [half, innerDimensionSize - half], realValues.shape.length - 1);
const imagComplexConjugate = Object(_split__WEBPACK_IMPORTED_MODULE_8__[/* split */ "a"])(imagValues, [half, innerDimensionSize - half], imagValues.shape.length - 1);
const outputShape = adjustedInput.shape.slice();
outputShape[adjustedInput.shape.length - 1] = half;
return Object(_reshape__WEBPACK_IMPORTED_MODULE_6__[/* reshape */ "a"])(Object(_complex__WEBPACK_IMPORTED_MODULE_1__[/* complex */ "a"])(realComplexConjugate[0], imagComplexConjugate[0]), outputShape);
}
const rfft = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ rfft_ });
//# sourceMappingURL=rfft.js.map
/***/ }),
/* 133 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return squaredDifference; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(23);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2);
/* harmony import */ var _broadcast_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(17);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns (a - b) * (a - b) element-wise.
* Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 4, 3, 16]);
* const b = tf.tensor1d([1, 2, 9, 4]);
*
* a.squaredDifference(b).print(); // or tf.squaredDifference(a, b)
* ```
*
* ```js
* // Broadcast squared difference a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(5);
*
* a.squaredDifference(b).print(); // or tf.squaredDifference(a, b)
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function squaredDifference_(a, b) {
let $a = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(a, 'a', 'squaredDifference');
let $b = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(b, 'b', 'squaredDifference');
[$a, $b] = Object(_tensor_util__WEBPACK_IMPORTED_MODULE_2__["makeTypesMatch"])($a, $b);
Object(_broadcast_util__WEBPACK_IMPORTED_MODULE_4__[/* assertAndGetBroadcastShape */ "a"])($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
const attrs = {};
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* SquaredDifference */ "Oc"], inputs, attrs);
}
const squaredDifference = Object(_operation__WEBPACK_IMPORTED_MODULE_5__[/* op */ "b"])({ squaredDifference_ });
//# sourceMappingURL=squared_difference.js.map
/***/ }),
/* 134 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return unsortedSegmentSum; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the sum along segments of a `tf.Tensor`.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* const segmentIds = tf.tensor1d([1, 2, 0, 1], 'int32');
* const numSegments = 3;
*
* x.unsortedSegmentSum(segmentIds, numSegments).print()
* //or tf.unsortedSegmentSum(x, segmentIds, numSegments)
* ```
* @param x The `tf.Tensor` that will be summed along its segments.
* @param segmentIds A `tf.Tensor1D` whose rank is equal to the rank of `x`'s
* dimension along the `axis`. Maps each element of `x` to a segment.
* @param numSegments The number of distinct `segmentIds`.
*
* @doc {heading: 'Operations', subheading: 'Segment'}
*/
function unsortedSegmentSum_(x, segmentIds, numSegments) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'unsortedSegmentSum');
const $segmentIds = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(segmentIds, 'segmentIds', 'unsortedSegmentSum', 'int32');
Object(_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"])(Object(_util__WEBPACK_IMPORTED_MODULE_3__[/* isInt */ "v"])(numSegments), () => 'numSegments must be of dtype int');
const inputs = { x: $x, segmentIds: $segmentIds };
const attrs = { numSegments };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* UnsortedSegmentSum */ "bd"], inputs, attrs);
}
const unsortedSegmentSum = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ unsortedSegmentSum_ });
//# sourceMappingURL=unsorted_segment_sum.js.map
/***/ }),
/* 135 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return norm; });
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
/* harmony import */ var _abs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(43);
/* harmony import */ var _axis_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(39);
/* harmony import */ var _max__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(72);
/* harmony import */ var _min__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(105);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4);
/* harmony import */ var _pow__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(53);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(7);
/* harmony import */ var _scalar__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(16);
/* harmony import */ var _sqrt__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(37);
/* harmony import */ var _square__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(25);
/* harmony import */ var _sum__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(19);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the norm of scalar, vectors, and matrices.
* This function can compute several different vector norms (the 1-norm, the
* Euclidean or 2-norm, the inf-norm, and in general the p-norm for p > 0)
* and matrix norms (Frobenius, 1-norm, and inf-norm).
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
*
* x.norm().print(); // or tf.norm(x)
* ```
*
* @param x The input array.
* @param ord Optional. Order of the norm. Supported norm types are
* following:
*
* | ord | norm for matrices | norm for vectors
* |------------|---------------------------|---------------------
* |'euclidean' |Frobenius norm |2-norm
* |'fro' |Frobenius norm |
* |Infinity |max(sum(abs(x), axis=1)) |max(abs(x))
* |-Infinity |min(sum(abs(x), axis=1)) |min(abs(x))
* |1 |max(sum(abs(x), axis=0)) |sum(abs(x))
* |2 | |sum(abs(x)^2)^1/2*
*
* @param axis Optional. If axis is null (the default), the input is
* considered a vector and a single vector norm is computed over the entire
* set of values in the Tensor, i.e. norm(x, ord) is equivalent
* to norm(x.reshape([-1]), ord). If axis is a integer, the input
* is considered a batch of vectors, and axis determines the axis in x
* over which to compute vector norms. If axis is a 2-tuple of integer it is
* considered a batch of matrices and axis determines the axes in NDArray
* over which to compute a matrix norm.
* @param keepDims Optional. If true, the norm have the same dimensionality
* as the input.
*
* @doc {heading: 'Operations', subheading: 'Matrices'}
*/
function norm_(x, ord = 'euclidean', axis = null, keepDims = false) {
x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* convertToTensor */ "a"])(x, 'x', 'norm');
const norm = normImpl(x, ord, axis);
let keepDimsShape = norm.shape;
if (keepDims) {
const axes = Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* parseAxisParam */ "I"])(axis, x.shape);
keepDimsShape = _axis_util__WEBPACK_IMPORTED_MODULE_3__[/* expandShapeToKeepDim */ "e"](norm.shape, axes);
}
return Object(_reshape__WEBPACK_IMPORTED_MODULE_8__[/* reshape */ "a"])(norm, keepDimsShape);
}
function normImpl(x, p, axis = null) {
if (x.rank === 0) {
return Object(_abs__WEBPACK_IMPORTED_MODULE_2__[/* abs */ "a"])(x);
}
// consider vector when no axis is specified
if (x.rank !== 1 && axis === null) {
return normImpl(Object(_reshape__WEBPACK_IMPORTED_MODULE_8__[/* reshape */ "a"])(x, [-1]), p, axis);
}
// vector
if (x.rank === 1 || typeof axis === 'number' ||
Array.isArray(axis) && axis.length === 1) {
if (p === 1) {
return Object(_sum__WEBPACK_IMPORTED_MODULE_12__[/* sum */ "a"])(Object(_abs__WEBPACK_IMPORTED_MODULE_2__[/* abs */ "a"])(x), axis);
}
if (p === Infinity) {
return Object(_max__WEBPACK_IMPORTED_MODULE_4__[/* max */ "a"])(Object(_abs__WEBPACK_IMPORTED_MODULE_2__[/* abs */ "a"])(x), axis);
}
if (p === -Infinity) {
return Object(_min__WEBPACK_IMPORTED_MODULE_5__[/* min */ "a"])(Object(_abs__WEBPACK_IMPORTED_MODULE_2__[/* abs */ "a"])(x), axis);
}
if (p === 'euclidean' || p === 2) {
// norm(x, 2) = sum(abs(xi) ^ 2) ^ 1/2
return Object(_sqrt__WEBPACK_IMPORTED_MODULE_10__[/* sqrt */ "a"])(Object(_sum__WEBPACK_IMPORTED_MODULE_12__[/* sum */ "a"])(Object(_pow__WEBPACK_IMPORTED_MODULE_7__[/* pow */ "a"])(Object(_abs__WEBPACK_IMPORTED_MODULE_2__[/* abs */ "a"])(x), Object(_scalar__WEBPACK_IMPORTED_MODULE_9__[/* scalar */ "a"])(2, 'int32')), axis));
}
throw new Error(`Error in norm: invalid ord value: ${p}`);
}
// matrix (assumption axis[0] < axis[1])
if (Array.isArray(axis) && axis.length === 2) {
if (p === 1) {
return Object(_max__WEBPACK_IMPORTED_MODULE_4__[/* max */ "a"])(Object(_sum__WEBPACK_IMPORTED_MODULE_12__[/* sum */ "a"])(Object(_abs__WEBPACK_IMPORTED_MODULE_2__[/* abs */ "a"])(x), axis[0]), axis[1] - 1);
}
if (p === Infinity) {
return Object(_max__WEBPACK_IMPORTED_MODULE_4__[/* max */ "a"])(Object(_sum__WEBPACK_IMPORTED_MODULE_12__[/* sum */ "a"])(Object(_abs__WEBPACK_IMPORTED_MODULE_2__[/* abs */ "a"])(x), axis[1]), axis[0]);
}
if (p === -Infinity) {
return Object(_min__WEBPACK_IMPORTED_MODULE_5__[/* min */ "a"])(Object(_sum__WEBPACK_IMPORTED_MODULE_12__[/* sum */ "a"])(Object(_abs__WEBPACK_IMPORTED_MODULE_2__[/* abs */ "a"])(x), axis[1]), axis[0]);
}
if (p === 'fro' || p === 'euclidean') {
// norm(x) = sqrt(sum(pow(x, 2)))
return Object(_sqrt__WEBPACK_IMPORTED_MODULE_10__[/* sqrt */ "a"])(Object(_sum__WEBPACK_IMPORTED_MODULE_12__[/* sum */ "a"])(Object(_square__WEBPACK_IMPORTED_MODULE_11__[/* square */ "a"])(x), axis));
}
throw new Error(`Error in norm: invalid ord value: ${p}`);
}
throw new Error(`Error in norm: invalid axis: ${axis}`);
}
const norm = Object(_operation__WEBPACK_IMPORTED_MODULE_6__[/* op */ "b"])({ norm_ });
//# sourceMappingURL=norm.js.map
/***/ }),
/* 136 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return expImpl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return exp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return expConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _utils_unary_impl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(73);
/* harmony import */ var _utils_unary_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(18);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const expImpl = Object(_utils_unary_impl__WEBPACK_IMPORTED_MODULE_1__[/* createSimpleUnaryImpl */ "a"])((xi) => Math.exp(xi));
const exp = Object(_utils_unary_utils__WEBPACK_IMPORTED_MODULE_2__[/* unaryKernelFuncFromImpl */ "b"])(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Exp"], expImpl);
const expConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Exp"],
backendName: 'cpu',
kernelFunc: exp,
};
//# sourceMappingURL=Exp.js.map
/***/ }),
/* 137 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return transposeImpl; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function transposeImpl(xVals, xShape, dtype, perm, newShape) {
const xRank = xShape.length;
const xSize = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(xShape);
const xStrides = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].computeStrides(xShape);
const newStrides = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].computeStrides(newShape);
const result = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].getTypedArrayFromDType(dtype, _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(newShape));
for (let i = 0; i < xSize; ++i) {
const loc = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].indexToLoc(i, xRank, xStrides);
// Permute location.
const newLoc = new Array(loc.length);
for (let i = 0; i < newLoc.length; i++) {
newLoc[i] = loc[perm[i]];
}
const newIndex = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].locToIndex(newLoc, xRank, newStrides);
result[newIndex] = xVals[i];
}
return result;
}
//# sourceMappingURL=Transpose_impl.js.map
/***/ }),
/* 138 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return conv2DBackpropInput; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the derivative of the input of a 2D convolution.
*
* @param xShape The shape of the input: [batch, height, width, inDepth].
* If length of 3, batch of 1 is assumed.
* @param dy The derivative of the output, of rank 4 or rank 3 of shape
* `[batch, outHeight, outWidth, outDepth]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, inDepth, outDepth]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm used:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function conv2DBackpropInput_(xShape, dy, filter, strides, pad, dataFormat = 'NHWC', dimRoundingMode) {
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](xShape.length === dy.rank, () => `Length of inShape ` +
`(${xShape.length}) and rank of dy (${dy.rank}) must match`);
let xShape4D = xShape;
let dy4D = dy;
let reshapedTo4D = false;
if (dy.rank === 3) {
reshapedTo4D = true;
dy4D = Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
xShape4D = [1, xShape[0], xShape[1], xShape[2]];
}
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](xShape4D.length === 4, () => `Error in conv2dDerInput: inShape must be length 4, but got length ` +
`${xShape4D.length}.`);
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](dy4D.rank === 4, () => `Error in conv2dDerInput: dy must be rank 4, but got ` +
`rank ${dy4D.rank}`);
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](filter.rank === 4, () => `Error in conv2dDerInput: filter must be rank 4, but got ` +
`rank ${filter.rank}`);
const inDepth = dataFormat === 'NHWC' ? xShape4D[3] : xShape4D[1];
const outDepth = dataFormat === 'NHWC' ? dy4D.shape[3] : dy4D.shape[1];
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](inDepth === filter.shape[2], () => `Error in conv2dDerInput: depth of input (${inDepth}) must ` +
`match input depth for filter ${filter.shape[2]}.`);
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](outDepth === filter.shape[3], () => `Error in conv2dDerInput: depth of output (${outDepth}) must ` +
`match output depth for filter ${filter.shape[3]}.`);
if (dimRoundingMode != null) {
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](_util__WEBPACK_IMPORTED_MODULE_2__[/* isInt */ "v"](pad), () => `Error in conv2dDerInput: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { dy: dy4D, filter };
const attrs = { strides, pad, dataFormat, dimRoundingMode, inputShape: xShape4D };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Conv2DBackpropInput */ "E"], inputs, attrs);
if (reshapedTo4D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const conv2DBackpropInput = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ conv2DBackpropInput_ });
//# sourceMappingURL=conv2d_backprop_input.js.map
/***/ }),
/* 139 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TEST_EPSILON_FLOAT16", function() { return TEST_EPSILON_FLOAT16; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "expectArraysClose", function() { return expectArraysClose; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "testEpsilon", function() { return testEpsilon; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "expectPromiseToFail", function() { return expectPromiseToFail; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "expectArraysEqual", function() { return expectArraysEqual; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "expectNumbersClose", function() { return expectNumbersClose; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "expectValuesInRange", function() { return expectValuesInRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "expectArrayBuffersEqual", function() { return expectArrayBuffersEqual; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "encodeStrings", function() { return encodeStrings; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(10);
/**
* @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 TEST_EPSILON_FLOAT32 = 1e-3;
const TEST_EPSILON_FLOAT16 = 1e-1;
function expectArraysClose(actual, expected, epsilon) {
if (epsilon == null) {
epsilon = testEpsilon();
}
return expectArraysPredicate(actual, expected, (a, b) => areClose(a, b, epsilon));
}
function testEpsilon() {
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].backend.floatPrecision() === 32 ? TEST_EPSILON_FLOAT32 :
TEST_EPSILON_FLOAT16;
}
function expectArraysPredicate(actual, expected, predicate) {
let checkClassType = true;
if (Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* isTypedArray */ "A"])(actual) || Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* isTypedArray */ "A"])(expected)) {
checkClassType = false;
}
if (Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* isTypedArray */ "A"])(actual) && Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* isTypedArray */ "A"])(expected)) {
checkClassType = true;
}
if (checkClassType) {
const aType = actual.constructor.name;
const bType = expected.constructor.name;
if (aType !== bType) {
throw new Error(`Arrays are of different type. Actual: ${aType}. ` +
`Expected: ${bType}`);
}
}
if (Array.isArray(actual) && Array.isArray(expected)) {
const actualShape = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_1__[/* inferShape */ "c"])(actual);
const expectedShape = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_1__[/* inferShape */ "c"])(expected);
if (!Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* arraysEqual */ "a"])(actualShape, expectedShape)) {
throw new Error(`Arrays have different shapes. ` +
`Actual: [${actualShape}]. Expected: [${expectedShape}]`);
}
}
const actualFlat = Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* isTypedArray */ "A"])(actual) ? actual : Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* flatten */ "m"])(actual);
const expectedFlat = Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* isTypedArray */ "A"])(expected) ?
expected :
Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* flatten */ "m"])(expected);
if (actualFlat.length !== expectedFlat.length) {
throw new Error(`Arrays have different lengths actual: ${actualFlat.length} vs ` +
`expected: ${expectedFlat.length}.\n` +
`Actual: ${actualFlat}.\n` +
`Expected: ${expectedFlat}.`);
}
for (let i = 0; i < expectedFlat.length; ++i) {
const a = actualFlat[i];
const e = expectedFlat[i];
if (!predicate(a, e)) {
throw new Error(`Arrays differ: actual[${i}] = ${a}, expected[${i}] = ${e}.\n` +
`Actual: ${actualFlat}.\n` +
`Expected: ${expectedFlat}.`);
}
}
}
function expectPromiseToFail(fn, done) {
fn().then(() => done.fail(), () => done());
}
function expectArraysEqual(actual, expected) {
const exp = typeof expected === 'string' || typeof expected === 'number' ||
typeof expected === 'boolean' ?
[expected] :
expected;
if (Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* isString */ "z"])(actual) || Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* isString */ "z"])(actual[0]) ||
Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* isString */ "z"])(expected) || Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* isString */ "z"])(expected[0])) {
// tslint:disable-next-line: triple-equals
return expectArraysPredicate(actual, exp, (a, b) => a == b);
}
return expectArraysPredicate(actual, expected, (a, b) => areClose(a, b, 0));
}
function expectNumbersClose(a, e, epsilon) {
if (epsilon == null) {
epsilon = testEpsilon();
}
if (!areClose(a, e, epsilon)) {
throw new Error(`Numbers differ: actual === ${a}, expected === ${e}`);
}
}
function areClose(a, e, epsilon) {
if (!isFinite(a) && !isFinite(e)) {
return true;
}
if (isNaN(a) || isNaN(e) || Math.abs(a - e) > epsilon) {
return false;
}
return true;
}
function expectValuesInRange(actual, low, high) {
for (let i = 0; i < actual.length; i++) {
if (actual[i] < low || actual[i] > high) {
throw new Error(`Value out of range:${actual[i]} low: ${low}, high: ${high}`);
}
}
}
function expectArrayBuffersEqual(actual, expected) {
// Safari & Jasmine don't like comparing ArrayBuffers directly. Wrapping in
// a Float32Array solves this issue.
expect(new Float32Array(actual)).toEqual(new Float32Array(expected));
}
/** Encodes strings into utf-8 bytes. */
function encodeStrings(a) {
for (let i = 0; i < a.length; i++) {
const val = a[i];
if (Array.isArray(val)) {
encodeStrings(val);
}
else {
a[i] = Object(_util__WEBPACK_IMPORTED_MODULE_3__["encodeString"])(val);
}
}
return a;
}
//# sourceMappingURL=test_util.js.map
/***/ }),
/* 140 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return conv2DBackpropFilter; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the derivative of the filter of a 2D convolution.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* [batch, height, width, inChannels]. If rank 3, batch of 1 is assumed.
* @param dy The dy image, of rank 4 or rank 3, of shape
* [batch, height, width, outDepth]. If rank 3, batch of 1 is assumed.
* @param filterShape The shape of the filter, length 4,
* [filterHeight, filterWidth, inDepth, outDepth].
* @param strides The strides of the convolution: [strideHeight,
* strideWidth].
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function conv2DBackpropFilter_(x, dy, filterShape, strides, pad, dataFormat = 'NHWC', dimRoundingMode) {
let x4D = x;
if (x.rank === 3) {
x4D = Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
}
let dy4D = dy;
if (dy4D.rank === 3) {
dy4D = Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
}
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](x4D.rank === 4, () => `Error in conv2dDerFilter: input must be rank 4, but got shape ` +
`${x4D.shape}.`);
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](dy4D.rank === 4, () => `Error in conv2dDerFilter: dy must be rank 4, but got shape ` +
`${dy4D.shape}.`);
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](filterShape.length === 4, () => `Error in conv2dDerFilter: filterShape must be length 4, but got ` +
`${filterShape}.`);
const inDepth = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];
const outDepth = dataFormat === 'NHWC' ? dy4D.shape[3] : dy4D.shape[1];
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](inDepth === filterShape[2], () => `Error in conv2dDerFilter: depth of input ${inDepth}) must ` +
`match input depth in filter (${filterShape[2]}.`);
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](outDepth === filterShape[3], () => `Error in conv2dDerFilter: depth of dy (${outDepth}) must ` +
`match output depth for filter (${filterShape[3]}).`);
if (dimRoundingMode != null) {
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](_util__WEBPACK_IMPORTED_MODULE_2__[/* isInt */ "v"](pad), () => `Error in conv2dDerFilter: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x4D, dy: dy4D };
const attrs = { strides, pad, dataFormat, dimRoundingMode, filterShape };
// tslint:disable-next-line: no-unnecessary-type-assertion
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Conv2DBackpropFilter */ "D"], inputs, attrs);
}
const conv2DBackpropFilter = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ conv2DBackpropFilter_ });
//# sourceMappingURL=conv2d_backprop_filter.js.map
/***/ }),
/* 141 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var require;var require;/*!
localForage -- Offline Storage, Improved
Version 1.7.3
https://localforage.github.io/localForage
(c) 2013-2017 Mozilla, Apache License 2.0
*/
(function(f){if(true){module.exports=f()}else { var g; }})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return require(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw (f.code="MODULE_NOT_FOUND", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var scriptEl = global.document.createElement('script');
scriptEl.onreadystatechange = function () {
nextTick();
scriptEl.onreadystatechange = null;
scriptEl.parentNode.removeChild(scriptEl);
scriptEl = null;
};
global.document.documentElement.appendChild(scriptEl);
};
} else {
scheduleDrain = function () {
setTimeout(nextTick, 0);
};
}
}
var draining;
var queue = [];
//named nextTick for less confusing stack traces
function nextTick() {
draining = true;
var i, oldQueue;
var len = queue.length;
while (len) {
oldQueue = queue;
queue = [];
i = -1;
while (++i < len) {
oldQueue[i]();
}
len = queue.length;
}
draining = false;
}
module.exports = immediate;
function immediate(task) {
if (queue.push(task) === 1 && !draining) {
scheduleDrain();
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],2:[function(_dereq_,module,exports){
'use strict';
var immediate = _dereq_(1);
/* istanbul ignore next */
function INTERNAL() {}
var handlers = {};
var REJECTED = ['REJECTED'];
var FULFILLED = ['FULFILLED'];
var PENDING = ['PENDING'];
module.exports = Promise;
function Promise(resolver) {
if (typeof resolver !== 'function') {
throw new TypeError('resolver must be a function');
}
this.state = PENDING;
this.queue = [];
this.outcome = void 0;
if (resolver !== INTERNAL) {
safelyResolveThenable(this, resolver);
}
}
Promise.prototype["catch"] = function (onRejected) {
return this.then(null, onRejected);
};
Promise.prototype.then = function (onFulfilled, onRejected) {
if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
typeof onRejected !== 'function' && this.state === REJECTED) {
return this;
}
var promise = new this.constructor(INTERNAL);
if (this.state !== PENDING) {
var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
unwrap(promise, resolver, this.outcome);
} else {
this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
}
return promise;
};
function QueueItem(promise, onFulfilled, onRejected) {
this.promise = promise;
if (typeof onFulfilled === 'function') {
this.onFulfilled = onFulfilled;
this.callFulfilled = this.otherCallFulfilled;
}
if (typeof onRejected === 'function') {
this.onRejected = onRejected;
this.callRejected = this.otherCallRejected;
}
}
QueueItem.prototype.callFulfilled = function (value) {
handlers.resolve(this.promise, value);
};
QueueItem.prototype.otherCallFulfilled = function (value) {
unwrap(this.promise, this.onFulfilled, value);
};
QueueItem.prototype.callRejected = function (value) {
handlers.reject(this.promise, value);
};
QueueItem.prototype.otherCallRejected = function (value) {
unwrap(this.promise, this.onRejected, value);
};
function unwrap(promise, func, value) {
immediate(function () {
var returnValue;
try {
returnValue = func(value);
} catch (e) {
return handlers.reject(promise, e);
}
if (returnValue === promise) {
handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
} else {
handlers.resolve(promise, returnValue);
}
});
}
handlers.resolve = function (self, value) {
var result = tryCatch(getThen, value);
if (result.status === 'error') {
return handlers.reject(self, result.value);
}
var thenable = result.value;
if (thenable) {
safelyResolveThenable(self, thenable);
} else {
self.state = FULFILLED;
self.outcome = value;
var i = -1;
var len = self.queue.length;
while (++i < len) {
self.queue[i].callFulfilled(value);
}
}
return self;
};
handlers.reject = function (self, error) {
self.state = REJECTED;
self.outcome = error;
var i = -1;
var len = self.queue.length;
while (++i < len) {
self.queue[i].callRejected(error);
}
return self;
};
function getThen(obj) {
// Make sure we only access the accessor once as required by the spec
var then = obj && obj.then;
if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
return function appyThen() {
then.apply(obj, arguments);
};
}
}
function safelyResolveThenable(self, thenable) {
// Either fulfill, reject or reject with error
var called = false;
function onError(value) {
if (called) {
return;
}
called = true;
handlers.reject(self, value);
}
function onSuccess(value) {
if (called) {
return;
}
called = true;
handlers.resolve(self, value);
}
function tryToUnwrap() {
thenable(onSuccess, onError);
}
var result = tryCatch(tryToUnwrap);
if (result.status === 'error') {
onError(result.value);
}
}
function tryCatch(func, value) {
var out = {};
try {
out.value = func(value);
out.status = 'success';
} catch (e) {
out.status = 'error';
out.value = e;
}
return out;
}
Promise.resolve = resolve;
function resolve(value) {
if (value instanceof this) {
return value;
}
return handlers.resolve(new this(INTERNAL), value);
}
Promise.reject = reject;
function reject(reason) {
var promise = new this(INTERNAL);
return handlers.reject(promise, reason);
}
Promise.all = all;
function all(iterable) {
var self = this;
if (Object.prototype.toString.call(iterable) !== '[object Array]') {
return this.reject(new TypeError('must be an array'));
}
var len = iterable.length;
var called = false;
if (!len) {
return this.resolve([]);
}
var values = new Array(len);
var resolved = 0;
var i = -1;
var promise = new this(INTERNAL);
while (++i < len) {
allResolver(iterable[i], i);
}
return promise;
function allResolver(value, i) {
self.resolve(value).then(resolveFromAll, function (error) {
if (!called) {
called = true;
handlers.reject(promise, error);
}
});
function resolveFromAll(outValue) {
values[i] = outValue;
if (++resolved === len && !called) {
called = true;
handlers.resolve(promise, values);
}
}
}
}
Promise.race = race;
function race(iterable) {
var self = this;
if (Object.prototype.toString.call(iterable) !== '[object Array]') {
return this.reject(new TypeError('must be an array'));
}
var len = iterable.length;
var called = false;
if (!len) {
return this.resolve([]);
}
var i = -1;
var promise = new this(INTERNAL);
while (++i < len) {
resolver(iterable[i]);
}
return promise;
function resolver(value) {
self.resolve(value).then(function (response) {
if (!called) {
called = true;
handlers.resolve(promise, response);
}
}, function (error) {
if (!called) {
called = true;
handlers.reject(promise, error);
}
});
}
}
},{"1":1}],3:[function(_dereq_,module,exports){
(function (global){
'use strict';
if (typeof global.Promise !== 'function') {
global.Promise = _dereq_(2);
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"2":2}],4:[function(_dereq_,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function getIDB() {
/* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */
try {
if (typeof indexedDB !== 'undefined') {
return indexedDB;
}
if (typeof webkitIndexedDB !== 'undefined') {
return webkitIndexedDB;
}
if (typeof mozIndexedDB !== 'undefined') {
return mozIndexedDB;
}
if (typeof OIndexedDB !== 'undefined') {
return OIndexedDB;
}
if (typeof msIndexedDB !== 'undefined') {
return msIndexedDB;
}
} catch (e) {
return;
}
}
var idb = getIDB();
function isIndexedDBValid() {
try {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
if (!idb) {
return false;
}
// We mimic PouchDB here;
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;
// Safari <10.1 does not meet our requirements for IDB support (#5572)
// since Safari 10.1 shipped with fetch, we can use that to detect it
return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&
// some outdated implementations of IDB that appear on Samsung
// and HTC Android devices <4.4 are missing IDBKeyRange
// See: https://github.com/mozilla/localForage/issues/128
// See: https://github.com/mozilla/localForage/issues/272
typeof IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
}
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function createBlob(parts, properties) {
/* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;
var builder = new Builder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// This is CommonJS because lie is an external dependency, so Rollup
// can just ignore it.
if (typeof Promise === 'undefined') {
// In the "nopromises" build this will just throw if you don't have
// a global promise object, but it would throw anyway later.
_dereq_(3);
}
var Promise$1 = Promise;
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
function executeTwoCallbacks(promise, callback, errorCallback) {
if (typeof callback === 'function') {
promise.then(callback);
}
if (typeof errorCallback === 'function') {
promise["catch"](errorCallback);
}
}
function normalizeKey(key) {
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
return key;
}
function getCallback() {
if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
return arguments[arguments.length - 1];
}
}
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
var supportsBlobs = void 0;
var dbContexts = {};
var toString = Object.prototype.toString;
// Transaction Modes
var READ_ONLY = 'readonly';
var READ_WRITE = 'readwrite';
// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
//
// Blobs are not supported in all versions of IndexedDB, notably
// Chrome <37 and Android <5. In those versions, storing a blob will throw.
//
// Various other blob bugs exist in Chrome v37-42 (inclusive).
// Detecting them is expensive and confusing to users, and Chrome 37-42
// is at very low usage worldwide, so we do a hacky userAgent check instead.
//
// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
// Code borrowed from PouchDB. See:
// https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js
//
function _checkBlobSupportWithoutCaching(idb) {
return new Promise$1(function (resolve) {
var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
var blob = createBlob(['']);
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.onabort = function (e) {
// If the transaction aborts now its due to not being able to
// write to the database, likely due to the disk being full
e.preventDefault();
e.stopPropagation();
resolve(false);
};
txn.oncomplete = function () {
var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
var matchedEdge = navigator.userAgent.match(/Edge\//);
// MS Edge pretends to be Chrome 42:
// https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
};
})["catch"](function () {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === 'boolean') {
return Promise$1.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function (value) {
supportsBlobs = value;
return supportsBlobs;
});
}
function _deferReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Create a deferred object representing the current database operation.
var deferredOperation = {};
deferredOperation.promise = new Promise$1(function (resolve, reject) {
deferredOperation.resolve = resolve;
deferredOperation.reject = reject;
});
// Enqueue the deferred operation.
dbContext.deferredOperations.push(deferredOperation);
// Chain its promise to the database readiness.
if (!dbContext.dbReady) {
dbContext.dbReady = deferredOperation.promise;
} else {
dbContext.dbReady = dbContext.dbReady.then(function () {
return deferredOperation.promise;
});
}
}
function _advanceReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Dequeue a deferred operation.
var deferredOperation = dbContext.deferredOperations.pop();
// Resolve its promise (which is part of the database readiness
// chain of promises).
if (deferredOperation) {
deferredOperation.resolve();
return deferredOperation.promise;
}
}
function _rejectReadiness(dbInfo, err) {
var dbContext = dbContexts[dbInfo.name];
// Dequeue a deferred operation.
var deferredOperation = dbContext.deferredOperations.pop();
// Reject its promise (which is part of the database readiness
// chain of promises).
if (deferredOperation) {
deferredOperation.reject(err);
return deferredOperation.promise;
}
}
function _getConnection(dbInfo, upgradeNeeded) {
return new Promise$1(function (resolve, reject) {
dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
if (dbInfo.db) {
if (upgradeNeeded) {
_deferReadiness(dbInfo);
dbInfo.db.close();
} else {
return resolve(dbInfo.db);
}
}
var dbArgs = [dbInfo.name];
if (upgradeNeeded) {
dbArgs.push(dbInfo.version);
}
var openreq = idb.open.apply(idb, dbArgs);
if (upgradeNeeded) {
openreq.onupgradeneeded = function (e) {
var db = openreq.result;
try {
db.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// Added when support for blob shims was added
db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
} catch (ex) {
if (ex.name === 'ConstraintError') {
console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
} else {
throw ex;
}
}
};
}
openreq.onerror = function (e) {
e.preventDefault();
reject(openreq.error);
};
openreq.onsuccess = function () {
resolve(openreq.result);
_advanceReadiness(dbInfo);
};
});
}
function _getOriginalConnection(dbInfo) {
return _getConnection(dbInfo, false);
}
function _getUpgradedConnection(dbInfo) {
return _getConnection(dbInfo, true);
}
function _isUpgradeNeeded(dbInfo, defaultVersion) {
if (!dbInfo.db) {
return true;
}
var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
var isDowngrade = dbInfo.version < dbInfo.db.version;
var isUpgrade = dbInfo.version > dbInfo.db.version;
if (isDowngrade) {
// If the version is not the default one
// then warn for impossible downgrade.
if (dbInfo.version !== defaultVersion) {
console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
}
// Align the versions to prevent errors.
dbInfo.version = dbInfo.db.version;
}
if (isUpgrade || isNewStore) {
// If the store is new then increment the version (if needed).
// This will trigger an "upgradeneeded" event which is required
// for creating a store.
if (isNewStore) {
var incVersion = dbInfo.db.version + 1;
if (incVersion > dbInfo.version) {
dbInfo.version = incVersion;
}
}
return true;
}
return false;
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new Promise$1(function (resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function (e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
}
// decode an encoded blob
function _decodeBlob(encodedBlob) {
var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
return createBlob([arrayBuff], { type: encodedBlob.type });
}
// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
// Specialize the default `ready()` function by making it dependent
// on the current database operations. Thus, the driver will be actually
// ready when it's been initialized (default) *and* there are no pending
// operations on the database (initiated by some other instances).
function _fullyReady(callback) {
var self = this;
var promise = self._initReady().then(function () {
var dbContext = dbContexts[self._dbInfo.name];
if (dbContext && dbContext.dbReady) {
return dbContext.dbReady;
}
});
executeTwoCallbacks(promise, callback, callback);
return promise;
}
// Try to establish a new db connection to replace the
// current one which is broken (i.e. experiencing
// InvalidStateError while creating a transaction).
function _tryReconnect(dbInfo) {
_deferReadiness(dbInfo);
var dbContext = dbContexts[dbInfo.name];
var forages = dbContext.forages;
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
if (forage._dbInfo.db) {
forage._dbInfo.db.close();
forage._dbInfo.db = null;
}
}
dbInfo.db = null;
return _getOriginalConnection(dbInfo).then(function (db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
}).then(function (db) {
// store the latest db reference
// in case the db was upgraded
dbInfo.db = dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
forages[i]._dbInfo.db = db;
}
})["catch"](function (err) {
_rejectReadiness(dbInfo, err);
throw err;
});
}
// FF doesn't like Promises (micro-tasks) and IDDB store operations,
// so we have to do it with callbacks
function createTransaction(dbInfo, mode, callback, retries) {
if (retries === undefined) {
retries = 1;
}
try {
var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
callback(null, tx);
} catch (err) {
if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {
return Promise$1.resolve().then(function () {
if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
// increase the db version, to create the new ObjectStore
if (dbInfo.db) {
dbInfo.version = dbInfo.db.version + 1;
}
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
}).then(function () {
return _tryReconnect(dbInfo).then(function () {
createTransaction(dbInfo, mode, callback, retries - 1);
});
})["catch"](callback);
}
callback(err);
}
}
function createDbContext() {
return {
// Running localForages sharing a database.
forages: [],
// Shared database.
db: null,
// Database readiness (promise).
dbReady: null,
// Deferred operations on the database.
deferredOperations: []
};
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
// Get the current context of the database;
var dbContext = dbContexts[dbInfo.name];
// ...or create a new context.
if (!dbContext) {
dbContext = createDbContext();
// Register the new context in the global container.
dbContexts[dbInfo.name] = dbContext;
}
// Register itself as a running localForage in the current context.
dbContext.forages.push(self);
// Replace the default `ready()` function with the specialized one.
if (!self._initReady) {
self._initReady = self.ready;
self.ready = _fullyReady;
}
// Create an array of initialization states of the related localForages.
var initPromises = [];
function ignoreErrors() {
// Don't handle errors here,
// just makes sure related localForages aren't pending.
return Promise$1.resolve();
}
for (var j = 0; j < dbContext.forages.length; j++) {
var forage = dbContext.forages[j];
if (forage !== self) {
// Don't wait for itself...
initPromises.push(forage._initReady()["catch"](ignoreErrors));
}
}
// Take a snapshot of the related localForages.
var forages = dbContext.forages.slice(0);
// Initialize the connection process only when
// all the related localForages aren't pending.
return Promise$1.all(initPromises).then(function () {
dbInfo.db = dbContext.db;
// Get the connection or open a new one without upgrade.
return _getOriginalConnection(dbInfo);
}).then(function (db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
}).then(function (db) {
dbInfo.db = dbContext.db = db;
self._dbInfo = dbInfo;
// Share the final connection amongst related localForages.
for (var k = 0; k < forages.length; k++) {
var forage = forages[k];
if (forage !== self) {
// Self is already up-to-date.
forage._dbInfo.db = dbInfo.db;
forage._dbInfo.version = dbInfo.version;
}
}
});
}
function getItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function () {
var value = req.result;
if (value === undefined) {
value = null;
}
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
resolve(value);
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function () {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
var result = iterator(value, cursor.key, iterationNumber++);
// when the iterator callback retuns any
// (non-`undefined`) value, then we stop
// the iteration immediately
if (result !== void 0) {
resolve(result);
} else {
cursor["continue"]();
}
} else {
resolve();
}
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
var dbInfo;
self.ready().then(function () {
dbInfo = self._dbInfo;
if (toString.call(value) === '[object Blob]') {
return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
if (blobSupport) {
return value;
}
return _encodeBlob(value);
});
}
return value;
}).then(function (value) {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var req = store.put(value, key);
transaction.oncomplete = function () {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `.delete()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store["delete"](key);
transaction.oncomplete = function () {
resolve();
};
transaction.onerror = function () {
reject(req.error);
};
// The request will be also be aborted if we've exceeded our storage
// space.
transaction.onabort = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function () {
resolve();
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.count();
req.onsuccess = function () {
resolve(req.result);
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var advanced = false;
var req = store.openCursor();
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.openCursor();
var keys = [];
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor["continue"]();
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function dropInstance(options, callback) {
callback = getCallback.apply(this, arguments);
var currentConfig = this.config();
options = typeof options !== 'function' && options || {};
if (!options.name) {
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = Promise$1.reject('Invalid arguments');
} else {
var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;
var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
forages[i]._dbInfo.db = db;
}
return db;
});
if (!options.storeName) {
promise = dbPromise.then(function (db) {
_deferReadiness(options);
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
db.close();
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
forage._dbInfo.db = null;
}
var dropDBPromise = new Promise$1(function (resolve, reject) {
var req = idb.deleteDatabase(options.name);
req.onerror = req.onblocked = function (err) {
var db = req.result;
if (db) {
db.close();
}
reject(err);
};
req.onsuccess = function () {
var db = req.result;
if (db) {
db.close();
}
resolve(db);
};
});
return dropDBPromise.then(function (db) {
dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
var _forage = forages[i];
_advanceReadiness(_forage._dbInfo);
}
})["catch"](function (err) {
(_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
throw err;
});
});
} else {
promise = dbPromise.then(function (db) {
if (!db.objectStoreNames.contains(options.storeName)) {
return;
}
var newVersion = db.version + 1;
_deferReadiness(options);
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
db.close();
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
forage._dbInfo.db = null;
forage._dbInfo.version = newVersion;
}
var dropObjectPromise = new Promise$1(function (resolve, reject) {
var req = idb.open(options.name, newVersion);
req.onerror = function (err) {
var db = req.result;
db.close();
reject(err);
};
req.onupgradeneeded = function () {
var db = req.result;
db.deleteObjectStore(options.storeName);
};
req.onsuccess = function () {
var db = req.result;
db.close();
resolve(db);
};
});
return dropObjectPromise.then(function (db) {
dbContext.db = db;
for (var j = 0; j < forages.length; j++) {
var _forage2 = forages[j];
_forage2._dbInfo.db = db;
_advanceReadiness(_forage2._dbInfo);
}
})["catch"](function (err) {
(_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
throw err;
});
});
}
}
executeCallback(promise, callback);
return promise;
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
_support: isIndexedDBValid(),
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys,
dropInstance: dropInstance
};
function isWebSQLValid() {
return typeof openDatabase === 'function';
}
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
var toString$1 = Object.prototype.toString;
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i += 4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
/*jslint bitwise: true */
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if (bytes.length % 3 === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
var valueType = '';
if (value) {
valueType = toString$1.call(value);
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueType === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueType === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueType === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueType === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueType === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueType === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueType === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueType === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueType === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueType === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function () {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ", value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return createBlob([buffer], { type: blobType });
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
function createDbTable(t, dbInfo, callback, errorCallback) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage$1(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
}
}
var dbInfoPromise = new Promise$1(function (resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
} catch (e) {
return reject(e);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function (t) {
createDbTable(t, dbInfo, function () {
self._dbInfo = dbInfo;
resolve();
}, function (t, error) {
reject(error);
});
}, reject);
});
dbInfo.serializer = localforageSerializer;
return dbInfoPromise;
}
function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {
t.executeSql(sqlStatement, args, callback, function (t, error) {
if (error.code === error.SYNTAX_ERR) {
t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name = ?", [dbInfo.storeName], function (t, results) {
if (!results.rows.length) {
// if the table is missing (was deleted)
// re-create it table and retry
createDbTable(t, dbInfo, function () {
t.executeSql(sqlStatement, args, callback, errorCallback);
}, errorCallback);
} else {
errorCallback(t, error);
}
}, errorCallback);
} else {
errorCallback(t, error);
}
}, errorCallback);
}
function getItem$1(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {
var result = results.rows.length ? results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
resolve(result);
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate$1(iterator, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void 0) {
resolve(result);
return;
}
}
resolve();
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function _setItem(key, value, callback, retriesLeft) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {
resolve(originalValue);
}, function (t, error) {
reject(error);
});
}, function (sqlError) {
// The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// Try to re-run the transaction.
if (retriesLeft > 0) {
resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));
return;
}
reject(sqlError);
}
});
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem$1(key, value, callback) {
return _setItem.apply(this, [key, value, callback, 1]);
}
function removeItem$1(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear$1(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length$1(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
// Ahhh, SQL makes this one soooooo easy.
tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key$1(n, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {
var result = results.rows.length ? results.rows.item(0).key : null;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys$1(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// https://www.w3.org/TR/webdatabase/#databases
// > There is no way to enumerate or delete the databases available for an origin from this API.
function getAllStoreNames(db) {
return new Promise$1(function (resolve, reject) {
db.transaction(function (t) {
t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function (t, results) {
var storeNames = [];
for (var i = 0; i < results.rows.length; i++) {
storeNames.push(results.rows.item(i).name);
}
resolve({
db: db,
storeNames: storeNames
});
}, function (t, error) {
reject(error);
});
}, function (sqlError) {
reject(sqlError);
});
});
}
function dropInstance$1(options, callback) {
callback = getCallback.apply(this, arguments);
var currentConfig = this.config();
options = typeof options !== 'function' && options || {};
if (!options.name) {
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = Promise$1.reject('Invalid arguments');
} else {
promise = new Promise$1(function (resolve) {
var db;
if (options.name === currentConfig.name) {
// use the db reference of the current instance
db = self._dbInfo.db;
} else {
db = openDatabase(options.name, '', '', 0);
}
if (!options.storeName) {
// drop all database tables
resolve(getAllStoreNames(db));
} else {
resolve({
db: db,
storeNames: [options.storeName]
});
}
}).then(function (operationInfo) {
return new Promise$1(function (resolve, reject) {
operationInfo.db.transaction(function (t) {
function dropTable(storeName) {
return new Promise$1(function (resolve, reject) {
t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
}
var operations = [];
for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {
operations.push(dropTable(operationInfo.storeNames[i]));
}
Promise$1.all(operations).then(function () {
resolve();
})["catch"](function (e) {
reject(e);
});
}, function (sqlError) {
reject(sqlError);
});
});
});
}
executeCallback(promise, callback);
return promise;
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage$1,
_support: isWebSQLValid(),
iterate: iterate$1,
getItem: getItem$1,
setItem: setItem$1,
removeItem: removeItem$1,
clear: clear$1,
length: length$1,
key: key$1,
keys: keys$1,
dropInstance: dropInstance$1
};
function isLocalStorageValid() {
try {
return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&
// in IE8 typeof localStorage.setItem === 'object'
!!localStorage.setItem;
} catch (e) {
return false;
}
}
function _getKeyPrefix(options, defaultConfig) {
var keyPrefix = options.name + '/';
if (options.storeName !== defaultConfig.storeName) {
keyPrefix += options.storeName + '/';
}
return keyPrefix;
}
// Check if localStorage throws when saving an item
function checkIfLocalStorageThrows() {
var localStorageTestKey = '_localforage_support_test';
try {
localStorage.setItem(localStorageTestKey, true);
localStorage.removeItem(localStorageTestKey);
return false;
} catch (e) {
return true;
}
}
// Check if localStorage is usable and allows to save an item
// This method checks if localStorage is usable in Safari Private Browsing
// mode, or in any other case where the available quota for localStorage
// is 0 and there wasn't any saved items yet.
function _isLocalStorageUsable() {
return !checkIfLocalStorageThrows() || localStorage.length > 0;
}
// Config the localStorage backend, using options set in the config.
function _initStorage$2(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);
if (!_isLocalStorageUsable()) {
return Promise$1.reject();
}
self._dbInfo = dbInfo;
dbInfo.serializer = localforageSerializer;
return Promise$1.resolve();
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear$2(callback) {
var self = this;
var promise = self.ready().then(function () {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem$2(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate$2(iterator, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var keyPrefix = dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
// We use a dedicated iterator instead of the `i` variable below
// so other keys we fetch in localStorage aren't counted in
// the `iterationNumber` argument passed to the `iterate()`
// callback.
//
// See: github.com/mozilla/localForage/pull/435#discussion_r38061530
var iterationNumber = 1;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) !== 0) {
continue;
}
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = dbInfo.serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
if (value !== void 0) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key$2(n, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys$2(callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
var itemKey = localStorage.key(i);
if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
keys.push(itemKey.substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length$2(callback) {
var self = this;
var promise = self.keys().then(function (keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem$2(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem$2(key, value, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise$1(function (resolve, reject) {
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
try {
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function dropInstance$2(options, callback) {
callback = getCallback.apply(this, arguments);
options = typeof options !== 'function' && options || {};
if (!options.name) {
var currentConfig = this.config();
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = Promise$1.reject('Invalid arguments');
} else {
promise = new Promise$1(function (resolve) {
if (!options.storeName) {
resolve(options.name + '/');
} else {
resolve(_getKeyPrefix(options, self._defaultConfig));
}
}).then(function (keyPrefix) {
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
}
executeCallback(promise, callback);
return promise;
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage$2,
_support: isLocalStorageValid(),
iterate: iterate$2,
getItem: getItem$2,
setItem: setItem$2,
removeItem: removeItem$2,
clear: clear$2,
length: length$2,
key: key$2,
keys: keys$2,
dropInstance: dropInstance$2
};
var sameValue = function sameValue(x, y) {
return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);
};
var includes = function includes(array, searchElement) {
var len = array.length;
var i = 0;
while (i < len) {
if (sameValue(array[i], searchElement)) {
return true;
}
i++;
}
return false;
};
var isArray = Array.isArray || function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
// Drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var DefinedDrivers = {};
var DriverSupport = {};
var DefaultDrivers = {
INDEXEDDB: asyncStorage,
WEBSQL: webSQLStorage,
LOCALSTORAGE: localStorageWrapper
};
var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];
var OptionalDriverMethods = ['dropInstance'];
var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);
var DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function () {
var _args = arguments;
return localForageInstance.ready().then(function () {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var _key in arg) {
if (arg.hasOwnProperty(_key)) {
if (isArray(arg[_key])) {
arguments[0][_key] = arg[_key].slice();
} else {
arguments[0][_key] = arg[_key];
}
}
}
}
}
return arguments[0];
}
var LocalForage = function () {
function LocalForage(options) {
_classCallCheck(this, LocalForage);
for (var driverTypeKey in DefaultDrivers) {
if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
var driver = DefaultDrivers[driverTypeKey];
var driverName = driver._driver;
this[driverTypeKey] = driverName;
if (!DefinedDrivers[driverName]) {
// we don't need to wait for the promise,
// since the default drivers can be defined
// in a blocking manner
this.defineDriver(driver);
}
}
}
this._defaultConfig = extend({}, DefaultConfig);
this._config = extend({}, this._defaultConfig, options);
this._driverSet = null;
this._initDriver = null;
this._ready = false;
this._dbInfo = null;
this._wrapLibraryMethodsWithReady();
this.setDriver(this._config.driver)["catch"](function () {});
}
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function config(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " + 'has been used.');
}
for (var i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
if (i === 'version' && typeof options[i] !== 'number') {
return new Error('Database version must be a number.');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
return this.setDriver(this._config.driver);
}
return true;
} else if (typeof options === 'string') {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
var promise = new Promise$1(function (resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
var driverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0, len = driverMethods.length; i < len; i++) {
var driverMethodName = driverMethods[i];
// when the property is there,
// it should be a method even when optional
var isRequired = !includes(OptionalDriverMethods, driverMethodName);
if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {
reject(complianceError);
return;
}
}
var configureMissingMethods = function configureMissingMethods() {
var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {
return function () {
var error = new Error('Method ' + methodName + ' is not implemented by the current driver');
var promise = Promise$1.reject(error);
executeCallback(promise, arguments[arguments.length - 1]);
return promise;
};
};
for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {
var optionalDriverMethod = OptionalDriverMethods[_i];
if (!driverObject[optionalDriverMethod]) {
driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);
}
}
};
configureMissingMethods();
var setDriverSupport = function setDriverSupport(support) {
if (DefinedDrivers[driverName]) {
console.info('Redefining LocalForage driver: ' + driverName);
}
DefinedDrivers[driverName] = driverObject;
DriverSupport[driverName] = support;
// don't use a then, so that we can define
// drivers that have simple _support methods
// in a blocking manner
resolve();
};
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
driverObject._support().then(setDriverSupport, reject);
} else {
setDriverSupport(!!driverObject._support);
}
} else {
setDriverSupport(true);
}
} catch (e) {
reject(e);
}
});
executeTwoCallbacks(promise, callback, errorCallback);
return promise;
};
LocalForage.prototype.driver = function driver() {
return this._driver || null;
};
LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));
executeTwoCallbacks(getDriverPromise, callback, errorCallback);
return getDriverPromise;
};
LocalForage.prototype.getSerializer = function getSerializer(callback) {
var serializerPromise = Promise$1.resolve(localforageSerializer);
executeTwoCallbacks(serializerPromise, callback);
return serializerPromise;
};
LocalForage.prototype.ready = function ready(callback) {
var self = this;
var promise = self._driverSet.then(function () {
if (self._ready === null) {
self._ready = self._initDriver();
}
return self._ready;
});
executeTwoCallbacks(promise, callback, callback);
return promise;
};
LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
var self = this;
if (!isArray(drivers)) {
drivers = [drivers];
}
var supportedDrivers = this._getSupportedDrivers(drivers);
function setDriverToConfig() {
self._config.driver = self.driver();
}
function extendSelfWithDriver(driver) {
self._extend(driver);
setDriverToConfig();
self._ready = self._initStorage(self._config);
return self._ready;
}
function initDriver(supportedDrivers) {
return function () {
var currentDriverIndex = 0;
function driverPromiseLoop() {
while (currentDriverIndex < supportedDrivers.length) {
var driverName = supportedDrivers[currentDriverIndex];
currentDriverIndex++;
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop);
}
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise$1.reject(error);
return self._driverSet;
}
return driverPromiseLoop();
};
}
// There might be a driver initialization in progress
// so wait for it to finish in order to avoid a possible
// race condition to set _dbInfo
var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () {
return Promise$1.resolve();
}) : Promise$1.resolve();
this._driverSet = oldDriverSetDone.then(function () {
var driverName = supportedDrivers[0];
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(function (driver) {
self._driver = driver._driver;
setDriverToConfig();
self._wrapLibraryMethodsWithReady();
self._initDriver = initDriver(supportedDrivers);
});
})["catch"](function () {
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise$1.reject(error);
return self._driverSet;
});
executeTwoCallbacks(this._driverSet, callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function supports(driverName) {
return !!DriverSupport[driverName];
};
LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
var supportedDrivers = [];
for (var i = 0, len = drivers.length; i < len; i++) {
var driverName = drivers[i];
if (this.supports(driverName)) {
supportedDrivers.push(driverName);
}
}
return supportedDrivers;
};
LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0, len = LibraryMethods.length; i < len; i++) {
callWhenReady(this, LibraryMethods[i]);
}
};
LocalForage.prototype.createInstance = function createInstance(options) {
return new LocalForage(options);
};
return LocalForage;
}();
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
var localforage_js = new LocalForage();
module.exports = localforage_js;
},{"3":3}]},{},[4])(4)
});
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(103)))
/***/ }),
/* 142 */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/* 143 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _device_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(149);
/* harmony import */ var _environment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(22);
/**
* @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 ENV = Object(_environment__WEBPACK_IMPORTED_MODULE_2__[/* env */ "c"])();
/**
* This file contains environment-related flag registrations.
*/
/** Whether to enable debug mode. */
ENV.registerFlag('DEBUG', () => false, debugValue => {
if (debugValue) {
console.warn('Debugging mode is ON. The output of every math call will ' +
'be downloaded to CPU and checked for NaNs. ' +
'This significantly impacts performance.');
}
});
/** Whether we are in a browser (as versus, say, node.js) environment. */
ENV.registerFlag('IS_BROWSER', () => _device_util__WEBPACK_IMPORTED_MODULE_1__["isBrowser"]());
/** Whether we are in a browser (as versus, say, node.js) environment. */
ENV.registerFlag('IS_NODE', () => (typeof process !== 'undefined') &&
(typeof process.versions !== 'undefined') &&
(typeof process.versions.node !== 'undefined'));
/** Whether this browser is Chrome. */
ENV.registerFlag('IS_CHROME', () => typeof navigator !== 'undefined' && navigator != null &&
navigator.userAgent != null && /Chrome/.test(navigator.userAgent) &&
/Google Inc/.test(navigator.vendor));
/**
* True when the environment is "production" where we disable safety checks
* to gain performance.
*/
ENV.registerFlag('PROD', () => false);
/**
* Whether to do sanity checks when inferring a shape from user-provided
* values, used when creating a new tensor.
*/
ENV.registerFlag('TENSORLIKE_CHECK_SHAPE_CONSISTENCY', () => ENV.getBool('DEBUG'));
/** Whether deprecation warnings are enabled. */
ENV.registerFlag('DEPRECATION_WARNINGS_ENABLED', () => true);
/** True if running unit tests. */
ENV.registerFlag('IS_TEST', () => false);
/** Whether to check computation result for errors. */
ENV.registerFlag('CHECK_COMPUTATION_FOR_ERRORS', () => true);
/** Whether the backend needs to wrap input to imageBitmap. */
ENV.registerFlag('WRAP_TO_IMAGEBITMAP', () => false);
//# sourceMappingURL=flags.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(142)))
/***/ }),
/* 144 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export EPSILON_FLOAT32 */
/* unused harmony export EPSILON_FLOAT16 */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DataStorage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return KernelBackend; });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const EPSILON_FLOAT32 = 1e-7;
const EPSILON_FLOAT16 = 1e-4;
/** Convenient class for storing tensor-related data. */
class DataStorage {
constructor(backend, dataMover) {
this.backend = backend;
this.dataMover = dataMover;
this.data = new WeakMap();
this.dataIdsCount = 0;
}
get(dataId) {
if (!this.data.has(dataId)) {
this.dataMover.moveData(this.backend, dataId);
}
return this.data.get(dataId);
}
set(dataId, value) {
this.dataIdsCount++;
this.data.set(dataId, value);
}
has(dataId) {
return this.data.has(dataId);
}
delete(dataId) {
this.dataIdsCount--;
return this.data.delete(dataId);
}
numDataIds() {
return this.dataIdsCount;
}
}
/**
* The interface that defines the kernels that should be implemented when
* adding a new backend. New backends don't need to implement every one of the
* methods, this can be done gradually (throw an error for unimplemented
* methods).
*/
class KernelBackend {
refCount(dataId) {
return notYetImplemented('refCount');
}
incRef(dataId) {
return notYetImplemented('incRef');
}
timerAvailable() {
return true;
}
time(f) {
return notYetImplemented('time');
}
read(dataId) {
return notYetImplemented('read');
}
readSync(dataId) {
return notYetImplemented('readSync');
}
numDataIds() {
return notYetImplemented('numDataIds');
}
disposeData(dataId, force) {
return notYetImplemented('disposeData');
}
write(values, shape, dtype) {
return notYetImplemented('write');
}
move(dataId, values, shape, dtype, refCount) {
return notYetImplemented('move');
}
memory() {
return notYetImplemented('memory');
}
/** Returns the highest precision for floats in bits (e.g. 16 or 32) */
floatPrecision() {
return notYetImplemented('floatPrecision');
}
/** Returns the smallest representable number. */
epsilon() {
return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;
}
dispose() {
return notYetImplemented('dispose');
}
}
function notYetImplemented(kernelName) {
throw new Error(`'${kernelName}' not yet implemented or not found in the registry. ` +
`This kernel may not be supported by the tfjs backend you have chosen`);
}
//# sourceMappingURL=backend.js.map
/***/ }),
/* 145 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return tanh; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes hyperbolic tangent of the input `tf.Tensor` element-wise: `tanh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, 70]);
*
* x.tanh().print(); // or tf.tanh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function tanh_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'tanh');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Tanh */ "Uc"], inputs);
}
const tanh = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ tanh_ });
//# sourceMappingURL=tanh.js.map
/***/ }),
/* 146 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return range; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(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.
* =============================================================================
*/
/**
* Creates a new `tf.Tensor1D` filled with the numbers in the range provided.
*
* The tensor is a is half-open interval meaning it includes start, but
* excludes stop. Decrementing ranges and negative step values are also
* supported.sv
*
*
* ```js
* tf.range(0, 9, 2).print();
* ```
*
* @param start An integer start value
* @param stop An integer stop value
* @param step An integer increment (will default to 1 or -1)
* @param dtype The data type of the output tensor. Defaults to 'float32'.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function range(start, stop, step = 1, dtype = 'float32') {
if (step === 0) {
throw new Error('Cannot have a step of zero');
}
const attrs = { start, stop, step, dtype };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Range */ "jc"], {} /* inputs */, attrs);
}
//# sourceMappingURL=range.js.map
/***/ }),
/* 147 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return SELU_SCALEALPHA; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return SELU_SCALE; });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const SELU_SCALEALPHA = 1.7580993408473768599402175208123;
const SELU_SCALE = 1.0507009873554804934193349852946;
//# sourceMappingURL=selu_util.js.map
/***/ }),
/* 148 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DTYPE_VALUE_SIZE_MAP; });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/* Type definitions for exporting and importing of models. */
/**
* A map from Tensor dtype to number of bytes per element of the Tensor.
*/
const DTYPE_VALUE_SIZE_MAP = {
'float32': 4,
'float16': 2,
'int32': 4,
'uint16': 2,
'uint8': 1,
'bool': 1,
'complex64': 8
};
//# sourceMappingURL=types.js.map
/***/ }),
/* 149 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isMobile", function() { return isMobile; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isBrowser", function() { return isBrowser; });
/**
* @license
* Copyright 2017 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line:no-any
function _isNavigatorDefined() {
return typeof navigator !== 'undefined' && navigator != null;
}
function isMobile(nav) {
if (nav || _isNavigatorDefined()) {
if (!nav) {
nav = navigator;
}
if (nav.product === 'ReactNative') {
return true;
}
// tslint:disable-next-line:no-any
const a = nav.userAgent || nav.vendor || window.opera;
// tslint:disable-next-line:max-line-length
return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i
.test(a) ||
// tslint:disable-next-line:max-line-length
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i
.test(a.substr(0, 4));
}
return false;
}
function isBrowser() {
return (typeof window !== 'undefined' && window.document != null) ||
//@ts-ignore
(typeof WorkerGlobalScope !== 'undefined');
}
//# sourceMappingURL=device_util.js.map
/***/ }),
/* 150 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return print; });
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Prints information about the `tf.Tensor` including its data.
*
* ```js
* const verbose = true;
* tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);
* ```
* @param x The tensor to be printed.
* @param verbose Whether to print verbose information about the ` Tensor`,
* including dtype and size.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function print(x, verbose = false) {
console.log(x.toString(verbose));
}
//# sourceMappingURL=print.js.map
/***/ }),
/* 151 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return all; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the logical and of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and an
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 1, 1], 'bool');
*
* x.all().print(); // or tf.all(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');
*
* const axis = 1;
* x.all(axis).print(); // or tf.all(x, axis)
* ```
*
* @param x The input tensor. Must be of dtype bool.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function all_(x, axis = null, keepDims = false) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'all', 'bool');
const inputs = { x: $x };
const attrs = { axis, keepDims };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* All */ "f"], inputs, attrs);
}
const all = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ all_ });
//# sourceMappingURL=all.js.map
/***/ }),
/* 152 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return any; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the logical or of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and an
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 1, 1], 'bool');
*
* x.any().print(); // or tf.any(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');
*
* const axis = 1;
* x.any(axis).print(); // or tf.any(x, axis)
* ```
*
* @param x The input tensor. Must be of dtype bool.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function any_(x, axis = null, keepDims = false) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'any', 'bool');
const inputs = { x: $x };
const attrs = { axis, keepDims };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Any */ "g"], inputs, attrs);
}
// tslint:disable-next-line:variable-name
const any = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ any_ });
//# sourceMappingURL=any.js.map
/***/ }),
/* 153 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return argMax; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the indices of the maximum values along an `axis`.
*
* The result has the same shape as `input` with the dimension along `axis`
* removed.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.argMax().print(); // or tf.argMax(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 4, 3], [2, 2]);
*
* const axis = 1;
* x.argMax(axis).print(); // or tf.argMax(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension to reduce. Defaults to 0 (outer-most dimension).
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function argMax_(x, axis = 0) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'argMax');
const inputs = { x: $x };
const attrs = { axis };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* ArgMax */ "h"], inputs, attrs);
}
const argMax = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ argMax_ });
//# sourceMappingURL=arg_max.js.map
/***/ }),
/* 154 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return argMin; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the indices of the minimum values along an `axis`.
*
* The result has the same shape as `input` with the dimension along `axis`
* removed.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.argMin().print(); // or tf.argMin(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 4, 3], [2, 2]);
*
* const axis = 1;
* x.argMin(axis).print(); // or tf.argMin(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension to reduce. Defaults to 0 (outer-most dimension).
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function argMin_(x, axis = 0) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'argMin');
const inputs = { x: $x };
const attrs = { axis };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* ArgMin */ "i"], inputs, attrs);
}
const argMin = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ argMin_ });
//# sourceMappingURL=arg_min.js.map
/***/ }),
/* 155 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return atan2; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(23);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes arctangent of `tf.Tensor`s a / b element-wise: `atan2(a, b)`.
* Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1.0, 1.0, -1.0, .7]);
* const b = tf.tensor1d([2.0, 13.0, 3.5, .21]);
*
* tf.atan2(a, b).print()
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function atan2_(a, b) {
let $a = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(a, 'a', 'atan2');
let $b = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(b, 'b', 'atan2');
[$a, $b] = Object(_tensor_util__WEBPACK_IMPORTED_MODULE_2__["makeTypesMatch"])($a, $b);
const inputs = { a: $a, b: $b };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Atan2 */ "m"], inputs);
}
const atan2 = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ atan2_ });
//# sourceMappingURL=atan2.js.map
/***/ }),
/* 156 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return conv1d; });
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
/* harmony import */ var _conv2d__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(65);
/* harmony import */ var _conv_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(31);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7);
/**
* Computes a 1D convolution over the input x.
*
* @param x The input tensor, of rank 3 or rank 2, of shape
* `[batch, width, inChannels]`. If rank 2, batch of 1 is assumed.
* @param filter The filter, rank 3, of shape
* `[filterWidth, inDepth, outDepth]`.
* @param stride The number of entries by which the filter is moved right at
* each step.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dataFormat An optional string from "NWC", "NCW". Defaults to "NWC",
* the data is stored in the order of [batch, in_width, in_channels]. Only
* "NWC" is currently supported.
* @param dilation The dilation rate in which we sample input values in
* atrous convolution. Defaults to `1`. If it is greater than 1, then
* stride must be `1`.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function conv1d_(x, filter, stride, pad, dataFormat = 'NWC', dilation = 1, dimRoundingMode) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* convertToTensor */ "a"])(x, 'x', 'conv1d');
const $filter = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* convertToTensor */ "a"])(filter, 'filter', 'conv1d');
let x3D = $x;
let reshapedTo3D = false;
if ($x.rank === 2) {
reshapedTo3D = true;
x3D = Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])($x, [1, $x.shape[0], $x.shape[1]]);
}
_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"](x3D.rank === 3, () => `Error in conv1d: input must be rank 3, but got rank ${x3D.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"]($filter.rank === 3, () => `Error in conv1d: filter must be rank 3, but got rank ` +
`${$filter.rank}.`);
if (dimRoundingMode != null) {
_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"](_util__WEBPACK_IMPORTED_MODULE_1__[/* isInt */ "v"](pad), () => `Error in conv1d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"](x3D.shape[2] === $filter.shape[1], () => `Error in conv1d: depth of input (${x3D.shape[2]}) must match ` +
`input depth for filter ${$filter.shape[1]}.`);
_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"](_conv_util__WEBPACK_IMPORTED_MODULE_3__[/* eitherStridesOrDilationsAreOne */ "h"](stride, dilation), () => 'Error in conv1D: Either stride or dilation must be 1. ' +
`Got stride ${stride} and dilation '${dilation}'`);
_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"](dataFormat === 'NWC', () => `Error in conv1d: got dataFormat of ${dataFormat} but only NWC is currently supported.`);
const filter4D = Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])($filter, [1, $filter.shape[0], $filter.shape[1], $filter.shape[2]]);
const input4D = Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])(x3D, [x3D.shape[0], 1, x3D.shape[1], x3D.shape[2]]);
const strides = [1, stride];
const dilations = [1, dilation];
const conv2dDataFormat = 'NHWC';
const res = Object(_conv2d__WEBPACK_IMPORTED_MODULE_2__[/* conv2d */ "a"])(input4D, filter4D, strides, pad, conv2dDataFormat, dilations, dimRoundingMode);
if (reshapedTo3D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])(res, [res.shape[2], res.shape[3]]);
}
return Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])(res, [res.shape[0], res.shape[2], res.shape[3]]);
}
const conv1d = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ conv1d_ });
//# sourceMappingURL=conv1d.js.map
/***/ }),
/* 157 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return conv2dTranspose; });
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _conv2d_backprop_input__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(138);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4);
/**
* Computes the transposed 2D convolution of an image, also known as a
* deconvolution.
*
* @param x The input image, of rank 4 or rank 3, of shape
* `[batch, height, width, inDepth]`. If rank 3, batch of 1 is assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, outDepth, inDepth]`.
* `inDepth` must match `inDepth` in `x`.
* @param outputShape Output shape, of rank 4 or rank 3:
* `[batch, height, width, outDepth]`. If rank 3, batch of 1 is assumed.
* @param strides The strides of the original convolution:
* `[strideHeight, strideWidth]`.
* @param pad The type of padding algorithm used in the non-transpose version
* of the op.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function conv2dTranspose_(x, filter, outputShape, strides, pad, dimRoundingMode) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* convertToTensor */ "a"])(x, 'x', 'conv2dTranspose');
const $filter = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* convertToTensor */ "a"])(filter, 'filter', 'conv2dTranspose');
return Object(_conv2d_backprop_input__WEBPACK_IMPORTED_MODULE_1__[/* conv2DBackpropInput */ "a"])(outputShape, $x, $filter, strides, pad, 'NHWC', dimRoundingMode);
}
const conv2dTranspose = Object(_operation__WEBPACK_IMPORTED_MODULE_2__[/* op */ "b"])({ conv2dTranspose_ });
//# sourceMappingURL=conv2d_transpose.js.map
/***/ }),
/* 158 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return cosh; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes hyperbolic cos of the input `tf.Tensor` element-wise: `cosh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.cosh().print(); // or tf.cosh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function cosh_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'cosh');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Cosh */ "J"], inputs);
}
const cosh = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ cosh_ });
//# sourceMappingURL=cosh.js.map
/***/ }),
/* 159 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return depthToSpace; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Rearranges data from depth into blocks of spatial data. More specifically,
* this op outputs a copy of the input tensor where values from the `depth`
* dimension are moved in spatial blocks to the `height` and `width` dimensions.
* The attr `blockSize` indicates the input block size and how the data is
* moved.
*
* - Chunks of data of size `blockSize * blockSize` from depth are rearranged
* into non-overlapping blocks of size `blockSize x blockSize`
*
* - The width the output tensor is `inputWidth * blockSize`, whereas the
* height is `inputHeight * blockSize`
*
* - The Y, X coordinates within each block of the output image are determined
* by the high order component of the input channel index
*
* - The depth of the input tensor must be divisible by `blockSize *
* blockSize`
*
* The `dataFormat` attr specifies the layout of the input and output tensors
* with the following options: "NHWC": [ `batch, height, width, channels` ]
* "NCHW": [ `batch, channels, height, width` ]
*
* ```js
* const x = tf.tensor4d([1, 2, 3, 4], [1, 1, 1, 4]);
* const blockSize = 2;
* const dataFormat = "NHWC";
*
* tf.depthToSpace(x, blockSize, dataFormat).print();
* ```
*
* @param x The input tensor of rank 4
* @param blockSIze An `int` that is `>= 2`. The size of the spatial block
* @param dataFormat An optional string from: "NHWC", "NCHW". Defaults to "NHWC"
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function depthToSpace_(x, blockSize, dataFormat = 'NHWC') {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'depthToSpace');
const inputHeight = (dataFormat === 'NHWC') ? $x.shape[1] : $x.shape[2];
const inputWidth = (dataFormat === 'NHWC') ? $x.shape[2] : $x.shape[3];
const inputDepth = (dataFormat === 'NHWC') ? $x.shape[3] : $x.shape[1];
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](inputHeight * blockSize >= 0, () => `Negative dimension size caused by overflow when multiplying
${inputHeight} and ${blockSize} for depthToSpace with input shape
${$x.shape}`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](inputWidth * blockSize >= 0, () => `Negative dimension size caused by overflow when multiplying
${inputWidth} and ${blockSize} for depthToSpace with input shape
${$x.shape}`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]((inputDepth % (blockSize * blockSize) === 0), () => `Dimension size must be evenly divisible by ${blockSize * blockSize} but is ${inputDepth} for depthToSpace with input shape ${$x.shape}`);
const inputs = { x: $x };
const attrs = { blockSize, dataFormat };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* DepthToSpace */ "N"], inputs, attrs);
}
const depthToSpace = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ depthToSpace_ });
//# sourceMappingURL=depth_to_space.js.map
/***/ }),
/* 160 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return dilation2d; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the grayscale dilation over the input `x`.
*
* @param x The input tensor, rank 3 or rank 4 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filter The filter tensor, rank 3, of shape
* `[filterHeight, filterWidth, depth]`.
* @param strides The strides of the sliding window for each dimension of the
* input tensor: `[strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dataFormat Specify the data format of the input and output data.
* Defaults to 'NHWC'. Only 'NHWC' is currently supported. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* for atrous morphological dilation. Defaults to `[1, 1]`. If `dilations`
* is a single number, then `dilationHeight == dilationWidth`. If it is
* greater than 1, then all values of `strides` must be 1.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function dilation2d_(x, filter, strides, pad, dilations = [1, 1], dataFormat = 'NHWC') {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'dilation2d');
const $filter = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(filter, 'filter', 'dilation2d');
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($x.rank === 3 || $x.rank === 4, () => `Error in dilation2d: input must be rank 3 or 4, but got rank ` +
`${$x.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($filter.rank === 3, () => `Error in dilation2d: filter must be rank 3, but got rank ` +
`${$filter.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](dataFormat === 'NHWC', () => `Error in dilation2d: Only NHWC is currently supported, ` +
`but got dataFormat of ${dataFormat}`);
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
x4D = Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
reshapedTo4D = true;
}
const inputs = { x: x4D, filter: $filter };
const attrs = { strides, pad, dilations };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Dilation2D */ "S"], inputs, attrs);
if (reshapedTo4D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const dilation2d = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ dilation2d_ });
//# sourceMappingURL=dilation2d.js.map
/***/ }),
/* 161 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return divNoNan; });
/* harmony import */ var _tensor_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(23);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _div__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(15);
/* harmony import */ var _equal__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(93);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/* harmony import */ var _where__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(36);
/* harmony import */ var _zeros_like__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(20);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting. Return 0
* if denominator is 0.
*
*
* ```js
* const a = tf.tensor1d([1, 4, 9, 16]);
* const b = tf.tensor1d([1, 2, 3, 4]);
* const c = tf.tensor1d([0, 0, 0, 0]);
*
* a.divNoNan(b).print(); // or tf.divNoNan(a, b)
* a.divNoNan(c).print(); // or tf.divNoNan(a, c)
* ```
*
* ```js
* // Broadcast div a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(2);
* const c = tf.scalar(0);
*
* a.divNoNan(b).print(); // or tf.divNoNan(a, b)
* a.divNoNan(c).print(); // or tf.divNoNan(a, c)
* ```
*
* @param a The first tensor as the numerator.
* @param b The second tensor as the denominator. Must have the same dtype as
* `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function divNoNan_(a, b) {
// TODO: Make this into its own kernel.
let $a = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_1__[/* convertToTensor */ "a"])(a, 'a', 'div');
let $b = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_1__[/* convertToTensor */ "a"])(b, 'b', 'div');
[$a, $b] = Object(_tensor_util__WEBPACK_IMPORTED_MODULE_0__["makeTypesMatch"])($a, $b);
const divResult = Object(_div__WEBPACK_IMPORTED_MODULE_2__[/* div */ "a"])($a, $b);
const zeros = Object(_zeros_like__WEBPACK_IMPORTED_MODULE_6__[/* zerosLike */ "a"])(divResult);
const bEqualsZero = Object(_equal__WEBPACK_IMPORTED_MODULE_3__[/* equal */ "a"])($b, zeros);
return Object(_where__WEBPACK_IMPORTED_MODULE_5__[/* where */ "a"])(bEqualsZero, zeros, divResult);
}
const divNoNan = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ divNoNan_ });
//# sourceMappingURL=div_no_nan.js.map
/***/ }),
/* 162 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return dot; });
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
/* harmony import */ var _mat_mul__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(24);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the dot product of two matrices and/or vectors, `t1` and `t2`.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor2d([[1, 2], [3, 4]]);
* const c = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);
*
* a.dot(b).print(); // or tf.dot(a, b)
* b.dot(a).print();
* b.dot(c).print();
* ```
* @param t1 The first tensor in the dot operation.
* @param t2 The second tensor in the dot operation.
*
* @doc {heading: 'Operations', subheading: 'Matrices'}
*/
function dot_(t1, t2) {
const $t1 = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* convertToTensor */ "a"])(t1, 't1', 'dot');
const $t2 = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* convertToTensor */ "a"])(t2, 't2', 'dot');
_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"](($t1.rank === 1 || $t1.rank === 2) && ($t2.rank === 1 || $t2.rank === 2), () => `Error in dot: inputs must all be rank 1 or 2, but got ranks ` +
`${$t1.rank} and ${$t2.rank}.`);
const t1Inner = ($t1.rank === 1 ? $t1.size : $t1.shape[1]);
const t2Inner = ($t2.rank === 1 ? $t2.size : $t2.shape[0]);
_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"](t1Inner === t2Inner, () => `Error in dot: inner dimensions of inputs must match, but got ` +
`${t1Inner} and ${t2Inner}.`);
if ($t1.rank === 1 && $t2.rank === 1) {
const t12D = Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])($t1, [1, -1]);
const t22D = Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])($t2, [-1, 1]);
const t1t2 = Object(_mat_mul__WEBPACK_IMPORTED_MODULE_2__[/* matMul */ "a"])(t12D, t22D);
return Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])(t1t2, []);
}
else if ($t1.rank === 1 && $t2.rank === 2) {
const t12D = Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])($t1, [1, -1]);
const t22D = Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])($t2, [$t2.shape[0], $t2.shape[1]]);
const t1t2 = Object(_mat_mul__WEBPACK_IMPORTED_MODULE_2__[/* matMul */ "a"])(t12D, t22D);
return Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])(t1t2, [t1t2.size]);
}
else if ($t1.rank === 2 && $t2.rank === 1) {
const t22D = Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])($t2, [-1, 1]);
const t1t2 = Object(_mat_mul__WEBPACK_IMPORTED_MODULE_2__[/* matMul */ "a"])($t1, t22D);
return Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])(t1t2, [t1t2.size]);
}
else {
const t22D = Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])($t2, [$t2.shape[0], $t2.shape[1]]);
const t1t2 = Object(_mat_mul__WEBPACK_IMPORTED_MODULE_2__[/* matMul */ "a"])($t1, t22D);
return t1t2;
}
}
const dot = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ dot_ });
//# sourceMappingURL=dot.js.map
/***/ }),
/* 163 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return localResponseNormalization; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Normalizes the activation of a local neighborhood across or within
* channels.
*
* @param x The input tensor. The 4-D input tensor is treated as a 3-D array
* of 1D vectors (along the last dimension), and each vector is
* normalized independently.
* @param depthRadius The number of adjacent channels in the 1D normalization
* window.
* @param bias A constant bias term for the basis.
* @param alpha A scale factor, usually positive.
* @param beta An exponent.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function localResponseNormalization_(x, depthRadius = 5, bias = 1, alpha = 1, beta = 0.5) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'localResponseNormalization');
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($x.rank === 4 || $x.rank === 3, () => `Error in localResponseNormalization: x must be rank 3 or 4 but got
rank ${$x.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](_util__WEBPACK_IMPORTED_MODULE_3__[/* isInt */ "v"](depthRadius), () => `Error in localResponseNormalization: depthRadius must be an ` +
`integer but got depthRadius ${depthRadius}.`);
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
const inputs = { x: x4D };
const attrs = { depthRadius, bias, alpha, beta };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* LRN */ "wb"], inputs, attrs);
if (reshapedTo4D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
else {
return res;
}
}
const localResponseNormalization = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ localResponseNormalization_ });
//# sourceMappingURL=local_response_normalization.js.map
/***/ }),
/* 164 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return log1p; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes natural logarithm of the input `tf.Tensor` plus one
* element-wise: `ln(1 + x)`
*
* ```js
* const x = tf.tensor1d([1, 2, Math.E - 1]);
*
* x.log1p().print(); // or tf.log1p(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function log1p_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'log1p');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Log1p */ "Db"], inputs);
}
const log1p = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ log1p_ });
//# sourceMappingURL=log1p.js.map
/***/ }),
/* 165 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return softplus; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes softplus of the input `tf.Tensor` element-wise: `log(exp(x) + 1)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.softplus().print(); // or tf.softplus(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function softplus_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'softplus');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Softplus */ "Hc"], inputs);
}
const softplus = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ softplus_ });
//# sourceMappingURL=softplus.js.map
/***/ }),
/* 166 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return logicalXor; });
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _broadcast_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17);
/* harmony import */ var _logical_and__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(59);
/* harmony import */ var _logical_not__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(95);
/* harmony import */ var _logical_or__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(125);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of `a XOR b` element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([false, false, true, true], 'bool');
* const b = tf.tensor1d([false, true, false, true], 'bool');
*
* a.logicalXor(b).print();
* ```
*
* @param a The first input tensor. Must be of dtype bool.
* @param b The second input tensor. Must be of dtype bool.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function logicalXor_(a, b) {
const $a = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* convertToTensor */ "a"])(a, 'a', 'logicalXor', 'bool');
const $b = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* convertToTensor */ "a"])(b, 'b', 'logicalXor', 'bool');
Object(_broadcast_util__WEBPACK_IMPORTED_MODULE_1__[/* assertAndGetBroadcastShape */ "a"])($a.shape, $b.shape);
// x ^ y = (x | y) & ~(x & y)
return Object(_logical_and__WEBPACK_IMPORTED_MODULE_2__[/* logicalAnd */ "a"])(Object(_logical_or__WEBPACK_IMPORTED_MODULE_4__[/* logicalOr */ "a"])(a, b), Object(_logical_not__WEBPACK_IMPORTED_MODULE_3__[/* logicalNot */ "a"])(Object(_logical_and__WEBPACK_IMPORTED_MODULE_2__[/* logicalAnd */ "a"])(a, b)));
}
const logicalXor = Object(_operation__WEBPACK_IMPORTED_MODULE_5__[/* op */ "b"])({ logicalXor_ });
//# sourceMappingURL=logical_xor.js.map
/***/ }),
/* 167 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return mirrorPad; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Pads a `tf.Tensor` using mirror padding.
*
* This operation implements the `REFLECT` and `SYMMETRIC` modes of pad.
*
* ```js
* const x = tf.range(0, 9).reshape([1, 1, 3, 3]);
* x.mirrorPad([[0, 0], [0, 0], [2, 2], [2, 2]], 'reflect').print();
* ```
* @param x The tensor to pad.
* @param paddings An array of length `R` (the rank of the tensor), where
* each element is a length-2 tuple of ints `[padBefore, padAfter]`,
* specifying how much to pad along each dimension of the tensor.
* In "reflect" mode, the padded regions do not include the borders,
* while in "symmetric" mode the padded regions do include the borders.
* For example, if the input is `[1, 2, 3]` and paddings is `[0, 2]`,
* then the output is `[1, 2, 3, 2, 1]` in "reflect" mode, and
* `[1, 2, 3, 3, 2]` in "symmetric" mode.
* If `mode` is "reflect" then both `paddings[D, 0]` and `paddings[D, 1]`
* must be no greater than `x.shape[D] - 1`. If mode is "symmetric"
* then both `paddings[D, 0]` and `paddings[D, 1]` must be no greater than
* `x.shape[D]`
* @param mode String to specify padding mode. Can be `'reflect' | 'symmetric'`
*/
/** @doc {heading: 'Tensors', subheading: 'Transformations'} */
function mirrorPad_(x, paddings, mode) {
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](mode === 'reflect' || mode === 'symmetric', () => `Invalid mode. Mode must be either reflect or symmetric. ` +
`Got ${mode}.`);
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'mirrorPad');
if ($x.rank === 0) {
throw new Error('mirrorPad(scalar) is not defined. ' +
'Pass non-scalar to mirrorPad');
}
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](paddings.length === $x.rank, () => `Padding doesn't match input. Must be ${$x.rank}. ` +
`Got ${paddings.length}.`);
const shapeOffset = mode === 'reflect' ? 1 : 0;
for (let i = 0; i < $x.rank; i++) {
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](paddings[i].length === 2, () => `Invalid number of paddings. Must be length of 2 each.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](paddings[i][0] >= 0 && paddings[i][0] <= $x.shape[i] - shapeOffset &&
paddings[i][1] >= 0 && paddings[i][1] <= $x.shape[i] - shapeOffset, () => `Padding in dimension ${i} cannot be greater than or equal ` +
`to ${$x.shape[i] - shapeOffset} or less than 0 for input of ` +
`shape ${$x.shape}`);
}
const attrs = { paddings, mode };
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* MirrorPad */ "Sb"], inputs, attrs);
}
const mirrorPad = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ mirrorPad_ });
//# sourceMappingURL=mirror_pad.js.map
/***/ }),
/* 168 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return mod; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(23);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the mod of a and b element-wise.
* `floor(x / y) * y + mod(x, y) = x`
* Supports broadcasting.
*
* We also expose `tf.modStrict` which has the same signature as this op and
* asserts that `a` and `b` are the same shape (does not broadcast).
*
* ```js
* const a = tf.tensor1d([1, 4, 3, 16]);
* const b = tf.tensor1d([1, 2, 9, 4]);
*
* a.mod(b).print(); // or tf.mod(a, b)
* ```
*
* ```js
* // Broadcast a mod b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(5);
*
* a.mod(b).print(); // or tf.mod(a, b)
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function mod_(a, b) {
let $a = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(a, 'a', 'mod');
let $b = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_3__[/* convertToTensor */ "a"])(b, 'b', 'mod');
[$a, $b] = Object(_tensor_util__WEBPACK_IMPORTED_MODULE_2__["makeTypesMatch"])($a, $b);
const inputs = { a: $a, b: $b };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Mod */ "Tb"], inputs);
}
const mod = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ mod_ });
//# sourceMappingURL=mod.js.map
/***/ }),
/* 169 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return pool; });
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
/* harmony import */ var _avg_pool__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(116);
/* harmony import */ var _batch_to_space_nd__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(91);
/* harmony import */ var _conv_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(31);
/* harmony import */ var _max_pool__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(126);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(7);
/* harmony import */ var _space_to_batch_nd__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(96);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Performs an N-D pooling operation
*
* @param input The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param windowShape The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param poolingType The type of pooling, either 'max' or 'avg'.
* @param pad The type of padding algorithm:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in dilated pooling. Defaults to `[1, 1]`. If `dilationRate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function pool_(input, windowShape, poolingType, pad, dilations, strides) {
if (dilations == null) {
dilations = [1, 1];
}
if (strides == null) {
strides = 1;
}
if (pad === 0) {
pad = 'valid';
}
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* convertToTensor */ "a"])(input, 'x', 'maxPool');
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = Object(_reshape__WEBPACK_IMPORTED_MODULE_7__[/* reshape */ "a"])($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"](_conv_util__WEBPACK_IMPORTED_MODULE_4__[/* eitherStridesOrDilationsAreOne */ "h"](strides, dilations), () => 'Error in pool: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
const convInfo = _conv_util__WEBPACK_IMPORTED_MODULE_4__[/* computePool2DInfo */ "e"](x4D.shape, windowShape, strides, dilations, pad);
const dilation = [convInfo.dilationHeight, convInfo.dilationWidth];
// The following implementation does batchToSpace(pool(spaceToBatch(x)))
// whenever dilation > 1 since the TF kernels do not support dilation > 1.
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L1037
let basePadding;
if (pad === 'same') {
basePadding = withSpaceToBatchBasePaddings([convInfo.filterHeight, convInfo.filterWidth], dilation);
}
else {
basePadding = [[0, 0], [0, 0]];
}
const isDilationOne = dilation[0] === 1 && dilation[1] === 1;
const [adjustedPadding, adjustedCrops] = requiredSpaceToBatchPaddings([convInfo.inHeight, convInfo.inWidth], dilation, basePadding);
const convertedPad = isDilationOne ? pad : 'valid';
const convertedX = isDilationOne ? x4D : Object(_space_to_batch_nd__WEBPACK_IMPORTED_MODULE_8__[/* spaceToBatchND */ "a"])(x4D, dilation, adjustedPadding);
const forwardOp = poolingType === 'avg' ?
() => Object(_avg_pool__WEBPACK_IMPORTED_MODULE_2__[/* avgPool */ "a"])(convertedX, windowShape, strides, convertedPad) :
() => Object(_max_pool__WEBPACK_IMPORTED_MODULE_5__[/* maxPool */ "a"])(convertedX, windowShape, strides, convertedPad);
const y = forwardOp();
const res = isDilationOne ? y : Object(_batch_to_space_nd__WEBPACK_IMPORTED_MODULE_3__[/* batchToSpaceND */ "a"])(y, dilation, adjustedCrops);
if (reshapedTo4D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_7__[/* reshape */ "a"])(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
// Helper function to compute crops and paddings for pool with dilation > 1.
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/array_ops.py#L2184
function requiredSpaceToBatchPaddings(inputShape, blockShape, basePadding) {
const padStart = basePadding.map(b => b[0]);
const origPadEnd = basePadding.map(b => b[1]);
const fullInputShape = inputShape.concat(padStart, origPadEnd);
const padEndExtra = blockShape.map((b, i) => (b - fullInputShape[i] % b) % b);
const padEnd = origPadEnd.map((s, i) => s + padEndExtra[i]);
const paddings = blockShape.map((_, i) => [padStart[i], padEnd[i]]);
const crops = blockShape.map((_, i) => [0, padEndExtra[i]]);
return [paddings, crops];
}
// Helper function to compute base paddings for pool with dilation > 1.
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L524
function withSpaceToBatchBasePaddings(filterShape, dilation) {
// Spatial dimensions of the filters and the upsampled filters in which we
// introduce (rate - 1) zeros between consecutive filter values.
const dilatedFilterShape = filterShape.map((s, i) => {
return s + (s - 1) * (dilation[i] - 1);
});
const padExtraShape = dilatedFilterShape.map(s => s - 1);
// When padding is odd, we pad more at end, following the same
// convention as conv2d.
const padExtraStart = padExtraShape.map(s => Math.floor(s / 2));
const padExtraEnd = padExtraShape.map((s, i) => s - padExtraStart[i]);
return padExtraShape.map((_, i) => {
return [padExtraStart[i], padExtraEnd[i]];
});
}
const pool = Object(_operation__WEBPACK_IMPORTED_MODULE_6__[/* op */ "b"])({ pool_ });
//# sourceMappingURL=pool.js.map
/***/ }),
/* 170 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return prod; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _cast__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(12);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the product of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and a
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.prod().print(); // or tf.prod(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.prod(axis).print(); // or tf.prod(x, axis)
* ```
*
* @param x The input tensor to compute the product over. If the dtype is `bool`
* it will be converted to `int32` and the output dtype will be `int32`.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function prod_(x, axis = null, keepDims = false) {
let $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'prod');
if ($x.dtype === 'bool') {
// bool is not an allowed type for the underlying kernel.
$x = Object(_cast__WEBPACK_IMPORTED_MODULE_3__[/* cast */ "a"])($x, 'int32');
}
const inputs = { x: $x };
const attrs = { axis, keepDims };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Prod */ "ic"], inputs, attrs);
}
const prod = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ prod_ });
//# sourceMappingURL=prod.js.map
/***/ }),
/* 171 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return randomUniform; });
/* harmony import */ var _buffer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var _rand_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(102);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a uniform distribution.
*
* The generated values follow a uniform distribution in the range [minval,
* maxval). The lower bound minval is included in the range, while the upper
* bound maxval is excluded.
*
* ```js
* tf.randomUniform([2, 2]).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param minval The lower bound on the range of random values to generate.
* Defaults to 0.
* @param maxval The upper bound on the range of random values to generate.
* Defaults to 1.
* @param dtype The data type of the output tensor. Defaults to 'float32'.
*
* @doc {heading: 'Tensors', subheading: 'Random'}
*/
function randomUniform_(shape, minval = 0, maxval = 1, dtype = 'float32', seed) {
const res = Object(_buffer__WEBPACK_IMPORTED_MODULE_0__[/* buffer */ "a"])(shape, dtype);
const random = new _rand_util__WEBPACK_IMPORTED_MODULE_2__[/* UniformRandom */ "c"](minval, maxval, null, seed);
for (let i = 0; i < res.values.length; i++) {
res.values[i] = random.nextValue();
}
return res.toTensor();
}
const randomUniform = Object(_operation__WEBPACK_IMPORTED_MODULE_1__[/* op */ "b"])({ randomUniform_ });
//# sourceMappingURL=random_uniform.js.map
/***/ }),
/* 172 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return rsqrt; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes reciprocal of square root of the input `tf.Tensor` element-wise:
* `y = 1 / sqrt(x)`
*
* ```js
* const x = tf.tensor1d([1, 2, 4, -1]);
*
* x.rsqrt().print(); // or tf.rsqrt(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function rsqrt_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'rsqrt');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Rsqrt */ "xc"], inputs);
}
const rsqrt = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ rsqrt_ });
//# sourceMappingURL=rsqrt.js.map
/***/ }),
/* 173 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return selu; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes scaled exponential linear element-wise.
*
* `x < 0 ? scale * alpha * (exp(x) - 1) : x`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.selu().print(); // or tf.selu(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function selu_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'selu');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Selu */ "Ac"], inputs);
}
const selu = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ selu_ });
//# sourceMappingURL=selu.js.map
/***/ }),
/* 174 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return separableConv2d; });
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
/* harmony import */ var _conv2d__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(65);
/* harmony import */ var _depthwise_conv2d__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(92);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7);
/**
* 2-D convolution with separable filters.
*
* Performs a depthwise convolution that acts separately on channels followed
* by a pointwise convolution that mixes channels. Note that this is
* separability between dimensions [1, 2] and 3, not spatial separability
* between dimensions 1 and 2.
*
* See
* [https://www.tensorflow.org/api_docs/python/tf/nn/separable_conv2d](
* https://www.tensorflow.org/api_docs/python/tf/nn/separable_conv2d)
* for more details.
*
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param depthwiseFilter The depthwise filter tensor, rank 4, of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]`. This is
* the filter used in the first step.
* @param pointwiseFilter The pointwise filter tensor, rank 4, of shape
* `[1, 1, inChannels * channelMultiplier, outChannels]`. This is
* the filter used in the second step.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`. If strides is a single number, then `strideHeight ==
* strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels]. Only "NHWC" is currently supported.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function separableConv2d_(x, depthwiseFilter, pointwiseFilter, strides, pad, dilation = [1, 1], dataFormat = 'NHWC') {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* convertToTensor */ "a"])(x, 'x', 'separableConv2d');
const $depthwiseFilter = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* convertToTensor */ "a"])(depthwiseFilter, 'depthwiseFilter', 'separableConv2d');
const $pointwiseFilter = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* convertToTensor */ "a"])(pointwiseFilter, 'pointwiseFilter', 'separableConv2d');
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
if (dataFormat === 'NCHW') {
throw new Error('separableConv2d currently does not support dataFormat NCHW; only ' +
'NHWC is supported');
}
_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"](x4D.rank === 4, () => `Error in separableConv2d: input must be rank 4, but got ` +
`rank ${x4D.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"]($depthwiseFilter.rank === 4, () => `Error in separableConv2d: depthwise filter must be rank 4, but ` +
`got rank ${$depthwiseFilter.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"]($pointwiseFilter.rank === 4, () => `Error in separableConv2d: pointwise filter must be rank 4, but ` +
`got rank ${$depthwiseFilter.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"]($pointwiseFilter.shape[0] === 1, () => `Error in separableConv2d: the first dimension of pointwise filter ` +
` must be 1, but got ${$pointwiseFilter.shape[0]}.`);
_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"]($pointwiseFilter.shape[1] === 1, () => `Error in separableConv2d: the second dimension of pointwise ` +
`filter must be 1, but got ${$pointwiseFilter.shape[1]}.`);
const inChannels = $depthwiseFilter.shape[2];
const channelMultiplier = $depthwiseFilter.shape[3];
_util__WEBPACK_IMPORTED_MODULE_1__[/* assert */ "b"]($pointwiseFilter.shape[2] === inChannels * channelMultiplier, () => `Error in separableConv2d: the third dimension of pointwise filter ` +
`must be ${inChannels * channelMultiplier}, ` +
`but got ${$pointwiseFilter.shape[2]}.`);
const depthwise = Object(_depthwise_conv2d__WEBPACK_IMPORTED_MODULE_3__[/* depthwiseConv2d */ "a"])(x4D, $depthwiseFilter, strides, pad, dataFormat, dilation);
const pointwiseStride = 1;
const res = Object(_conv2d__WEBPACK_IMPORTED_MODULE_2__[/* conv2d */ "a"])(depthwise, $pointwiseFilter, pointwiseStride, 'valid', dataFormat);
if (reshapedTo4D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const separableConv2d = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ separableConv2d_ });
//# sourceMappingURL=separable_conv2d.js.map
/***/ }),
/* 175 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return sin; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes sin of the input Tensor element-wise: `sin(x)`
*
* ```js
* const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);
*
* x.sin().print(); // or tf.sin(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function sin_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'sin');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Sin */ "Dc"], inputs);
}
const sin = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ sin_ });
//# sourceMappingURL=sin.js.map
/***/ }),
/* 176 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return sinh; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes hyperbolic sin of the input `tf.Tensor` element-wise: `sinh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.sinh().print(); // or tf.sinh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function sinh_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'sinh');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Sinh */ "Ec"], inputs);
}
const sinh = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ sinh_ });
//# sourceMappingURL=sinh.js.map
/***/ }),
/* 177 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return irfft; });
/* harmony import */ var _complex__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(58);
/* harmony import */ var _concat__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32);
/* harmony import */ var _imag__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(121);
/* harmony import */ var _mul__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(9);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/* harmony import */ var _real__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(107);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7);
/* harmony import */ var _reverse__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(48);
/* harmony import */ var _scalar__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(16);
/* harmony import */ var _slice__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(28);
/* harmony import */ var _ifft__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(108);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Inversed real value input fast Fourier transform.
*
* Computes the 1-dimensional inversed discrete Fourier transform over the
* inner-most dimension of the real input.
*
* ```js
* const real = tf.tensor1d([1, 2, 3]);
* const imag = tf.tensor1d([0, 0, 0]);
* const x = tf.complex(real, imag);
*
* x.irfft().print();
* ```
* @param input The real value input to compute an irfft over.
*
* @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}
*/
function irfft_(input) {
const innerDimensionSize = input.shape[input.shape.length - 1];
const batch = input.size / innerDimensionSize;
let ret;
if (innerDimensionSize <= 2) {
const complexInput = Object(_reshape__WEBPACK_IMPORTED_MODULE_6__[/* reshape */ "a"])(input, [batch, innerDimensionSize]);
ret = Object(_ifft__WEBPACK_IMPORTED_MODULE_10__[/* ifft */ "a"])(complexInput);
}
else {
// The length of unique components of the DFT of a real-valued signal
// is 2 * (input_len - 1)
const outputShape = [batch, 2 * (innerDimensionSize - 1)];
const realInput = Object(_reshape__WEBPACK_IMPORTED_MODULE_6__[/* reshape */ "a"])(Object(_real__WEBPACK_IMPORTED_MODULE_5__[/* real */ "a"])(input), [batch, innerDimensionSize]);
const imagInput = Object(_reshape__WEBPACK_IMPORTED_MODULE_6__[/* reshape */ "a"])(Object(_imag__WEBPACK_IMPORTED_MODULE_2__[/* imag */ "a"])(input), [batch, innerDimensionSize]);
const realConjugate = Object(_reverse__WEBPACK_IMPORTED_MODULE_7__[/* reverse */ "a"])(Object(_slice__WEBPACK_IMPORTED_MODULE_9__[/* slice */ "a"])(realInput, [0, 1], [batch, innerDimensionSize - 2]), 1);
const imagConjugate = Object(_mul__WEBPACK_IMPORTED_MODULE_3__[/* mul */ "a"])(Object(_reverse__WEBPACK_IMPORTED_MODULE_7__[/* reverse */ "a"])(Object(_slice__WEBPACK_IMPORTED_MODULE_9__[/* slice */ "a"])(imagInput, [0, 1], [batch, innerDimensionSize - 2]), 1), Object(_scalar__WEBPACK_IMPORTED_MODULE_8__[/* scalar */ "a"])(-1));
const r = Object(_concat__WEBPACK_IMPORTED_MODULE_1__[/* concat */ "a"])([realInput, realConjugate], 1);
const i = Object(_concat__WEBPACK_IMPORTED_MODULE_1__[/* concat */ "a"])([imagInput, imagConjugate], 1);
const complexInput = Object(_reshape__WEBPACK_IMPORTED_MODULE_6__[/* reshape */ "a"])(Object(_complex__WEBPACK_IMPORTED_MODULE_0__[/* complex */ "a"])(r, i), [outputShape[0], outputShape[1]]);
ret = Object(_ifft__WEBPACK_IMPORTED_MODULE_10__[/* ifft */ "a"])(complexInput);
}
ret = Object(_real__WEBPACK_IMPORTED_MODULE_5__[/* real */ "a"])(ret);
// reshape the result if the input is 3D tensor.
if (input.rank === 3 && input.shape[0] !== 0) {
const temp = ret;
const batch = input.shape[0];
ret = Object(_reshape__WEBPACK_IMPORTED_MODULE_6__[/* reshape */ "a"])(ret, [batch, ret.shape[0] / batch, ret.shape[1]]);
temp.dispose();
}
return ret;
}
const irfft = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ irfft_ });
//# sourceMappingURL=irfft.js.map
/***/ }),
/* 178 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return tensor3d; });
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
/* harmony import */ var _tensor_ops_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(51);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates rank-3 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor3d` as it makes the code more readable.
*
* ```js
* // Pass a nested array.
* tf.tensor3d([[[1], [2]], [[3], [4]]]).print();
* ```
* ```js
* // Pass a flat array and specify a shape.
* tf.tensor3d([1, 2, 3, 4], [2, 2, 1]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`.
* @param shape The shape of the tensor. If not provided, it is inferred from
* `values`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor3d(values, shape, dtype) {
Object(_util__WEBPACK_IMPORTED_MODULE_1__[/* assertNonNull */ "d"])(values);
if (shape != null && shape.length !== 3) {
throw new Error('tensor3d() requires shape to have three numbers');
}
const inferredShape = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_0__[/* inferShape */ "c"])(values, dtype);
if (inferredShape.length !== 3 && inferredShape.length !== 1) {
throw new Error('tensor3d() requires values to be number[][][] or flat/TypedArray');
}
if (inferredShape.length === 1 && shape == null) {
throw new Error('tensor3d() requires shape to be provided when `values` ' +
'are a flat array');
}
return Object(_tensor_ops_util__WEBPACK_IMPORTED_MODULE_2__[/* makeTensor */ "a"])(values, shape, inferredShape, dtype);
}
//# sourceMappingURL=tensor3d.js.map
/***/ }),
/* 179 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return topk; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Finds the values and indices of the `k` largest entries along the last
* dimension.
*
* If the input is a vector (rank=1), finds the k largest entries in the vector
* and outputs their values and indices as vectors. Thus values[j] is the j-th
* largest entry in input, and its index is indices[j].
* For higher rank inputs, computes the top k entries along the last dimension.
*
* If two elements are equal, the lower-index element appears first.
*
* ```js
* const a = tf.tensor2d([[1, 5], [4, 3]]);
* const {values, indices} = tf.topk(a);
* values.print();
* indices.print();
* ```
* @param x 1-D or higher `tf.Tensor` with last dimension being at least `k`.
* @param k Number of top elements to look for along the last dimension.
* @param sorted If true, the resulting `k` elements will be sorted by the
* values in descending order.
*
* @doc {heading: 'Operations', subheading: 'Evaluation'}
*/
function topk_(x, k = 1, sorted = true) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'topk');
if ($x.rank === 0) {
throw new Error('topk() expects the input to be of rank 1 or higher');
}
const lastDim = $x.shape[$x.shape.length - 1];
if (k > lastDim) {
throw new Error(`'k' passed to topk() must be <= the last dimension (${lastDim}) ` +
`but got ${k}`);
}
const inputs = { x: $x };
const attrs = { k, sorted };
const [values, indices] = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* TopK */ "Wc"], inputs, attrs);
return { values, indices };
}
const topk = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ topk_ });
//# sourceMappingURL=topk.js.map
/***/ }),
/* 180 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return unique; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Finds unique elements along an axis of a tensor.
*
* It returns a tensor `values` containing all of the unique elements along the
* `axis` of the given tensor `x` in the same order that they occur along the
* `axis` in `x`; `x` does not need to be sorted. It also returns a tensor
* `indices` the same size as the number of the elements in `x` along the `axis`
* dimension. It contains the index in the unique output `values`.
*
* ```js
* // A 1-D tensor
* const a = tf.tensor1d([1, 1, 2, 4, 4, 4, 7, 8, 8]);
* const {values, indices} = tf.unique(a);
* values.print(); // [1, 2, 4, 7, 8,]
* indices.print(); // [0, 0, 1, 2, 2, 2, 3, 4, 4]
* ```
*
* ```js
* // A 2-D tensor with axis=0
* //
* // 'a' is: [[1, 0, 0],
* // [1, 0, 0],
* // [2, 0, 0]]
* const a = tf.tensor2d([[1, 0, 0], [1, 0, 0], [2, 0, 0]]);
* const {values, indices} = tf.unique(a, 0)
* values.print(); // [[1, 0, 0],
* // [2, 0, 0]]
* indices.print(); // [0, 0, 1]
* ```
*
* ```js
* // A 2-D tensor with axis=1
* //
* // 'a' is: [[1, 0, 0],
* // [1, 0, 0],
* // [2, 0, 0]]
* const a = tf.tensor2d([[1, 0, 0], [1, 0, 0], [2, 0, 0]]);
* const {values, indices} = tf.unique(a, 1)
* values.print(); // [[1, 0],
* // [1, 0],
* // [2, 0]]
* indices.print(); // [0, 1, 1]
* ```
* @param x A tensor (int32, string, bool).
* @param axis The axis of the tensor to find the unique elements.
* @returns [uniqueElements, indices] (see above for details)
*
* @doc {heading: 'Operations', subheading: 'Evaluation'}
*/
function unique_(x, axis = 0) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'unique', 'string_or_numeric');
Object(_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"])($x.rank > 0, () => 'The input tensor must be at least 1D');
const inputs = { x: $x };
const attrs = { axis };
const [values, indices] = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Unique */ "Zc"], inputs, attrs);
return { values, indices };
}
const unique = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ unique_ });
//# sourceMappingURL=unique.js.map
/***/ }),
/* 181 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return whereAsync; });
/* harmony import */ var _backends_where_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(182);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(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.
* =============================================================================
*/
/**
* Returns the coordinates of true elements of condition.
*
* The coordinates are returned in a 2-D tensor where the first dimension (rows)
* represents the number of true elements, and the second dimension (columns)
* represents the coordinates of the true elements. Keep in mind, the shape of
* the output tensor can vary depending on how many true values there are in
* input. Indices are output in row-major order. The resulting tensor has the
* shape `[numTrueElems, condition.rank]`.
*
* This is analogous to calling the python `tf.where(cond)` without an x or y.
*
* ```js
* const cond = tf.tensor1d([false, false, true], 'bool');
* const result = await tf.whereAsync(cond);
* result.print();
* ```
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
async function whereAsync_(condition) {
const $condition = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_1__[/* convertToTensor */ "a"])(condition, 'condition', 'whereAsync', 'bool');
const vals = await $condition.data();
const res = Object(_backends_where_impl__WEBPACK_IMPORTED_MODULE_0__[/* whereImpl */ "a"])($condition.shape, vals);
if (condition !== $condition) {
$condition.dispose();
}
return res;
}
const whereAsync = whereAsync_;
//# sourceMappingURL=where_async.js.map
/***/ }),
/* 182 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return whereImpl; });
/* harmony import */ var _ops_buffer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** An implementation of the Where kernel shared between cpu and webgl */
function whereImpl(condShape, condVals) {
const indices = [];
for (let i = 0; i < condVals.length; i++) {
if (condVals[i]) {
indices.push(i);
}
}
const inBuffer = Object(_ops_buffer__WEBPACK_IMPORTED_MODULE_0__[/* buffer */ "a"])(condShape, 'int32');
const out = Object(_ops_buffer__WEBPACK_IMPORTED_MODULE_0__[/* buffer */ "a"])([indices.length, condShape.length], 'int32');
for (let i = 0; i < indices.length; i++) {
const loc = inBuffer.indexToLoc(indices[i]);
const offset = i * condShape.length;
out.values.set(loc, offset);
}
return out.toTensor();
}
//# sourceMappingURL=where_impl.js.map
/***/ }),
/* 183 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _kernels_Abs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(184);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "simpleAbsImpl", function() { return _kernels_Abs__WEBPACK_IMPORTED_MODULE_0__["b"]; });
/* harmony import */ var _kernels_Add__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(68);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addImpl", function() { return _kernels_Add__WEBPACK_IMPORTED_MODULE_1__["c"]; });
/* harmony import */ var _kernels_Bincount_impl__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(98);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bincountImpl", function() { return _kernels_Bincount_impl__WEBPACK_IMPORTED_MODULE_2__["a"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bincountReduceImpl", function() { return _kernels_Bincount_impl__WEBPACK_IMPORTED_MODULE_2__["b"]; });
/* harmony import */ var _kernels_Ceil__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(185);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ceilImpl", function() { return _kernels_Ceil__WEBPACK_IMPORTED_MODULE_3__["b"]; });
/* harmony import */ var _kernels_Concat_impl__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(186);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "concatImpl", function() { return _kernels_Concat_impl__WEBPACK_IMPORTED_MODULE_4__["a"]; });
/* harmony import */ var _kernels_Exp__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(136);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "expImpl", function() { return _kernels_Exp__WEBPACK_IMPORTED_MODULE_5__["c"]; });
/* harmony import */ var _kernels_Expm1__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(187);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "expm1Impl", function() { return _kernels_Expm1__WEBPACK_IMPORTED_MODULE_6__["b"]; });
/* harmony import */ var _kernels_Floor__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(188);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "floorImpl", function() { return _kernels_Floor__WEBPACK_IMPORTED_MODULE_7__["b"]; });
/* harmony import */ var _kernels_GatherV2_impl__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(189);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "gatherV2Impl", function() { return _kernels_GatherV2_impl__WEBPACK_IMPORTED_MODULE_8__["a"]; });
/* harmony import */ var _kernels_Greater__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(190);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "greaterImpl", function() { return _kernels_Greater__WEBPACK_IMPORTED_MODULE_9__["b"]; });
/* harmony import */ var _kernels_Less__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(191);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "lessImpl", function() { return _kernels_Less__WEBPACK_IMPORTED_MODULE_10__["b"]; });
/* harmony import */ var _kernels_LinSpace_impl__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(192);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "linSpaceImpl", function() { return _kernels_LinSpace_impl__WEBPACK_IMPORTED_MODULE_11__["a"]; });
/* harmony import */ var _kernels_Log__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(193);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "logImpl", function() { return _kernels_Log__WEBPACK_IMPORTED_MODULE_12__["b"]; });
/* harmony import */ var _kernels_Max_impl__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(194);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "maxImpl", function() { return _kernels_Max_impl__WEBPACK_IMPORTED_MODULE_13__["a"]; });
/* harmony import */ var _kernels_Maximum__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(195);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "maximumImpl", function() { return _kernels_Maximum__WEBPACK_IMPORTED_MODULE_14__["b"]; });
/* harmony import */ var _kernels_Minimum__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(196);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "minimumImpl", function() { return _kernels_Minimum__WEBPACK_IMPORTED_MODULE_15__["b"]; });
/* harmony import */ var _kernels_Multiply__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(69);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "multiplyImpl", function() { return _kernels_Multiply__WEBPACK_IMPORTED_MODULE_16__["c"]; });
/* harmony import */ var _kernels_Neg__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(197);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "negImpl", function() { return _kernels_Neg__WEBPACK_IMPORTED_MODULE_17__["b"]; });
/* harmony import */ var _kernels_NotEqual__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(198);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "notEqualImpl", function() { return _kernels_NotEqual__WEBPACK_IMPORTED_MODULE_18__["b"]; });
/* harmony import */ var _kernels_Prod__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(199);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "prodImpl", function() { return _kernels_Prod__WEBPACK_IMPORTED_MODULE_19__["b"]; });
/* harmony import */ var _kernels_Range_impl__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(200);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "rangeImpl", function() { return _kernels_Range_impl__WEBPACK_IMPORTED_MODULE_20__["a"]; });
/* harmony import */ var _kernels_Rsqrt__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(201);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "rsqrtImpl", function() { return _kernels_Rsqrt__WEBPACK_IMPORTED_MODULE_21__["b"]; });
/* harmony import */ var _kernels_Slice__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(54);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sliceImpl", function() { return _kernels_Slice__WEBPACK_IMPORTED_MODULE_22__["c"]; });
/* harmony import */ var _kernels_SparseReshape_impl__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(202);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sparseReshapeImpl", function() { return _kernels_SparseReshape_impl__WEBPACK_IMPORTED_MODULE_23__["a"]; });
/* harmony import */ var _kernels_SquaredDifference__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(203);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "squaredDifferenceImpl", function() { return _kernels_SquaredDifference__WEBPACK_IMPORTED_MODULE_24__["b"]; });
/* harmony import */ var _kernels_StridedSlice_impl__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(204);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stridedSliceImpl", function() { return _kernels_StridedSlice_impl__WEBPACK_IMPORTED_MODULE_25__["a"]; });
/* harmony import */ var _kernels_Sub__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(99);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "subImpl", function() { return _kernels_Sub__WEBPACK_IMPORTED_MODULE_26__["c"]; });
/* harmony import */ var _kernels_Tile_impl__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(205);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "tileImpl", function() { return _kernels_Tile_impl__WEBPACK_IMPORTED_MODULE_27__["a"]; });
/* harmony import */ var _kernels_TopK_impl__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(206);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "topKImpl", function() { return _kernels_TopK_impl__WEBPACK_IMPORTED_MODULE_28__["a"]; });
/* harmony import */ var _kernels_Transpose_impl__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(137);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "transposeImpl", function() { return _kernels_Transpose_impl__WEBPACK_IMPORTED_MODULE_29__["a"]; });
/* harmony import */ var _kernels_Unique_impl__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(207);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "uniqueImpl", function() { return _kernels_Unique_impl__WEBPACK_IMPORTED_MODULE_30__["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.
* =============================================================================
*/
// Shared functionality among backends.
//# sourceMappingURL=shared.js.map
/***/ }),
/* 184 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return simpleAbsImpl; });
/* unused harmony export abs */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return absConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _cpu_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(11);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function simpleAbsImpl(vals) {
const resultValues = new Float32Array(vals.length);
for (let i = 0; i < vals.length; ++i) {
resultValues[i] = Math.abs(vals[i]);
}
return resultValues;
}
const abs = (args) => {
const { x } = args.inputs;
const cpuBackend = args.backend;
Object(_cpu_util__WEBPACK_IMPORTED_MODULE_1__[/* assertNotComplex */ "a"])(x, 'abs');
let resultValues = new Float32Array(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(x.shape));
const values = cpuBackend.data.get(x.dataId).values;
resultValues = simpleAbsImpl(values);
return cpuBackend.makeOutput(resultValues, x.shape, 'float32');
};
const absConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Abs"],
backendName: 'cpu',
kernelFunc: abs,
};
//# sourceMappingURL=Abs.js.map
/***/ }),
/* 185 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ceilImpl; });
/* unused harmony export ceil */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ceilConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _utils_unary_impl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(73);
/* harmony import */ var _utils_unary_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(18);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const ceilImpl = Object(_utils_unary_impl__WEBPACK_IMPORTED_MODULE_1__[/* createSimpleUnaryImpl */ "a"])((xi) => Math.ceil(xi));
const ceil = Object(_utils_unary_utils__WEBPACK_IMPORTED_MODULE_2__[/* unaryKernelFuncFromImpl */ "b"])(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Ceil"], ceilImpl);
const ceilConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Ceil"],
backendName: 'cpu',
kernelFunc: ceil,
};
//# sourceMappingURL=Ceil.js.map
/***/ }),
/* 186 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return concatImpl; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function concatImpl(inputs, outShape, dtype, simplyConcat) {
const outVals = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].getArrayFromDType(dtype, _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(outShape));
if (simplyConcat && dtype !== 'string') {
// Use built-in TypedArray.set() method for speed.
let offset = 0;
inputs.forEach(input => {
const size = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(input.shape);
outVals.set(input.vals, offset);
offset += size;
});
}
else {
let colOffset = 0;
inputs.forEach(input => {
const decodedData = dtype === 'string' ?
_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["backend_util"].fromUint8ToStringArray(input.vals) :
input.vals;
let tIdx = 0;
for (let row = 0; row < input.shape[0]; ++row) {
const resIdx = row * outShape[1] + colOffset;
for (let col = 0; col < input.shape[1]; ++col) {
outVals[resIdx + col] = decodedData[tIdx++];
}
}
colOffset += input.shape[1];
});
}
return outVals;
}
//# sourceMappingURL=Concat_impl.js.map
/***/ }),
/* 187 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return expm1Impl; });
/* unused harmony export expm1 */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return expm1Config; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _utils_unary_impl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(73);
/* harmony import */ var _utils_unary_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(18);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const expm1Impl = Object(_utils_unary_impl__WEBPACK_IMPORTED_MODULE_1__[/* createSimpleUnaryImpl */ "a"])((xi) => Math.expm1(xi));
const expm1 = Object(_utils_unary_utils__WEBPACK_IMPORTED_MODULE_2__[/* unaryKernelFuncFromImpl */ "b"])(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Expm1"], expm1Impl);
const expm1Config = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Expm1"],
backendName: 'cpu',
kernelFunc: expm1,
};
//# sourceMappingURL=Expm1.js.map
/***/ }),
/* 188 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return floorImpl; });
/* unused harmony export floor */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return floorConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _utils_unary_impl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(73);
/* harmony import */ var _utils_unary_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(18);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const floorImpl = Object(_utils_unary_impl__WEBPACK_IMPORTED_MODULE_1__[/* createSimpleUnaryImpl */ "a"])((xi) => Math.floor(xi));
const floor = Object(_utils_unary_utils__WEBPACK_IMPORTED_MODULE_2__[/* unaryKernelFuncFromImpl */ "b"])(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Floor"], floorImpl);
const floorConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Floor"],
backendName: 'cpu',
kernelFunc: floor,
};
//# sourceMappingURL=Floor.js.map
/***/ }),
/* 189 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return gatherV2Impl; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function gatherV2Impl(xBuf, indicesBuf, flattenOutputShape) {
const outBuf = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["buffer"])(flattenOutputShape, xBuf.dtype);
for (let i = 0; i < outBuf.size; ++i) {
const newLoc = outBuf.indexToLoc(i);
const originalLoc = newLoc.slice();
const batchIdx = originalLoc[0];
const indicesIdx = originalLoc[2];
const indicesIndex = indicesBuf.locToIndex([batchIdx, indicesIdx]);
originalLoc[2] = indicesBuf.values[indicesIndex];
const originalIndex = xBuf.locToIndex(originalLoc);
outBuf.values[i] = xBuf.values[originalIndex];
}
return outBuf;
}
//# sourceMappingURL=GatherV2_impl.js.map
/***/ }),
/* 190 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return greaterImpl; });
/* unused harmony export greater */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return greaterConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(27);
/* harmony import */ var _utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const greaterImpl = Object(_utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__[/* createSimpleBinaryKernelImpl */ "a"])((a, b) => (a > b) ? 1 : 0);
const greater = Object(_utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__[/* binaryKernelFunc */ "a"])(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Greater"], greaterImpl, null /* complexImpl */, 'bool');
const greaterConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Greater"],
backendName: 'cpu',
kernelFunc: greater
};
//# sourceMappingURL=Greater.js.map
/***/ }),
/* 191 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return lessImpl; });
/* unused harmony export less */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return lessConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(27);
/* harmony import */ var _utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const lessImpl = Object(_utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__[/* createSimpleBinaryKernelImpl */ "a"])((a, b) => (a < b) ? 1 : 0);
const less = Object(_utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__[/* binaryKernelFunc */ "a"])(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Less"], lessImpl, null /* complexImpl */, 'bool');
const lessConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Less"],
backendName: 'cpu',
kernelFunc: less
};
//# sourceMappingURL=Less.js.map
/***/ }),
/* 192 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return linSpaceImpl; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function linSpaceImpl(start, stop, num) {
const step = (stop - start) / (num - 1);
const values = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].makeZerosTypedArray(num, 'float32');
values[0] = start;
for (let i = 1; i < values.length; i++) {
values[i] = values[i - 1] + step;
}
return values;
}
//# sourceMappingURL=LinSpace_impl.js.map
/***/ }),
/* 193 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return logImpl; });
/* unused harmony export log */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return logConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _utils_unary_impl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(73);
/* harmony import */ var _utils_unary_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(18);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const logImpl = Object(_utils_unary_impl__WEBPACK_IMPORTED_MODULE_1__[/* createSimpleUnaryImpl */ "a"])((xi) => Math.log(xi));
const log = Object(_utils_unary_utils__WEBPACK_IMPORTED_MODULE_2__[/* unaryKernelFuncFromImpl */ "b"])(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Log"], logImpl);
const logConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Log"],
backendName: 'cpu',
kernelFunc: log,
};
//# sourceMappingURL=Log.js.map
/***/ }),
/* 194 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return maxImpl; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function maxImpl(aVals, reduceSize, outShape, dtype) {
const vals = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].getTypedArrayFromDType(dtype, _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(outShape));
for (let i = 0; i < vals.length; ++i) {
const offset = i * reduceSize;
let max = aVals[offset];
for (let j = 0; j < reduceSize; ++j) {
const value = aVals[offset + j];
if (value > max) {
max = value;
}
}
vals[i] = max;
}
return vals;
}
//# sourceMappingURL=Max_impl.js.map
/***/ }),
/* 195 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return maximumImpl; });
/* unused harmony export maximum */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return maximumConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(27);
/* harmony import */ var _utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const maximumImpl = Object(_utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__[/* createSimpleBinaryKernelImpl */ "a"])(((aValue, bValue) => Math.max(aValue, bValue)));
const maximum = Object(_utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__[/* binaryKernelFunc */ "a"])(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Maximum"], maximumImpl);
const maximumConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Maximum"],
backendName: 'cpu',
kernelFunc: maximum
};
//# sourceMappingURL=Maximum.js.map
/***/ }),
/* 196 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return minimumImpl; });
/* unused harmony export minimum */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return minimumConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(27);
/* harmony import */ var _utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const minimumImpl = Object(_utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__[/* createSimpleBinaryKernelImpl */ "a"])(((aValue, bValue) => Math.min(aValue, bValue)));
const minimum = Object(_utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__[/* binaryKernelFunc */ "a"])(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Minimum"], minimumImpl);
const minimumConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Minimum"],
backendName: 'cpu',
kernelFunc: minimum
};
//# sourceMappingURL=Minimum.js.map
/***/ }),
/* 197 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return negImpl; });
/* unused harmony export neg */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return negConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _cpu_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(11);
/* harmony import */ var _Multiply__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(69);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function negImpl(xVals, xShape, xDtype) {
const minusOne = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].createScalarValue(-1, xDtype);
return Object(_Multiply__WEBPACK_IMPORTED_MODULE_2__[/* multiplyImpl */ "c"])([], xShape, minusOne, xVals, xDtype);
}
function neg(args) {
const { inputs, backend } = args;
const { x } = inputs;
Object(_cpu_util__WEBPACK_IMPORTED_MODULE_1__[/* assertNotComplex */ "a"])(x, 'neg');
const xVals = backend.data.get(x.dataId).values;
const [res, newShape] = negImpl(xVals, x.shape, x.dtype);
return backend.makeTensorInfo(newShape, x.dtype, res);
}
const negConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Neg"],
backendName: 'cpu',
kernelFunc: neg
};
//# sourceMappingURL=Neg.js.map
/***/ }),
/* 198 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return notEqualImpl; });
/* unused harmony export notEqual */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return notEqualConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(27);
/* harmony import */ var _utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const notEqualImpl = Object(_utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__[/* createSimpleBinaryKernelImpl */ "a"])(((a, b) => (a !== b) ? 1 : 0));
const notEqual = Object(_utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__[/* binaryKernelFunc */ "a"])(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["NotEqual"], notEqualImpl, null /* complexOp */, 'bool');
const notEqualConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["NotEqual"],
backendName: 'cpu',
kernelFunc: notEqual
};
//# sourceMappingURL=NotEqual.js.map
/***/ }),
/* 199 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return prodImpl; });
/* unused harmony export prod */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return prodConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _cpu_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(11);
/* harmony import */ var _Transpose__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(33);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function prodImpl(xShape, xDtype, xVals, reductionAxes) {
const [outShape, reduceShape] = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["backend_util"].computeOutAndReduceShapes(xShape, reductionAxes);
const outDtype = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["upcastType"])(xDtype, 'int32');
const outVals = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].makeZerosTypedArray(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(outShape), outDtype);
const reduceSize = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(reduceShape);
for (let i = 0; i < outVals.length; ++i) {
const offset = i * reduceSize;
let prod = 1;
for (let j = 0; j < reduceSize; ++j) {
prod *= xVals[offset + j];
}
outVals[i] = prod;
}
return { outVals, outShape, outDtype };
}
function prod(args) {
const { inputs, backend, attrs } = args;
const { x } = inputs;
const { axis, keepDims } = attrs;
Object(_cpu_util__WEBPACK_IMPORTED_MODULE_1__[/* assertNotComplex */ "a"])(x, 'prod');
const xRank = x.shape.length;
const axes = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].parseAxisParam(axis, x.shape);
const permutation = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["backend_util"].getAxesPermutation(axes, xRank);
let reductionAxes = axes;
let permutedX = x;
const intermediateTensorInfos = [];
if (permutation != null) {
permutedX = Object(_Transpose__WEBPACK_IMPORTED_MODULE_2__[/* transpose */ "a"])({ inputs: { x }, backend, attrs: { perm: permutation } });
intermediateTensorInfos.push(permutedX);
reductionAxes = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["backend_util"].getInnerMostAxes(reductionAxes.length, xRank);
}
const xVals = backend.data.get(permutedX.dataId).values;
const { outVals, outShape, outDtype } = prodImpl(permutedX.shape, permutedX.dtype, xVals, reductionAxes);
let resultShape = outShape;
if (keepDims) {
resultShape = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["backend_util"].expandShapeToKeepDim(outShape, axes);
}
intermediateTensorInfos.forEach(t => backend.disposeIntermediateTensorInfo(t));
return backend.makeTensorInfo(resultShape, outDtype, outVals);
}
const prodConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Prod"],
backendName: 'cpu',
kernelFunc: prod
};
//# sourceMappingURL=Prod.js.map
/***/ }),
/* 200 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return rangeImpl; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function rangeImpl(start, stop, step, dtype) {
const sameStartStop = start === stop;
const increasingRangeNegativeStep = start < stop && step < 0;
const decreasingRangePositiveStep = stop < start && step > 1;
if (sameStartStop || increasingRangeNegativeStep ||
decreasingRangePositiveStep) {
return _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].makeZerosTypedArray(0, dtype);
}
const numElements = Math.abs(Math.ceil((stop - start) / step));
const values = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].makeZerosTypedArray(numElements, dtype);
if (stop < start && step === 1) {
// Auto adjust the step's sign if it hasn't been set
// (or was set to 1)
step = -1;
}
values[0] = start;
for (let i = 1; i < values.length; i++) {
values[i] = values[i - 1] + step;
}
return values;
}
//# sourceMappingURL=Range_impl.js.map
/***/ }),
/* 201 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return rsqrtImpl; });
/* unused harmony export rsqrt */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return rsqrtConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _utils_unary_impl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(73);
/* harmony import */ var _utils_unary_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(18);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const rsqrtImpl = Object(_utils_unary_impl__WEBPACK_IMPORTED_MODULE_1__[/* createSimpleUnaryImpl */ "a"])((xi) => 1 / Math.sqrt(xi));
const rsqrt = Object(_utils_unary_utils__WEBPACK_IMPORTED_MODULE_2__[/* unaryKernelFuncFromImpl */ "b"])(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Rsqrt"], rsqrtImpl);
const rsqrtConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Rsqrt"],
backendName: 'cpu',
kernelFunc: rsqrt,
};
//# sourceMappingURL=Rsqrt.js.map
/***/ }),
/* 202 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return sparseReshapeImpl; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @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 sparseReshapeImpl(inputIndices, inputIndicesShape, inputDType, inputShape, targetShape) {
const denseSize = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(inputShape);
const nnz = inputIndicesShape[0];
const outputRank = targetShape.length;
// Compute the output shape. Determine product of specified dimensions, and
// find the index of the unspecified one.
const outputShape = [];
let product = 1;
let unknownIndex = -1;
for (let d = 0; d < outputRank; ++d) {
const size = targetShape[d];
if (size === -1) {
if (unknownIndex !== -1) {
throw new Error(`only one output dimension may be -1, not both ${unknownIndex} and ${d}`);
}
unknownIndex = d;
outputShape.push(1);
}
else {
if (size < 0) {
throw new Error(`size ${d} must be non-negative, not ${size}`);
}
product *= size;
outputShape.push(size);
}
}
if (unknownIndex !== -1) {
if (product <= 0) {
throw new Error('reshape cannot infer the missing ' +
'input size for an empty tensor unless all ' +
'specified input sizes are non-zero');
}
const missing = Math.trunc(denseSize / product);
if (product * missing !== denseSize) {
throw new Error(`Input to reshape is a SparseTensor with ${denseSize}
dense values, but the requested shape requires a multiple of ${product}. inputShape=${inputShape} outputShape= ${outputShape}`);
}
outputShape[unknownIndex] = missing;
}
const outputSize = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(outputShape);
if (outputSize !== denseSize) {
throw new Error(`Input to reshape is a tensor with ${denseSize} dense values, but the requested shape has ${outputSize}. inputShape=${inputShape} outputShape=${outputShape}`);
}
const inputRank = inputShape.length;
const inputStrides = [];
if (inputRank > 0) {
inputStrides[inputRank - 1] = 1;
for (let d = inputRank - 2; d >= 0; --d) {
inputStrides[d] = inputStrides[d + 1] * inputShape[d + 1];
}
}
const outputStrides = [];
if (outputRank > 0) {
outputStrides[outputRank - 1] = 1;
for (let d = outputRank - 2; d >= 0; --d) {
outputStrides[d] = outputStrides[d + 1] * outputShape[d + 1];
}
}
const newIndices = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].getArrayFromDType(inputDType, nnz * outputRank);
for (let i = 0; i < nnz; ++i) {
let id = 0;
for (let j = 0; j < inputRank; ++j) {
// inputIndices is a 2d tensor with shape of [nnz, inputRank]
id += inputIndices[i * inputRank + j] * inputStrides[j];
}
for (let j = 0; j < outputRank; ++j) {
// newIndices is a 2d tensor with shape of [nnz, outputRank]
newIndices[i * outputRank + j] = Math.trunc(id / outputStrides[j]);
id %= outputStrides[j];
}
}
return [newIndices, [nnz, outputRank], outputShape];
}
//# sourceMappingURL=SparseReshape_impl.js.map
/***/ }),
/* 203 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return squaredDifferenceImpl; });
/* unused harmony export squaredDifference */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return squaredDifferenceConfig; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(27);
/* harmony import */ var _utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const squaredDifferenceImpl = Object(_utils_binary_impl__WEBPACK_IMPORTED_MODULE_1__[/* createSimpleBinaryKernelImpl */ "a"])(((a, b) => {
const diff = a - b;
return diff * diff;
}));
const squaredDifference = Object(_utils_binary_utils__WEBPACK_IMPORTED_MODULE_2__[/* binaryKernelFunc */ "a"])(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["SquaredDifference"], squaredDifferenceImpl);
const squaredDifferenceConfig = {
kernelName: _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["SquaredDifference"],
backendName: 'cpu',
kernelFunc: squaredDifference
};
//# sourceMappingURL=SquaredDifference.js.map
/***/ }),
/* 204 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return stridedSliceImpl; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function stridedSliceImpl(outShape, xBuf, strides, begin) {
const outBuf = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["buffer"])(outShape, xBuf.dtype);
for (let i = 0; i < outBuf.size; i++) {
const loc = outBuf.indexToLoc(i);
const newLoc = new Array(loc.length);
for (let j = 0; j < newLoc.length; j++) {
newLoc[j] = loc[j] * strides[j] + begin[j];
}
outBuf.set(xBuf.get(...newLoc), ...loc);
}
return outBuf;
}
//# sourceMappingURL=StridedSlice_impl.js.map
/***/ }),
/* 205 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return tileImpl; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* An implementation of the tile kernel shared between webgl and cpu for string
* tensors only.
*/
function tileImpl(xBuf, reps) {
const newShape = new Array(xBuf.rank);
for (let i = 0; i < newShape.length; i++) {
newShape[i] = xBuf.shape[i] * reps[i];
}
const result = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["buffer"])(newShape, xBuf.dtype);
for (let i = 0; i < result.values.length; ++i) {
const newLoc = result.indexToLoc(i);
const originalLoc = new Array(xBuf.rank);
for (let j = 0; j < originalLoc.length; j++) {
originalLoc[j] = newLoc[j] % xBuf.shape[j];
}
const originalIndex = xBuf.locToIndex(originalLoc);
result.values[i] = xBuf.values[originalIndex];
}
return result;
}
//# sourceMappingURL=Tile_impl.js.map
/***/ }),
/* 206 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return topKImpl; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** An implementation of the TopK kernel shared between webgl and cpu. */
function topKImpl(x, xShape, xDtype, k, sorted) {
// Reshape into a 2d tensor [batch, lastDim] and compute topk along lastDim.
const lastDim = xShape[xShape.length - 1];
const [batch, size] = [x.length / lastDim, lastDim];
const allTopKVals = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].getTypedArrayFromDType(xDtype, batch * k);
const allTopKIndices = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].getTypedArrayFromDType('int32', batch * k);
for (let b = 0; b < batch; b++) {
const offset = b * size;
const vals = x.subarray(offset, offset + size);
const valAndInd = [];
for (let i = 0; i < vals.length; i++) {
valAndInd.push({ value: vals[i], index: i });
}
valAndInd.sort((a, b) => b.value - a.value);
const outOffset = b * k;
const topKVals = allTopKVals.subarray(outOffset, outOffset + k);
const topKIndices = allTopKIndices.subarray(outOffset, outOffset + k);
for (let i = 0; i < k; i++) {
topKVals[i] = valAndInd[i].value;
topKIndices[i] = valAndInd[i].index;
}
}
// Reshape back to the original input shape, except that the last
// dimension is k.
const outputShape = xShape.slice();
outputShape[outputShape.length - 1] = k;
return [
Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["buffer"])(outputShape, xDtype, allTopKVals),
Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["buffer"])(outputShape, 'int32', allTopKIndices)
];
}
//# sourceMappingURL=TopK_impl.js.map
/***/ }),
/* 207 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return uniqueImpl; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function uniqueImpl(values, axis, shape, dtype) {
// Normalize and validate axis.
const $axis = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].parseAxisParam(axis, shape)[0];
// Calculate the new shape that is suitable for extracting data along the
// given axis.
//
// The rank is 3.
// The size of the 1st dimension is the size of all the axes < the given axis.
// The size of the 2nd dimension is the same as the size of the given axis.
// The size of the 3rd dimension is the size of all the axes > the given axis.
//
// For example, for a 4D tensor with shape=[2, 3, 5, 4] and axis=2, the
// newShape would be: [2*3, 5, 4].
//
// Note that this is not the final output shape. This will be the shape for an
// intermediate TensorBuffer (see inputBuffer below) to allow us to extract
// values along the given axis. To demonstrate how it works, consider the
// following example:
//
// Input: a 3D tensor, with shape [1, 2, 3]
// [
// [
// [1,2,3],
// [4,5,6]
// ]
// ]
// Axis: 2 (the last axis).
// Along axis 2, we expect to extract 3 tensors: [1,4], [2,5], [3,6].
//
// For this example, newShape would be: [2, 3, 1], where 2 is calculated from
// 1*2. The re-shaped data would look like:
//
// [
// [
// [1], [2], [3]
// ],
// [
// [4], [5], [6]
// ]
// ]
//
// Then, we can construct a 3-level nested loop by the following dimension
// order to extract the values along the axis (dimension1):
// i: dimension1 // 0,1,2 (newShape[1])
// m: dimension0 // 0,1 (newShape[0])
// n: dimension2 // 0 (newShape[2])
//
// m, i, n
// ---------
// Iteration 0: data at [0, 0, 0] => "1"
// Iteration 1: data at [1, 0, 0] => "4"
// We got [1,4].
// Iteration 2: data at [0, 1, 0] => "2"
// Iteration 3: data at [1, 1, 0] => "5"
// We got [2,5].
// Iteration 4: data at [0, 2, 0] => "3"
// Iteration 5: data at [1, 2, 0] => "6"
// We got [3,6].
const newShape = [1, shape[0], 1];
for (let i = 0; i < $axis; i++) {
newShape[0] *= shape[i];
}
newShape[1] = shape[$axis];
for (let i = $axis + 1; i < shape.length; i++) {
newShape[2] *= shape[i];
}
// A map from unique elements (their string representations) to their values
// in "indices" (below).
const uniqueElements = {};
// The indices of each unique element in the original tensor along the given
// axis. It is 1D and has the same size as the given axis.
const indices = new Int32Array(shape[$axis]);
// Create a buffer so we can easily extract value at a given location.
const inputBuffer = new _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["TensorBuffer"](newShape, dtype, values);
// The indices along the given axis that have unique elements. This is a
// de-duped version of "indices" above.
const uniqueIndices = [];
const is1DTensor = newShape[0] === 1 && newShape[2] === 1;
for (let i = 0; i < shape[$axis]; i++) {
// Extract values along the axis.
let element;
if (is1DTensor) {
// Fast path for 1D tensor input.
element = values[i].toString();
}
else {
const axisValues = [];
for (let m = 0; m < newShape[0]; m++) {
for (let n = 0; n < newShape[2]; n++) {
axisValues.push(inputBuffer.get(m, i, n));
}
}
element = axisValues.join(',');
}
// Dedup and update various indices.
if (uniqueElements[element] !== undefined) {
indices[i] = uniqueElements[element];
}
else {
const uniqueIndex = Object.keys(uniqueElements).length;
uniqueElements[element] = uniqueIndex;
indices[i] = uniqueIndex;
uniqueIndices.push(i);
}
}
// Now we know where each of the unique elements are located along the axis
// (uniqueIndices). Extract them from input buffer and store them in the
// output buffer.
const outputTmpShape = newShape.slice();
outputTmpShape[1] = Object.keys(uniqueElements).length;
const outputBuffer = new _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["TensorBuffer"](outputTmpShape, dtype);
uniqueIndices.forEach((uniqueElementIndex, i) => {
for (let m = 0; m < newShape[0]; m++) {
for (let n = 0; n < newShape[2]; n++) {
outputBuffer.set(inputBuffer.get(m, uniqueElementIndex, n), m, i, n);
}
}
});
// The output shape can be calculated from the input shape with the size of
// the given axis replaced by the number of unique elements along that axis.
const outputShape = shape.slice();
outputShape[$axis] = outputTmpShape[1];
return {
outputValues: outputBuffer.values,
outputShape,
indices,
};
}
//# sourceMappingURL=Unique_impl.js.map
/***/ }),
/* 208 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "GraphModel", function() { return /* reexport */ graph_model_GraphModel; });
__webpack_require__.d(__webpack_exports__, "loadGraphModel", function() { return /* reexport */ loadGraphModel; });
__webpack_require__.d(__webpack_exports__, "deregisterOp", function() { return /* reexport */ register["a" /* deregisterOp */]; });
__webpack_require__.d(__webpack_exports__, "registerOp", function() { return /* reexport */ register["c" /* registerOp */]; });
__webpack_require__.d(__webpack_exports__, "version_converter", function() { return /* reexport */ version; });
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/index.js + 41 modules
var dist = __webpack_require__(0);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/operation_mapper.js
var operation_mapper = __webpack_require__(57);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/utils.js
var utils = __webpack_require__(1);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/custom_op/node_value_impl.js
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Helper class for lookup inputs and params for nodes in the model graph.
*/
class node_value_impl_NodeValueImpl {
constructor(node, tensorMap, context) {
this.node = node;
this.tensorMap = tensorMap;
this.context = context;
this.inputs = [];
this.attrs = {};
this.inputs = node.inputNames.map(name => this.getInput(name));
if (node.rawAttrs != null) {
this.attrs = Object.keys(node.rawAttrs)
.reduce((attrs, key) => {
attrs[key] = this.getAttr(key);
return attrs;
}, {});
}
}
/**
* Return the value of the attribute or input param.
* @param name String: name of attribute or input param.
*/
getInput(name) {
return Object(utils["e" /* getTensor */])(name, this.tensorMap, this.context);
}
/**
* Return the value of the attribute or input param.
* @param name String: name of attribute or input param.
*/
getAttr(name, defaultValue) {
const value = this.node.rawAttrs[name];
if (value.tensor != null) {
return Object(utils["e" /* getTensor */])(name, this.tensorMap, this.context);
}
if (value.i != null || value.f != null) {
return Object(operation_mapper["f" /* getNumberParam */])(this.node.rawAttrs, name, defaultValue);
}
if (value.s != null) {
return Object(operation_mapper["i" /* getStringParam */])(this.node.rawAttrs, name, defaultValue);
}
if (value.b != null) {
return Object(operation_mapper["c" /* getBoolParam */])(this.node.rawAttrs, name, defaultValue);
}
if (value.shape != null) {
return Object(operation_mapper["k" /* getTensorShapeParam */])(this.node.rawAttrs, name, defaultValue);
}
if (value.type != null) {
return Object(operation_mapper["e" /* getDtypeParam */])(this.node.rawAttrs, name, defaultValue);
}
if (value.list != null) {
if (value.list.i != null || value.list.f != null) {
return Object(operation_mapper["g" /* getNumericArrayParam */])(this.node.rawAttrs, name, defaultValue);
}
if (value.list.s != null) {
return Object(operation_mapper["h" /* getStringArrayParam */])(this.node.rawAttrs, name, defaultValue);
}
if (value.list.shape != null) {
return Object(operation_mapper["j" /* getTensorShapeArrayParam */])(this.node.rawAttrs, name, defaultValue);
}
if (value.list.b != null) {
return Object(operation_mapper["b" /* getBoolArrayParam */])(this.node.rawAttrs, name, defaultValue);
}
if (value.list.type != null) {
return Object(operation_mapper["d" /* getDtypeArrayParam */])(this.node.rawAttrs, name, defaultValue);
}
}
return defaultValue;
}
}
//# sourceMappingURL=node_value_impl.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/custom_op/register.js
var register = __webpack_require__(104);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/add.js
var add = __webpack_require__(13);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/add_n.js
var add_n = __webpack_require__(218);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/mod.js
var mod = __webpack_require__(168);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/mul.js
var mul = __webpack_require__(9);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/div.js
var div = __webpack_require__(15);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/div_no_nan.js
var div_no_nan = __webpack_require__(161);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/floorDiv.js
var floorDiv = __webpack_require__(114);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/sub.js
var sub = __webpack_require__(14);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/minimum.js
var minimum = __webpack_require__(127);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/maximum.js
var maximum = __webpack_require__(90);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/pow.js
var pow = __webpack_require__(53);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/squared_difference.js
var squared_difference = __webpack_require__(133);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/arithmetic_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
const executeOp = (node, tensorMap, context) => {
switch (node.op) {
case 'BiasAdd':
case 'AddV2':
case 'Add': {
return [add["a" /* add */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
case 'AddN': {
return [add_n["a" /* addN */](Object(utils["d" /* getParamValue */])('tensors', node, tensorMap, context))];
}
case 'FloorMod':
case 'Mod':
return [mod["a" /* mod */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
case 'Mul':
return [mul["a" /* mul */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
case 'RealDiv':
case 'Div': {
return [div["a" /* div */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
case 'DivNoNan': {
return [div_no_nan["a" /* divNoNan */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
case 'FloorDiv': {
return [floorDiv["a" /* floorDiv */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
case 'Sub': {
return [sub["a" /* sub */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
case 'Minimum': {
return [minimum["a" /* minimum */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
case 'Maximum': {
return [maximum["a" /* maximum */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
case 'Pow': {
return [pow["a" /* pow */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
case 'SquaredDifference': {
return [squared_difference["a" /* squaredDifference */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const CATEGORY = 'arithmetic';
//# sourceMappingURL=arithmetic_executor.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/abs.js
var abs = __webpack_require__(43);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/acos.js
var acos = __webpack_require__(216);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/acosh.js
var acosh = __webpack_require__(217);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/asin.js
var asin = __webpack_require__(219);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/asinh.js
var asinh = __webpack_require__(220);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/atan.js
var atan = __webpack_require__(221);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/atan2.js
var atan2 = __webpack_require__(155);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/atanh.js
var atanh = __webpack_require__(222);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/ceil.js
var ceil = __webpack_require__(225);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/complex.js
var complex = __webpack_require__(58);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/cos.js
var cos = __webpack_require__(117);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/cosh.js
var cosh = __webpack_require__(158);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/elu.js
var elu = __webpack_require__(119);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/erf.js
var erf = __webpack_require__(230);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/exp.js
var exp = __webpack_require__(41);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/expm1.js
var expm1 = __webpack_require__(231);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/floor.js
var floor = __webpack_require__(120);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/log.js
var log = __webpack_require__(75);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/log1p.js
var log1p = __webpack_require__(164);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/imag.js
var imag = __webpack_require__(121);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/neg.js
var neg = __webpack_require__(30);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/reciprocal.js
var reciprocal = __webpack_require__(242);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/real.js
var real = __webpack_require__(107);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/relu.js
var relu = __webpack_require__(81);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/round.js
var round = __webpack_require__(243);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/selu.js
var selu = __webpack_require__(173);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/sigmoid.js
var sigmoid = __webpack_require__(71);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/sin.js
var sin = __webpack_require__(175);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/sign.js
var sign = __webpack_require__(245);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/sinh.js
var sinh = __webpack_require__(176);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/softplus.js
var softplus = __webpack_require__(165);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/sqrt.js
var sqrt = __webpack_require__(37);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/square.js
var square = __webpack_require__(25);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/tanh.js
var tanh = __webpack_require__(145);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/tan.js
var tan = __webpack_require__(248);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/clip_by_value.js
var clip_by_value = __webpack_require__(226);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/relu6.js
var relu6 = __webpack_require__(130);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/rsqrt.js
var rsqrt = __webpack_require__(172);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/prod.js
var prod = __webpack_require__(170);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/leaky_relu.js
var leaky_relu = __webpack_require__(122);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/prelu.js
var prelu = __webpack_require__(129);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/is_nan.js
var is_nan = __webpack_require__(234);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/basic_math_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
const basic_math_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case 'Abs':
case 'ComplexAbs':
return [abs["a" /* abs */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Acos':
return [acos["a" /* acos */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Acosh':
return [acosh["a" /* acosh */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Asin':
return [asin["a" /* asin */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Asinh':
return [asinh["a" /* asinh */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Atan':
return [atan["a" /* atan */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Atan2':
return [atan2["a" /* atan2 */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('y', node, tensorMap, context))];
case 'Atanh':
return [atanh["a" /* atanh */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Ceil':
return [ceil["a" /* ceil */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Complex':
return [complex["a" /* complex */](Object(utils["d" /* getParamValue */])('real', node, tensorMap, context), Object(utils["d" /* getParamValue */])('imag', node, tensorMap, context))];
case 'Cos':
return [cos["a" /* cos */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Cosh':
return [cosh["a" /* cosh */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Elu':
return [elu["a" /* elu */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Erf':
return [erf["a" /* erf */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Exp':
return [exp["a" /* exp */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Expm1': {
return [expm1["a" /* expm1 */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
case 'Floor':
return [floor["a" /* floor */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Log':
return [log["a" /* log */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Log1p': {
return [log1p["a" /* log1p */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
case 'Imag':
return [imag["a" /* imag */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Neg':
return [neg["a" /* neg */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Reciprocal': {
return [reciprocal["a" /* reciprocal */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
case 'Real':
return [real["a" /* real */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Relu':
return [relu["a" /* relu */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Round': {
return [round["a" /* round */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
case 'Selu':
return [selu["a" /* selu */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Sigmoid':
return [sigmoid["a" /* sigmoid */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Sin':
return [sin["a" /* sin */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Sign': {
return [sign["a" /* sign */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
case 'Sinh': {
return [sinh["a" /* sinh */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
case 'Softplus': {
return [softplus["a" /* softplus */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
case 'Sqrt': {
return [sqrt["a" /* sqrt */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
case 'Square': {
return [square["a" /* square */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
case 'Tanh': {
return [tanh["a" /* tanh */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
case 'Tan':
return [tan["a" /* tan */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'ClipByValue':
return [clip_by_value["a" /* clipByValue */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('clipValueMin', node, tensorMap, context), Object(utils["d" /* getParamValue */])('clipValueMax', node, tensorMap, context))];
case 'Relu6':
return [relu6["a" /* relu6 */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
case 'Rsqrt':
return [rsqrt["a" /* rsqrt */](Object(utils["e" /* getTensor */])(node.inputNames[0], tensorMap, context))];
case 'Prod':
return [prod["a" /* prod */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('axes', node, tensorMap, context))];
case 'LeakyRelu':
return [leaky_relu["a" /* leakyRelu */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('alpha', node, tensorMap, context))];
case 'Prelu':
return [prelu["a" /* prelu */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('alpha', node, tensorMap, context))];
case 'IsNan':
return [is_nan["a" /* isNaN */](Object(utils["e" /* getTensor */])(node.inputNames[0], tensorMap, context))];
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const basic_math_executor_CATEGORY = 'basic_math';
//# sourceMappingURL=basic_math_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/executor/tensor_utils.js
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* This differs from util.assertShapesMatch in that it allows values of
* negative one, an undefined size of a dimensinon, in a shape to match
* anything.
*/
/**
* Used by TensorList and TensorArray to verify if elementShape matches, support
* negative value as the dim shape.
* @param shapeA
* @param shapeB
* @param errorMessagePrefix
*/
function assertShapesMatchAllowUndefinedSize(shapeA, shapeB, errorMessagePrefix = '') {
// constant shape means unknown rank
if (typeof shapeA === 'number' || typeof shapeB === 'number') {
return;
}
dist["util"].assert(shapeA.length === shapeB.length, () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);
for (let i = 0; i < shapeA.length; i++) {
const dim0 = shapeA[i];
const dim1 = shapeB[i];
dist["util"].assert(dim0 < 0 || dim1 < 0 || dim0 === dim1, () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);
}
}
function fullDefinedShape(elementShape) {
if (typeof elementShape === 'number' || elementShape.some(dim => dim < 0)) {
return false;
}
return true;
}
/**
* Generate the output element shape from the list elementShape, list tensors
* and input param.
* @param listElementShape
* @param tensors
* @param elementShape
*/
function inferElementShape(listElementShape, tensors, elementShape) {
let partialShape = mergeElementShape(listElementShape, elementShape);
const notfullDefinedShape = !fullDefinedShape(partialShape);
if (notfullDefinedShape && tensors.length === 0) {
throw new Error(`Tried to calculate elements of an empty list` +
` with non-fully-defined elementShape: ${partialShape}`);
}
if (notfullDefinedShape) {
tensors.forEach(tensor => {
partialShape = mergeElementShape(tensor.shape, partialShape);
});
}
if (!fullDefinedShape(partialShape)) {
throw new Error(`Non-fully-defined elementShape: ${partialShape}`);
}
return partialShape;
}
function mergeElementShape(elementShapeA, elementShapeB) {
if (typeof elementShapeA === 'number') {
return elementShapeB;
}
if (typeof elementShapeB === 'number') {
return elementShapeA;
}
if (elementShapeA.length !== elementShapeB.length) {
throw new Error(`Incompatible ranks during merge: ${elementShapeA} vs. ${elementShapeB}`);
}
const result = [];
for (let i = 0; i < elementShapeA.length; ++i) {
const dim0 = elementShapeA[i];
const dim1 = elementShapeB[i];
if (dim0 >= 0 && dim1 >= 0 && dim0 !== dim1) {
throw new Error(`Incompatible shape during merge: ${elementShapeA} vs. ${elementShapeB}`);
}
result[i] = dim0 >= 0 ? dim0 : dim1;
}
return result;
}
//# sourceMappingURL=tensor_utils.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/executor/tensor_array.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* The TensorArray object keeps an array of Tensors. It
* allows reading from the array and writing to the array.
*/
class tensor_array_TensorArray {
constructor(name, dtype, maxSize, elementShape, identicalElementShapes, dynamicSize, clearAfterRead) {
this.name = name;
this.dtype = dtype;
this.maxSize = maxSize;
this.elementShape = elementShape;
this.identicalElementShapes = identicalElementShapes;
this.dynamicSize = dynamicSize;
this.clearAfterRead = clearAfterRead;
this.tensors = [];
this.closed_ = false;
this.idTensor = Object(dist["scalar"])(0);
Object(dist["keep"])(this.idTensor);
}
get id() {
return this.idTensor.id;
}
get closed() {
return this.closed_;
}
/**
* Dispose the tensors and idTensor and mark the TensoryArray as closed.
*/
clearAndClose(keepIds) {
this.tensors.forEach(tensor => {
if (keepIds == null || !keepIds.has(tensor.tensor.id)) {
tensor.tensor.dispose();
}
});
this.tensors = [];
this.closed_ = true;
this.idTensor.dispose();
}
size() {
return this.tensors.length;
}
/**
* Read the value at location index in the TensorArray.
* @param index Number the index to read from.
*/
read(index) {
if (this.closed_) {
throw new Error(`TensorArray ${this.name} has already been closed.`);
}
if (index < 0 || index >= this.size()) {
throw new Error(`Tried to read from index ${index}, but array size is: ${this.size()}`);
}
const tensorWithState = this.tensors[index];
if (tensorWithState.cleared) {
throw new Error(`TensorArray ${this.name}: Could not read index ${index} twice because it was cleared after a previous read ` +
`(perhaps try setting clear_after_read = false?).`);
}
if (this.clearAfterRead) {
tensorWithState.cleared = true;
}
tensorWithState.read = true;
return tensorWithState.tensor;
}
/**
* Helper method to read multiple tensors from the specified indices.
*/
readMany(indices) {
return indices.map(index => this.read(index));
}
/**
* Write value into the index of the TensorArray.
* @param index number the index to write to.
* @param tensor
*/
write(index, tensor) {
if (this.closed_) {
throw new Error(`TensorArray ${this.name} has already been closed.`);
}
if (index < 0 || !this.dynamicSize && index >= this.maxSize) {
throw new Error(`Tried to write to index ${index}, but array is not resizeable and size is: ${this.maxSize}`);
}
const t = this.tensors[index] || {};
if (tensor.dtype !== this.dtype) {
throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${index},
because the value dtype is ${tensor.dtype}, but TensorArray dtype is ${this.dtype}.`);
}
// Set the shape for the first time write to unknow shape tensor array
if (this.size() === 0 &&
(this.elementShape == null || this.elementShape.length === 0)) {
this.elementShape = tensor.shape;
}
assertShapesMatchAllowUndefinedSize(this.elementShape, tensor.shape, `TensorArray ${this.name}: Could not write to TensorArray index ${index}.`);
if (t.read) {
throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${index}, because it has already been read.`);
}
if (t.written) {
throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${index}, because it has already been written.`);
}
t.tensor = tensor;
Object(dist["keep"])(tensor);
t.written = true;
this.tensors[index] = t;
}
/**
* Helper method to write multiple tensors to the specified indices.
*/
writeMany(indices, tensors) {
if (indices.length !== tensors.length) {
throw new Error(`TensorArray ${this.name}: could not write multiple tensors,` +
`because the index size: ${indices.length} is not the same as tensors size: ${tensors.length}.`);
}
indices.forEach((i, index) => this.write(i, tensors[index]));
}
/**
* Return selected values in the TensorArray as a packed Tensor. All of
* selected values must have been written and their shapes must all match.
* @param [indices] number[] Optional. Taking values in [0, max_value). If the
* TensorArray is not dynamic, max_value=size(). If not specified returns
* all tensors in the original order.
* @param [dtype]
*/
gather(indices, dtype) {
if (!!dtype && dtype !== this.dtype) {
throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${dtype}`);
}
if (!indices) {
indices = [];
for (let i = 0; i < this.size(); i++) {
indices.push(i);
}
}
else {
indices = indices.slice(0, this.size());
}
if (indices.length === 0) {
return Object(dist["tensor"])([], [0].concat(this.elementShape));
}
// Read all the PersistentTensors into a vector to keep track of
// their memory.
const tensors = this.readMany(indices);
assertShapesMatchAllowUndefinedSize(this.elementShape, tensors[0].shape, 'TensorArray shape mismatch: ');
return Object(dist["stack"])(tensors, 0);
}
/**
* Return the values in the TensorArray as a concatenated Tensor.
*/
concat(dtype) {
if (!!dtype && dtype !== this.dtype) {
throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${dtype}`);
}
if (this.size() === 0) {
return Object(dist["tensor"])([], [0].concat(this.elementShape));
}
const indices = [];
for (let i = 0; i < this.size(); i++) {
indices.push(i);
}
// Collect all the tensors from the tensors array.
const tensors = this.readMany(indices);
assertShapesMatchAllowUndefinedSize(this.elementShape, tensors[0].shape, `TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${tensors[0].shape})`);
return Object(dist["concat"])(tensors, 0);
}
/**
* Scatter the values of a Tensor in specific indices of a TensorArray.
* @param indices nummber[] values in [0, max_value). If the
* TensorArray is not dynamic, max_value=size().
* @param tensor Tensor input tensor.
*/
scatter(indices, tensor) {
if (tensor.dtype !== this.dtype) {
throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${tensor.dtype}`);
}
if (indices.length !== tensor.shape[0]) {
throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${indices.length} vs. ${tensor.shape[0]}`);
}
const maxIndex = Math.max(...indices);
if (!this.dynamicSize && maxIndex >= this.maxSize) {
throw new Error(`Max index must be < array size (${maxIndex} vs. ${this.maxSize})`);
}
this.writeMany(indices, Object(dist["unstack"])(tensor, 0));
}
/**
* Split the values of a Tensor into the TensorArray.
* @param length number[] with the lengths to use when splitting value along
* its first dimension.
* @param tensor Tensor, the tensor to split.
*/
split(length, tensor) {
if (tensor.dtype !== this.dtype) {
throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${tensor.dtype}`);
}
let totalLength = 0;
const cumulativeLengths = length.map(len => {
totalLength += len;
return totalLength;
});
if (totalLength !== tensor.shape[0]) {
throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${totalLength}, and tensor's shape is: ${tensor.shape}`);
}
if (!this.dynamicSize && length.length !== this.maxSize) {
throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${length.length}), ` +
'and the TensorArray is not marked as dynamically resizeable');
}
const elementPerRow = totalLength === 0 ? 0 : tensor.size / totalLength;
const tensors = [];
Object(dist["tidy"])(() => {
tensor = Object(dist["reshape"])(tensor, [1, totalLength, elementPerRow]);
for (let i = 0; i < length.length; ++i) {
const previousLength = (i === 0) ? 0 : cumulativeLengths[i - 1];
const indices = [0, previousLength, 0];
const sizes = [1, length[i], elementPerRow];
tensors[i] = Object(dist["reshape"])(Object(dist["slice"])(tensor, indices, sizes), this.elementShape);
}
return tensors;
});
const indices = [];
for (let i = 0; i < length.length; i++) {
indices[i] = i;
}
this.writeMany(indices, tensors);
}
}
//# sourceMappingURL=tensor_array.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/executor/tensor_list.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.
* =============================================================================
*/
/**
* TensorList stores a container of `tf.Tensor` objects, which are accessible
* via tensors field.
*
* In order to get a copy of the underlying list, use the copy method:
* ```
* TensorList b = a.copy();
* b.tensors().pushBack(t); // This does not modify a.tensors().
* ```
*
* Note that this is not a deep copy: the memory locations of the underlying
* tensors will still point to the same locations of the corresponding tensors
* in the original.
*/
class tensor_list_TensorList {
/**
*
* @param tensors list of tensors
* @param elementShape shape of each tensor, this can be a single number (any
* shape is allowed) or partial shape (dim = -1).
* @param elementDtype data type of each tensor
* @param maxNumElements The maximum allowed size of `tensors`. Defaults to -1
* meaning that the size of `tensors` is unbounded.
*/
constructor(tensors, elementShape, elementDtype, maxNumElements = -1) {
this.tensors = tensors;
this.elementShape = elementShape;
this.elementDtype = elementDtype;
if (tensors != null) {
tensors.forEach(tensor => {
if (elementDtype !== tensor.dtype) {
throw new Error(`Invalid data types; op elements ${elementDtype}, but list elements ${tensor.dtype}`);
}
assertShapesMatchAllowUndefinedSize(elementShape, tensor.shape, 'TensorList shape mismatch: ');
Object(dist["keep"])(tensor);
});
}
this.idTensor = Object(dist["scalar"])(0);
this.maxNumElements = maxNumElements;
Object(dist["keep"])(this.idTensor);
}
get id() {
return this.idTensor.id;
}
/**
* Get a new TensorList containing a copy of the underlying tensor container.
*/
copy() {
return new tensor_list_TensorList([...this.tensors], this.elementShape, this.elementDtype);
}
/**
* Dispose the tensors and idTensor and clear the tensor list.
*/
clearAndClose(keepIds) {
this.tensors.forEach(tensor => {
if (keepIds == null || !keepIds.has(tensor.id)) {
tensor.dispose();
}
});
this.tensors.length = 0;
this.idTensor.dispose();
}
/**
* The size of the tensors in the tensor list.
*/
size() {
return this.tensors.length;
}
/**
* Return a tensor that stacks a list of rank-R tf.Tensors into one rank-(R+1)
* tf.Tensor.
* @param elementShape shape of each tensor
* @param elementDtype data type of each tensor
* @param numElements the number of elements to stack
*/
stack(elementShape, elementDtype, numElements = -1) {
if (elementDtype !== this.elementDtype) {
throw new Error(`Invalid data types; op elements ${elementDtype}, but list elements ${this.elementDtype}`);
}
if (numElements !== -1 && this.tensors.length !== numElements) {
throw new Error(`Operation expected a list with ${numElements} elements but got a list with ${this.tensors.length} elements.`);
}
assertShapesMatchAllowUndefinedSize(elementShape, this.elementShape, 'TensorList shape mismatch: ');
const outputElementShape = inferElementShape(this.elementShape, this.tensors, elementShape);
return Object(dist["tidy"])(() => {
const reshapedTensors = this.tensors.map(tensor => Object(dist["reshape"])(tensor, outputElementShape));
return Object(dist["stack"])(reshapedTensors, 0);
});
}
/**
* Pop a tensor from the end of the list.
* @param elementShape shape of the tensor
* @param elementDtype data type of the tensor
*/
popBack(elementShape, elementDtype) {
if (elementDtype !== this.elementDtype) {
throw new Error(`Invalid data types; op elements ${elementDtype}, but list elements ${this.elementDtype}`);
}
if (this.size() === 0) {
throw new Error('Trying to pop from an empty list.');
}
const outputElementShape = inferElementShape(this.elementShape, this.tensors, elementShape);
const tensor = this.tensors.pop();
assertShapesMatchAllowUndefinedSize(tensor.shape, elementShape, 'TensorList shape mismatch: ');
return Object(dist["reshape"])(tensor, outputElementShape);
}
/**
* Push a tensor to the end of the list.
* @param tensor Tensor to be pushed.
*/
pushBack(tensor) {
if (tensor.dtype !== this.elementDtype) {
throw new Error(`Invalid data types; op elements ${tensor.dtype}, but list elements ${this.elementDtype}`);
}
assertShapesMatchAllowUndefinedSize(tensor.shape, this.elementShape, 'TensorList shape mismatch: ');
if (this.maxNumElements === this.size()) {
throw new Error(`Trying to push element into a full list.`);
}
Object(dist["keep"])(tensor);
this.tensors.push(tensor);
}
/**
* Update the size of the list.
* @param size the new size of the list.
*/
resize(size) {
if (size < 0) {
throw new Error(`TensorListResize expects size to be non-negative. Got: ${size}`);
}
if (this.maxNumElements !== -1 && size > this.maxNumElements) {
throw new Error(`TensorListResize input size ${size} is greater maxNumElement ${this.maxNumElements}.`);
}
this.tensors.length = size;
}
/**
* Retrieve the element at the provided index
* @param elementShape shape of the tensor
* @param elementDtype dtype of the tensor
* @param elementIndex index of the tensor
*/
getItem(elementIndex, elementShape, elementDtype) {
if (elementDtype !== this.elementDtype) {
throw new Error(`Invalid data types; op elements ${elementDtype}, but list elements ${this.elementDtype}`);
}
if (elementIndex < 0 || elementIndex > this.tensors.length) {
throw new Error(`Trying to access element ${elementIndex} in a list with ${this.tensors.length} elements.`);
}
if (this.tensors[elementIndex] == null) {
throw new Error(`element at index ${elementIndex} is null.`);
}
assertShapesMatchAllowUndefinedSize(this.tensors[elementIndex].shape, elementShape, 'TensorList shape mismatch: ');
const outputElementShape = inferElementShape(this.elementShape, this.tensors, elementShape);
return Object(dist["reshape"])(this.tensors[elementIndex], outputElementShape);
}
/**
* Set the tensor at the index
* @param elementIndex index of the tensor
* @param tensor the tensor to be inserted into the list
*/
setItem(elementIndex, tensor) {
if (tensor.dtype !== this.elementDtype) {
throw new Error(`Invalid data types; op elements ${tensor.dtype}, but list elements ${this.elementDtype}`);
}
if (elementIndex < 0 ||
this.maxNumElements !== -1 && elementIndex >= this.maxNumElements) {
throw new Error(`Trying to set element ${elementIndex} in a list with max ${this.maxNumElements} elements.`);
}
assertShapesMatchAllowUndefinedSize(this.elementShape, tensor.shape, 'TensorList shape mismatch: ');
Object(dist["keep"])(tensor);
this.tensors[elementIndex] = tensor;
}
/**
* Return selected values in the TensorList as a stacked Tensor. All of
* selected values must have been written and their shapes must all match.
* @param indices indices of tensors to gather
* @param elementDtype output tensor dtype
* @param elementShape output tensor element shape
*/
gather(indices, elementDtype, elementShape) {
if (elementDtype !== this.elementDtype) {
throw new Error(`Invalid data types; op elements ${elementDtype}, but list elements ${this.elementDtype}`);
}
assertShapesMatchAllowUndefinedSize(this.elementShape, elementShape, 'TensorList shape mismatch: ');
// When indices is greater than the size of the list, indices beyond the
// size of the list are ignored.
indices = indices.slice(0, this.size());
const outputElementShape = inferElementShape(this.elementShape, this.tensors, elementShape);
if (indices.length === 0) {
return Object(dist["tensor"])([], [0].concat(outputElementShape));
}
return Object(dist["tidy"])(() => {
const tensors = indices.map(i => Object(dist["reshape"])(this.tensors[i], outputElementShape));
return Object(dist["stack"])(tensors, 0);
});
}
/**
* Return the values in the TensorList as a concatenated Tensor.
* @param elementDtype output tensor dtype
* @param elementShape output tensor element shape
*/
concat(elementDtype, elementShape) {
if (!!elementDtype && elementDtype !== this.elementDtype) {
throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${elementDtype}`);
}
assertShapesMatchAllowUndefinedSize(this.elementShape, elementShape, 'TensorList shape mismatch: ');
const outputElementShape = inferElementShape(this.elementShape, this.tensors, elementShape);
if (this.size() === 0) {
return Object(dist["tensor"])([], [0].concat(outputElementShape));
}
return Object(dist["tidy"])(() => {
const tensors = this.tensors.map(t => Object(dist["reshape"])(t, outputElementShape));
return Object(dist["concat"])(tensors, 0);
});
}
}
/**
* Creates a TensorList which, when stacked, has the value of tensor.
* @param tensor from tensor
* @param elementShape output tensor element shape
*/
function fromTensor(tensor, elementShape, elementDtype) {
const dtype = tensor.dtype;
if (tensor.shape.length < 1) {
throw new Error(`Tensor must be at least a vector, but saw shape: ${tensor.shape}`);
}
if (tensor.dtype !== elementDtype) {
throw new Error(`Invalid data types; op elements ${tensor.dtype}, but list elements ${elementDtype}`);
}
const tensorElementShape = tensor.shape.slice(1);
assertShapesMatchAllowUndefinedSize(tensorElementShape, elementShape, 'TensorList shape mismatch: ');
const tensorList = Object(dist["unstack"])(tensor);
return new tensor_list_TensorList(tensorList, elementShape, dtype);
}
/**
* Return a TensorList of the given size with empty elements.
* @param elementShape the shape of the future elements of the list
* @param elementDtype the desired type of elements in the list
* @param numElements the number of elements to reserve
*/
function reserve(elementShape, elementDtype, numElements) {
return new tensor_list_TensorList([], elementShape, elementDtype, numElements);
}
/**
* Put tensors at specific indices of a stacked tensor into a TensorList.
* @param indices list of indices on how to scatter the tensor.
* @param tensor input tensor.
* @param elementShape the shape of the future elements of the list
* @param numElements the number of elements to scatter
*/
function scatter(tensor, indices, elementShape, numElements) {
if (indices.length !== tensor.shape[0]) {
throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${indices.length} vs. ${tensor.shape[0]}`);
}
const maxIndex = Math.max(...indices);
if (numElements != null && numElements !== -1 && maxIndex >= numElements) {
throw new Error(`Max index must be < array size (${maxIndex} vs. ${numElements})`);
}
const list = new tensor_list_TensorList([], elementShape, tensor.dtype, numElements);
const tensors = Object(dist["unstack"])(tensor, 0);
indices.forEach((value, index) => {
list.setItem(value, tensors[index]);
});
return list;
}
/**
* Split the values of a Tensor into a TensorList.
* @param length the lengths to use when splitting value along
* its first dimension.
* @param tensor the tensor to split.
* @param elementShape the shape of the future elements of the list
*/
function split(tensor, length, elementShape) {
let totalLength = 0;
const cumulativeLengths = length.map(len => {
totalLength += len;
return totalLength;
});
if (totalLength !== tensor.shape[0]) {
throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${totalLength}, and tensor's shape is: ${tensor.shape}`);
}
const shapeWithoutFirstDim = tensor.shape.slice(1);
const outputElementShape = mergeElementShape(shapeWithoutFirstDim, elementShape);
const elementPerRow = totalLength === 0 ? 0 : tensor.size / totalLength;
const tensors = Object(dist["tidy"])(() => {
const tensors = [];
tensor = Object(dist["reshape"])(tensor, [1, totalLength, elementPerRow]);
for (let i = 0; i < length.length; ++i) {
const previousLength = (i === 0) ? 0 : cumulativeLengths[i - 1];
const indices = [0, previousLength, 0];
const sizes = [1, length[i], elementPerRow];
tensors[i] = Object(dist["reshape"])(Object(dist["slice"])(tensor, indices, sizes), outputElementShape);
}
tensor.dispose();
return tensors;
});
const list = new tensor_list_TensorList([], elementShape, tensor.dtype, length.length);
for (let i = 0; i < tensors.length; i++) {
list.setItem(i, tensors[i]);
}
return list;
}
//# sourceMappingURL=tensor_list.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/control_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const control_executor_executeOp = async (node, tensorMap, context) => {
switch (node.op) {
case 'If':
case 'StatelessIf': {
const thenFunc = Object(utils["d" /* getParamValue */])('thenBranch', node, tensorMap, context);
const elseFunc = Object(utils["d" /* getParamValue */])('elseBranch', node, tensorMap, context);
const cond = Object(utils["d" /* getParamValue */])('cond', node, tensorMap, context);
const args = Object(utils["d" /* getParamValue */])('args', node, tensorMap, context);
const condValue = await cond.data();
if (condValue[0]) {
return context.functionMap[thenFunc].executeFunctionAsync(args, context.tensorArrayMap, context.tensorListMap);
}
else {
return context.functionMap[elseFunc].executeFunctionAsync(args, context.tensorArrayMap, context.tensorListMap);
}
}
case 'While':
case 'StatelessWhile': {
const bodyFunc = Object(utils["d" /* getParamValue */])('body', node, tensorMap, context);
const condFunc = Object(utils["d" /* getParamValue */])('cond', node, tensorMap, context);
const args = Object(utils["d" /* getParamValue */])('args', node, tensorMap, context);
// Calculate the condition of the loop
const condResult = (await context.functionMap[condFunc].executeFunctionAsync(args, context.tensorArrayMap, context.tensorListMap));
const argIds = args.map(tensor => tensor.id);
let condValue = await condResult[0].data();
// Dispose the intermediate tensors for condition function
condResult.forEach(tensor => {
if (!tensor.kept && argIds.indexOf(tensor.id) === -1) {
tensor.dispose();
}
});
let result = args;
while (condValue[0]) {
// Record the previous result for intermediate tensor tracking
const origResult = result;
// Execution the body of the loop
result = await context.functionMap[bodyFunc].executeFunctionAsync(result, context.tensorArrayMap, context.tensorListMap);
const resultIds = result.map(tensor => tensor.id);
// Dispose the intermediate tensor for body function that is not global
// kept, not input/output of the body function
origResult.forEach(tensor => {
if (!tensor.kept && argIds.indexOf(tensor.id) === -1 &&
resultIds.indexOf(tensor.id) === -1) {
tensor.dispose();
}
});
// Recalcuate the condition of the loop using the latest results.
const condResult = (await context.functionMap[condFunc].executeFunctionAsync(result, context.tensorArrayMap, context.tensorListMap));
condValue = await condResult[0].data();
// Dispose the intermediate tensors for condition function
condResult.forEach(tensor => {
if (!tensor.kept && argIds.indexOf(tensor.id) === -1 &&
resultIds.indexOf(tensor.id) === -1) {
tensor.dispose();
}
});
}
return result;
}
case 'LoopCond': {
const pred = Object(utils["d" /* getParamValue */])('pred', node, tensorMap, context);
return [Object(utils["a" /* cloneTensor */])(pred)];
}
case 'Switch': {
const pred = Object(utils["d" /* getParamValue */])('pred', node, tensorMap, context);
let data = Object(utils["d" /* getParamValue */])('data', node, tensorMap, context);
if (!data.kept) {
data = Object(utils["a" /* cloneTensor */])(data);
}
// Outputs nodes :0 => false, :1 => true
return (await pred.data())[0] ? [undefined, data] : [data, undefined];
}
case 'Merge': {
const inputName = node.inputNames.find(name => Object(utils["e" /* getTensor */])(name, tensorMap, context) !== undefined);
if (inputName) {
const data = Object(utils["e" /* getTensor */])(inputName, tensorMap, context);
return [Object(utils["a" /* cloneTensor */])(data)];
}
return undefined;
}
case 'Enter': {
const frameId = Object(utils["d" /* getParamValue */])('frameName', node, tensorMap, context);
const data = Object(utils["d" /* getParamValue */])('tensor', node, tensorMap, context);
context.enterFrame(frameId);
return [Object(utils["a" /* cloneTensor */])(data)];
}
case 'Exit': {
const data = Object(utils["d" /* getParamValue */])('tensor', node, tensorMap, context);
context.exitFrame();
return [Object(utils["a" /* cloneTensor */])(data)];
}
case 'NextIteration': {
const data = Object(utils["d" /* getParamValue */])('tensor', node, tensorMap, context);
context.nextIteration();
return [Object(utils["a" /* cloneTensor */])(data)];
}
case 'TensorArrayV3': {
const size = Object(utils["d" /* getParamValue */])('size', node, tensorMap, context);
const dtype = Object(utils["d" /* getParamValue */])('dtype', node, tensorMap, context);
const elementShape = Object(utils["d" /* getParamValue */])('elementShape', node, tensorMap, context);
const dynamicSize = Object(utils["d" /* getParamValue */])('dynamicSize', node, tensorMap, context);
const clearAfterRead = Object(utils["d" /* getParamValue */])('clearAfterRead', node, tensorMap, context);
const identicalElementShapes = Object(utils["d" /* getParamValue */])('identicalElementShapes', node, tensorMap, context);
const name = Object(utils["d" /* getParamValue */])('name', node, tensorMap, context);
const tensorArray = new tensor_array_TensorArray(name, dtype, size, elementShape, identicalElementShapes, dynamicSize, clearAfterRead);
context.addTensorArray(tensorArray);
return [tensorArray.idTensor, Object(dist["scalar"])(1.0)];
}
case 'TensorArrayWriteV3': {
const id = Object(utils["d" /* getParamValue */])('tensorArrayId', node, tensorMap, context);
const index = Object(utils["d" /* getParamValue */])('index', node, tensorMap, context);
const writeTensor = Object(utils["d" /* getParamValue */])('tensor', node, tensorMap, context);
const writeTensorArray = context.getTensorArray(id.id);
writeTensorArray.write(index, writeTensor);
return [writeTensorArray.idTensor];
}
case 'TensorArrayReadV3': {
const readId = Object(utils["d" /* getParamValue */])('tensorArrayId', node, tensorMap, context);
const readIndex = Object(utils["d" /* getParamValue */])('index', node, tensorMap, context);
const readTensorArray = context.getTensorArray(readId.id);
return [readTensorArray.read(readIndex)];
}
case 'TensorArrayGatherV3': {
const gatherId = Object(utils["d" /* getParamValue */])('tensorArrayId', node, tensorMap, context);
const gatherIndices = Object(utils["d" /* getParamValue */])('indices', node, tensorMap, context);
const gatherDtype = Object(utils["d" /* getParamValue */])('dtype', node, tensorMap, context);
const gatherTensorArray = context.getTensorArray(gatherId.id);
return [gatherTensorArray.gather(gatherIndices, gatherDtype)];
}
case 'TensorArrayScatterV3': {
const scatterId = Object(utils["d" /* getParamValue */])('tensorArrayId', node, tensorMap, context);
const scatterIndices = Object(utils["d" /* getParamValue */])('indices', node, tensorMap, context);
const scatterTensor = Object(utils["d" /* getParamValue */])('tensor', node, tensorMap, context);
const scatterTensorArray = context.getTensorArray(scatterId.id);
scatterTensorArray.scatter(scatterIndices, scatterTensor);
return [scatterTensorArray.idTensor];
}
case 'TensorArrayConcatV3': {
const concatId = Object(utils["d" /* getParamValue */])('tensorArrayId', node, tensorMap, context);
const concatTensorArray = context.getTensorArray(concatId.id);
const concatDtype = Object(utils["d" /* getParamValue */])('dtype', node, tensorMap, context);
return [concatTensorArray.concat(concatDtype)];
}
case 'TensorArraySplitV3': {
const splitId = Object(utils["d" /* getParamValue */])('tensorArrayId', node, tensorMap, context);
const splitTensor = Object(utils["d" /* getParamValue */])('tensor', node, tensorMap, context);
const lengths = Object(utils["d" /* getParamValue */])('lengths', node, tensorMap, context);
const splitTensorArray = context.getTensorArray(splitId.id);
splitTensorArray.split(lengths, splitTensor);
return [splitTensorArray.idTensor];
}
case 'TensorArraySizeV3': {
const sizeId = Object(utils["d" /* getParamValue */])('tensorArrayId', node, tensorMap, context);
const sizeTensorArray = context.getTensorArray(sizeId.id);
return [Object(dist["scalar"])(sizeTensorArray.size(), 'int32')];
}
case 'TensorArrayCloseV3': {
const closeId = Object(utils["d" /* getParamValue */])('tensorArrayId', node, tensorMap, context);
const closeTensorArray = context.getTensorArray(closeId.id);
closeTensorArray.clearAndClose();
return [closeTensorArray.idTensor];
}
case 'TensorListSetItem': {
const idTensor = Object(utils["d" /* getParamValue */])('tensorListId', node, tensorMap, context);
const index = Object(utils["d" /* getParamValue */])('index', node, tensorMap, context);
const writeTensor = Object(utils["d" /* getParamValue */])('tensor', node, tensorMap, context);
const tensorList = context.getTensorList(idTensor.id);
tensorList.setItem(index, writeTensor);
return [tensorList.idTensor];
}
case 'TensorListGetItem': {
const idTensor = Object(utils["d" /* getParamValue */])('tensorListId', node, tensorMap, context);
const readIndex = Object(utils["d" /* getParamValue */])('index', node, tensorMap, context);
const elementShape = Object(utils["d" /* getParamValue */])('elementShape', node, tensorMap, context);
const elementDType = Object(utils["d" /* getParamValue */])('elementDType', node, tensorMap, context);
const tensorList = context.getTensorList(idTensor.id);
return [tensorList.getItem(readIndex, elementShape, elementDType)];
}
case 'TensorListScatterV2':
case 'TensorListScatter': {
const scatterIndices = Object(utils["d" /* getParamValue */])('indices', node, tensorMap, context);
const scatterTensor = Object(utils["d" /* getParamValue */])('tensor', node, tensorMap, context);
const elementShape = Object(utils["d" /* getParamValue */])('elementShape', node, tensorMap, context);
const numElements = Object(utils["d" /* getParamValue */])('numElements', node, tensorMap, context);
const tensorList = scatter(scatterTensor, scatterIndices, elementShape, numElements);
context.addTensorList(tensorList);
return [tensorList.idTensor];
}
case 'TensorListReserve':
case 'EmptyTensorList': {
const elementShape = Object(utils["d" /* getParamValue */])('elementShape', node, tensorMap, context);
const elementDtype = Object(utils["d" /* getParamValue */])('elementDType', node, tensorMap, context);
let numElementsParam;
if (node.op === 'TensorListReserve') {
numElementsParam = 'numElements';
}
else {
numElementsParam = 'maxNumElements';
}
const numElements = Object(utils["d" /* getParamValue */])(numElementsParam, node, tensorMap, context);
const tensorList = reserve(elementShape, elementDtype, numElements);
context.addTensorList(tensorList);
return [tensorList.idTensor];
}
case 'TensorListGather': {
const gatherId = Object(utils["d" /* getParamValue */])('tensorListId', node, tensorMap, context);
const gatherIndices = Object(utils["d" /* getParamValue */])('indices', node, tensorMap, context);
const elementShape = Object(utils["d" /* getParamValue */])('elementShape', node, tensorMap, context);
const elementDtype = Object(utils["d" /* getParamValue */])('elementDType', node, tensorMap, context);
const tensorList = context.getTensorList(gatherId.id);
return [tensorList.gather(gatherIndices, elementDtype, elementShape)];
}
case 'TensorListStack': {
const idTensor = Object(utils["d" /* getParamValue */])('tensorListId', node, tensorMap, context);
const elementShape = Object(utils["d" /* getParamValue */])('elementShape', node, tensorMap, context);
const elementDtype = Object(utils["d" /* getParamValue */])('elementDType', node, tensorMap, context);
const numElements = Object(utils["d" /* getParamValue */])('numElements', node, tensorMap, context);
const tensorList = context.getTensorList(idTensor.id);
return [tensorList.stack(elementShape, elementDtype, numElements)];
}
case 'TensorListFromTensor': {
const tensor = Object(utils["d" /* getParamValue */])('tensor', node, tensorMap, context);
const elementShape = Object(utils["d" /* getParamValue */])('elementShape', node, tensorMap, context);
const elementDtype = Object(utils["d" /* getParamValue */])('elementDType', node, tensorMap, context);
const tensorList = fromTensor(tensor, elementShape, elementDtype);
context.addTensorList(tensorList);
return [tensorList.idTensor];
}
case 'TensorListConcat': {
const concatId = Object(utils["d" /* getParamValue */])('tensorListId', node, tensorMap, context);
const tensorList = context.getTensorList(concatId.id);
const concatDtype = Object(utils["d" /* getParamValue */])('dtype', node, tensorMap, context);
const elementShape = Object(utils["d" /* getParamValue */])('elementShape', node, tensorMap, context);
return [tensorList.concat(concatDtype, elementShape)];
}
case 'TensorListPushBack': {
const idTensor = Object(utils["d" /* getParamValue */])('tensorListId', node, tensorMap, context);
const writeTensor = Object(utils["d" /* getParamValue */])('tensor', node, tensorMap, context);
const tensorList = context.getTensorList(idTensor.id);
tensorList.pushBack(writeTensor);
return [tensorList.idTensor];
}
case 'TensorListPopBack': {
const idTensor = Object(utils["d" /* getParamValue */])('tensorListId', node, tensorMap, context);
const elementShape = Object(utils["d" /* getParamValue */])('elementShape', node, tensorMap, context);
const elementDType = Object(utils["d" /* getParamValue */])('elementDType', node, tensorMap, context);
const tensorList = context.getTensorList(idTensor.id);
return [tensorList.popBack(elementShape, elementDType)];
}
case 'TensorListSplit': {
const splitTensor = Object(utils["d" /* getParamValue */])('tensor', node, tensorMap, context);
const elementShape = Object(utils["d" /* getParamValue */])('elementShape', node, tensorMap, context);
const lengths = Object(utils["d" /* getParamValue */])('lengths', node, tensorMap, context);
const tensorList = split(splitTensor, lengths, elementShape);
context.addTensorList(tensorList);
return [tensorList.idTensor];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const control_executor_CATEGORY = 'control';
//# sourceMappingURL=control_executor.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/conv1d.js
var conv1d = __webpack_require__(156);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/conv2d.js
var conv2d = __webpack_require__(65);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/ops.js + 73 modules
var ops = __webpack_require__(21);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/conv2d_transpose.js
var conv2d_transpose = __webpack_require__(157);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/depthwise_conv2d.js
var depthwise_conv2d = __webpack_require__(92);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/conv3d.js
var conv3d = __webpack_require__(227);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/avg_pool.js
var avg_pool = __webpack_require__(116);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/max_pool.js
var max_pool = __webpack_require__(126);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/max_pool_with_argmax.js
var max_pool_with_argmax = __webpack_require__(239);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/avg_pool_3d.js
var avg_pool_3d = __webpack_require__(223);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/max_pool_3d.js
var max_pool_3d = __webpack_require__(238);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/dilation2d.js
var dilation2d = __webpack_require__(160);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/convolution_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
function fusedConvAndDepthWiseParams(node, tensorMap, context) {
const [extraOp, activationFunc] = Object(utils["d" /* getParamValue */])('fusedOps', node, tensorMap, context);
const isBiasAdd = extraOp === 'biasadd';
const isPrelu = activationFunc === 'prelu';
const isBatchNorm = extraOp === 'fusedbatchnorm';
const numArgs = Object(utils["d" /* getParamValue */])('numArgs', node, tensorMap, context);
if (isBiasAdd) {
if (isPrelu && numArgs !== 2) {
throw new Error('FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu ' +
'must have two extra arguments: bias and alpha.');
}
if (!isPrelu && numArgs !== 1) {
throw new Error('FusedConv2d and DepthwiseConv2d with BiasAdd must have ' +
'one extra argument: bias.');
}
}
if (isBatchNorm) {
throw new Error('FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported');
}
const stride = Object(utils["d" /* getParamValue */])('strides', node, tensorMap, context);
const pad = Object(utils["c" /* getPadding */])(node, tensorMap, context);
const dataFormat = Object(utils["d" /* getParamValue */])('dataFormat', node, tensorMap, context)
.toUpperCase();
const dilations = Object(utils["d" /* getParamValue */])('dilations', node, tensorMap, context);
const [biasArg, preluArg] = Object(utils["d" /* getParamValue */])('args', node, tensorMap, context);
const leakyreluAlpha = Object(utils["d" /* getParamValue */])('leakyreluAlpha', node, tensorMap, context);
return {
stride,
pad,
dataFormat,
dilations,
biasArg,
preluArg,
activationFunc,
leakyreluAlpha
};
}
const convolution_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case 'Conv1D': {
const stride = Object(utils["d" /* getParamValue */])('stride', node, tensorMap, context);
const pad = Object(utils["d" /* getParamValue */])('pad', node, tensorMap, context);
const dataFormat = Object(utils["d" /* getParamValue */])('dataFormat', node, tensorMap, context)
.toUpperCase();
const dilation = Object(utils["d" /* getParamValue */])('dilation', node, tensorMap, context);
return [conv1d["a" /* conv1d */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('filter', node, tensorMap, context), stride, pad, dataFormat, dilation)];
}
case 'Conv2D': {
const stride = Object(utils["d" /* getParamValue */])('strides', node, tensorMap, context);
const pad = Object(utils["c" /* getPadding */])(node, tensorMap, context);
const dataFormat = Object(utils["d" /* getParamValue */])('dataFormat', node, tensorMap, context)
.toUpperCase();
const dilations = Object(utils["d" /* getParamValue */])('dilations', node, tensorMap, context);
return [conv2d["a" /* conv2d */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('filter', node, tensorMap, context), [stride[1], stride[2]], pad, dataFormat, [dilations[1], dilations[2]])];
}
case '_FusedConv2D': {
const { stride, pad, dataFormat, dilations, biasArg, preluArg, activationFunc, leakyreluAlpha } = fusedConvAndDepthWiseParams(node, tensorMap, context);
return [ops["qb" /* fused */].conv2d({
x: Object(utils["d" /* getParamValue */])('x', node, tensorMap, context),
filter: Object(utils["d" /* getParamValue */])('filter', node, tensorMap, context),
strides: [stride[1], stride[2]],
pad: pad,
dataFormat: dataFormat,
dilations: [dilations[1], dilations[2]],
bias: biasArg,
activation: activationFunc,
preluActivationWeights: preluArg,
leakyreluAlpha
})];
}
case 'FusedDepthwiseConv2dNative': {
const { stride, pad, dataFormat, dilations, biasArg, preluArg, activationFunc, leakyreluAlpha, } = fusedConvAndDepthWiseParams(node, tensorMap, context);
return [ops["qb" /* fused */].depthwiseConv2d({
x: Object(utils["d" /* getParamValue */])('x', node, tensorMap, context),
filter: Object(utils["d" /* getParamValue */])('filter', node, tensorMap, context),
strides: [stride[1], stride[2]],
pad: pad,
dataFormat: dataFormat,
dilations: [dilations[1], dilations[2]],
bias: biasArg,
activation: activationFunc,
preluActivationWeights: preluArg,
leakyreluAlpha
})];
}
case 'Conv2DBackpropInput':
case 'Conv2dTranspose': {
const shape = Object(utils["d" /* getParamValue */])('outputShape', node, tensorMap, context);
const stride = Object(utils["d" /* getParamValue */])('strides', node, tensorMap, context);
const pad = Object(utils["c" /* getPadding */])(node, tensorMap, context);
return [conv2d_transpose["a" /* conv2dTranspose */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('filter', node, tensorMap, context), shape, [stride[1], stride[2]], pad)];
}
case 'DepthwiseConv2dNative':
case 'DepthwiseConv2d': {
const stride = Object(utils["d" /* getParamValue */])('strides', node, tensorMap, context);
const pad = Object(utils["c" /* getPadding */])(node, tensorMap, context);
const dilations = Object(utils["d" /* getParamValue */])('dilations', node, tensorMap, context);
const dataFormat = Object(utils["d" /* getParamValue */])('dataFormat', node, tensorMap, context)
.toUpperCase();
return [depthwise_conv2d["a" /* depthwiseConv2d */](Object(utils["d" /* getParamValue */])('input', node, tensorMap, context), Object(utils["d" /* getParamValue */])('filter', node, tensorMap, context), [stride[1], stride[2]], pad, dataFormat, [dilations[1], dilations[2]])];
}
case 'Conv3D': {
const stride = Object(utils["d" /* getParamValue */])('strides', node, tensorMap, context);
const pad = Object(utils["d" /* getParamValue */])('pad', node, tensorMap, context);
const dataFormat = Object(utils["d" /* getParamValue */])('dataFormat', node, tensorMap, context)
.toUpperCase();
const dilations = Object(utils["d" /* getParamValue */])('dilations', node, tensorMap, context);
return [conv3d["a" /* conv3d */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('filter', node, tensorMap, context), [stride[1], stride[2], stride[3]], pad, dataFormat, [dilations[1], dilations[2], dilations[3]])];
}
case 'AvgPool': {
const stride = Object(utils["d" /* getParamValue */])('strides', node, tensorMap, context);
const pad = Object(utils["d" /* getParamValue */])('pad', node, tensorMap, context);
const kernelSize = Object(utils["d" /* getParamValue */])('kernelSize', node, tensorMap, context);
return [avg_pool["a" /* avgPool */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), [kernelSize[1], kernelSize[2]], [stride[1], stride[2]], pad)];
}
case 'MaxPool': {
const stride = Object(utils["d" /* getParamValue */])('strides', node, tensorMap, context);
const pad = Object(utils["d" /* getParamValue */])('pad', node, tensorMap, context);
const kernelSize = Object(utils["d" /* getParamValue */])('kernelSize', node, tensorMap, context);
return [max_pool["a" /* maxPool */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), [kernelSize[1], kernelSize[2]], [stride[1], stride[2]], pad)];
}
case 'MaxPoolWithArgmax': {
const stride = Object(utils["d" /* getParamValue */])('strides', node, tensorMap, context);
const pad = Object(utils["d" /* getParamValue */])('pad', node, tensorMap, context);
const kernelSize = Object(utils["d" /* getParamValue */])('kernelSize', node, tensorMap, context);
const includeBatchInIndex = Object(utils["d" /* getParamValue */])('includeBatchInIndex', node, tensorMap, context);
const { result, indexes } = max_pool_with_argmax["a" /* maxPoolWithArgmax */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), [kernelSize[1], kernelSize[2]], [stride[1], stride[2]], pad, includeBatchInIndex);
return [result, indexes];
}
case 'AvgPool3D': {
const stride = Object(utils["d" /* getParamValue */])('strides', node, tensorMap, context);
const pad = Object(utils["d" /* getParamValue */])('pad', node, tensorMap, context);
const kernelSize = Object(utils["d" /* getParamValue */])('kernelSize', node, tensorMap, context);
return [avg_pool_3d["a" /* avgPool3d */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), [kernelSize[1], kernelSize[2], kernelSize[3]], [stride[1], stride[2], stride[3]], pad)];
}
case 'MaxPool3D': {
const stride = Object(utils["d" /* getParamValue */])('strides', node, tensorMap, context);
const pad = Object(utils["d" /* getParamValue */])('pad', node, tensorMap, context);
const kernelSize = Object(utils["d" /* getParamValue */])('kernelSize', node, tensorMap, context);
return [max_pool_3d["a" /* maxPool3d */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), [kernelSize[1], kernelSize[2], kernelSize[3]], [stride[1], stride[2], stride[3]], pad)];
}
case 'Dilation2D': {
const strides = Object(utils["d" /* getParamValue */])('strides', node, tensorMap, context);
const pad = Object(utils["d" /* getParamValue */])('pad', node, tensorMap, context);
const dilations = Object(utils["d" /* getParamValue */])('dilations', node, tensorMap, context);
// strides: [1, stride_height, stride_width, 1].
const strideHeight = strides[1];
const strideWidth = strides[2];
// dilations: [1, dilation_height, dilation_width, 1].
const dilationHeight = dilations[1];
const dilationWidth = dilations[2];
return [dilation2d["a" /* dilation2d */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('filter', node, tensorMap, context), [strideHeight, strideWidth], pad, [dilationHeight, dilationWidth], 'NHWC' /* dataFormat */)];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const convolution_executor_CATEGORY = 'convolution';
//# sourceMappingURL=convolution_executor.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/fill.js
var fill = __webpack_require__(115);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/linspace.js
var linspace = __webpack_require__(235);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/multinomial.js
var multinomial = __webpack_require__(240);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/one_hot.js
var one_hot = __webpack_require__(106);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/ones.js
var ones = __webpack_require__(55);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/ones_like.js
var ones_like = __webpack_require__(241);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/random_uniform.js
var random_uniform = __webpack_require__(171);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/range.js
var range = __webpack_require__(146);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/truncated_normal.js
var truncated_normal = __webpack_require__(249);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/zeros.js
var zeros = __webpack_require__(80);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/zeros_like.js
var zeros_like = __webpack_require__(20);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/creation_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
const creation_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case 'Fill': {
const shape = Object(utils["d" /* getParamValue */])('shape', node, tensorMap, context);
const dtype = Object(utils["d" /* getParamValue */])('dtype', node, tensorMap, context);
const value = Object(utils["d" /* getParamValue */])('value', node, tensorMap, context);
return [fill["a" /* fill */](shape, value, dtype)];
}
case 'LinSpace': {
const start = Object(utils["d" /* getParamValue */])('start', node, tensorMap, context);
const stop = Object(utils["d" /* getParamValue */])('stop', node, tensorMap, context);
const num = Object(utils["d" /* getParamValue */])('num', node, tensorMap, context);
return [linspace["a" /* linspace */](start, stop, num)];
}
case 'Multinomial': {
const logits = Object(utils["d" /* getParamValue */])('logits', node, tensorMap, context);
const numSamples = Object(utils["d" /* getParamValue */])('numSamples', node, tensorMap, context);
const seed = Object(utils["d" /* getParamValue */])('seed', node, tensorMap, context);
return [multinomial["a" /* multinomial */](logits, numSamples, seed)];
}
case 'OneHot': {
const indices = Object(utils["d" /* getParamValue */])('indices', node, tensorMap, context);
const depth = Object(utils["d" /* getParamValue */])('depth', node, tensorMap, context);
const onValue = Object(utils["d" /* getParamValue */])('onValue', node, tensorMap, context);
const offValue = Object(utils["d" /* getParamValue */])('offValue', node, tensorMap, context);
return [one_hot["a" /* oneHot */](indices, depth, onValue, offValue)];
}
case 'Ones': {
return [ones["a" /* ones */](Object(utils["d" /* getParamValue */])('shape', node, tensorMap, context), Object(utils["d" /* getParamValue */])('dtype', node, tensorMap, context))];
}
case 'OnesLike': {
return [ones_like["a" /* onesLike */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
case 'RandomUniform': {
return [random_uniform["a" /* randomUniform */](
// tslint:disable-next-line:no-any
Object(utils["d" /* getParamValue */])('shape', node, tensorMap, context), Object(utils["d" /* getParamValue */])('minval', node, tensorMap, context), Object(utils["d" /* getParamValue */])('maxval', node, tensorMap, context), Object(utils["d" /* getParamValue */])('dtype', node, tensorMap, context))];
}
case 'Range': {
const start = Object(utils["d" /* getParamValue */])('start', node, tensorMap, context);
const stop = Object(utils["d" /* getParamValue */])('stop', node, tensorMap, context);
const step = Object(utils["d" /* getParamValue */])('step', node, tensorMap, context);
return [range["a" /* range */](start, stop, step, Object(utils["d" /* getParamValue */])('dtype', node, tensorMap, context))];
}
case 'TruncatedNormal': {
const shape = Object(utils["d" /* getParamValue */])('shape', node, tensorMap, context);
const mean = Object(utils["d" /* getParamValue */])('mean', node, tensorMap, context);
const stdDev = Object(utils["d" /* getParamValue */])('stdDev', node, tensorMap, context);
const seed = Object(utils["d" /* getParamValue */])('seed', node, tensorMap, context);
return [truncated_normal["a" /* truncatedNormal */](shape, mean, stdDev, Object(utils["d" /* getParamValue */])('dtype', node, tensorMap, context), seed)];
}
case 'Zeros': {
return [zeros["a" /* zeros */](Object(utils["d" /* getParamValue */])('shape', node, tensorMap, context), Object(utils["d" /* getParamValue */])('dtype', node, tensorMap, context))];
}
case 'ZerosLike': {
return [zeros_like["a" /* zerosLike */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const creation_executor_CATEGORY = 'creation';
//# sourceMappingURL=creation_executor.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/cast.js
var cast = __webpack_require__(12);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/where_async.js
var where_async = __webpack_require__(181);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/setdiff1d_async.js
var setdiff1d_async = __webpack_require__(244);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/dynamic_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
function nmsParams(node, tensorMap, context) {
const boxes = Object(utils["d" /* getParamValue */])('boxes', node, tensorMap, context);
const scores = Object(utils["d" /* getParamValue */])('scores', node, tensorMap, context);
const maxOutputSize = Object(utils["d" /* getParamValue */])('maxOutputSize', node, tensorMap, context);
const iouThreshold = Object(utils["d" /* getParamValue */])('iouThreshold', node, tensorMap, context);
const scoreThreshold = Object(utils["d" /* getParamValue */])('scoreThreshold', node, tensorMap, context);
const softNmsSigma = Object(utils["d" /* getParamValue */])('softNmsSigma', node, tensorMap, context);
return {
boxes,
scores,
maxOutputSize,
iouThreshold,
scoreThreshold,
softNmsSigma
};
}
const dynamic_executor_executeOp = async (node, tensorMap, context) => {
switch (node.op) {
case 'NonMaxSuppressionV5': {
const { boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma } = nmsParams(node, tensorMap, context);
const result = await ops["xb" /* image */].nonMaxSuppressionWithScoreAsync(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
return [result.selectedIndices, result.selectedScores];
}
case 'NonMaxSuppressionV4': {
const { boxes, scores, maxOutputSize, iouThreshold, scoreThreshold } = nmsParams(node, tensorMap, context);
const padToMaxOutputSize = Object(utils["d" /* getParamValue */])('padToMaxOutputSize', node, tensorMap, context);
const result = await ops["xb" /* image */].nonMaxSuppressionPaddedAsync(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize);
return [result.selectedIndices, result.validOutputs];
}
case 'NonMaxSuppressionV3':
case 'NonMaxSuppressionV2': {
const { boxes, scores, maxOutputSize, iouThreshold, scoreThreshold } = nmsParams(node, tensorMap, context);
return [await ops["xb" /* image */].nonMaxSuppressionAsync(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold)];
}
case 'Where': {
const condition = cast["a" /* cast */](Object(utils["d" /* getParamValue */])('condition', node, tensorMap, context), 'bool');
const result = [await where_async["a" /* whereAsync */](condition)];
condition.dispose();
return result;
}
case 'ListDiff': {
return setdiff1d_async["a" /* setdiff1dAsync */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('y', node, tensorMap, context));
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const dynamic_executor_CATEGORY = 'dynamic';
//# sourceMappingURL=dynamic_executor.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/topk.js
var topk = __webpack_require__(179);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/unique.js
var unique = __webpack_require__(180);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/evaluation_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
const evaluation_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case 'TopKV2': {
const x = Object(utils["d" /* getParamValue */])('x', node, tensorMap, context);
const k = Object(utils["d" /* getParamValue */])('k', node, tensorMap, context);
const sorted = Object(utils["d" /* getParamValue */])('sorted', node, tensorMap, context);
const result = topk["a" /* topk */](x, k, sorted);
return [result.values, result.indices];
}
case 'Unique': {
const x = Object(utils["d" /* getParamValue */])('x', node, tensorMap, context);
const result = unique["a" /* unique */](x);
return [result.values, result.indices];
}
case 'UniqueV2': {
const x = Object(utils["d" /* getParamValue */])('x', node, tensorMap, context);
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
const result = unique["a" /* unique */](x, axis);
return [result.values, result.indices];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const evaluation_executor_CATEGORY = 'evaluation';
//# sourceMappingURL=evaluation_executor.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/tensor1d.js
var tensor1d = __webpack_require__(77);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/scalar.js
var scalar = __webpack_require__(16);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/graph_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
const graph_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case 'Const': {
return tensorMap[node.name];
}
case 'PlaceholderWithDefault':
const def = Object(utils["d" /* getParamValue */])('default', node, tensorMap, context);
return [Object(utils["e" /* getTensor */])(node.name, tensorMap, context) || def];
case 'Placeholder':
return [Object(utils["e" /* getTensor */])(node.name, tensorMap, context)];
case 'Identity':
case 'StopGradient':
case 'FakeQuantWithMinMaxVars': { // This op is currently ignored.
const data = Object(utils["d" /* getParamValue */])('x', node, tensorMap, context);
return [Object(utils["a" /* cloneTensor */])(data)];
}
case 'IdentityN':
return Object(utils["d" /* getParamValue */])('x', node, tensorMap, context)
.map((t) => Object(utils["a" /* cloneTensor */])(t));
case 'Snapshot':
const snapshot = Object(utils["d" /* getParamValue */])('x', node, tensorMap, context);
return [Object(utils["a" /* cloneTensor */])(snapshot)];
case 'Shape':
return [tensor1d["a" /* tensor1d */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context).shape, 'int32')];
case 'ShapeN':
return Object(utils["d" /* getParamValue */])('x', node, tensorMap, context)
.map((t) => tensor1d["a" /* tensor1d */](t.shape));
case 'Size':
return [scalar["a" /* scalar */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context).size, 'int32')];
case 'Rank':
return [scalar["a" /* scalar */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context).rank, 'int32')];
case 'NoOp':
return [scalar["a" /* scalar */](1)];
case 'Print':
const input = Object(utils["d" /* getParamValue */])('x', node, tensorMap, context);
const data = Object(utils["d" /* getParamValue */])('data', node, tensorMap, context);
const message = Object(utils["d" /* getParamValue */])('message', node, tensorMap, context);
const summarize = Object(utils["d" /* getParamValue */])('summarize', node, tensorMap, context);
console.warn('The graph has a tf.print() operation,' +
'usually used for debugging, which slows down performance.');
console.log(message);
for (let i = 0; i < data.length; i++) {
console.log(Array.prototype.slice.call(data[i].dataSync())
.slice(0, summarize));
}
return [input];
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const graph_executor_CATEGORY = 'graph';
//# sourceMappingURL=graph_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/executor/hash_table.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.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
/**
* Hashtable contains a set of tensors, which can be accessed by key.
*/
class hash_table_HashTable {
/**
* Constructor of HashTable. Creates a hash table.
*
* @param keyDType `dtype` of the table keys.
* @param valueDType `dtype` of the table values.
*/
constructor(keyDType, valueDType) {
this.keyDType = keyDType;
this.valueDType = valueDType;
this.handle = Object(dist["scalar"])(0);
// tslint:disable-next-line: no-any
this.tensorMap = new Map();
Object(dist["keep"])(this.handle);
}
get id() {
return this.handle.id;
}
/**
* Dispose the tensors and handle and clear the hashtable.
*/
clearAndClose() {
this.tensorMap.forEach(value => value.dispose());
this.tensorMap.clear();
this.handle.dispose();
}
/**
* The number of items in the hash table.
*/
size() {
return this.tensorMap.size;
}
/**
* The number of items in the hash table as a rank-0 tensor.
*/
tensorSize() {
return scalar["a" /* scalar */](this.size(), 'int32');
}
/**
* Replaces the contents of the table with the specified keys and values.
* @param keys Keys to store in the hashtable.
* @param values Values to store in the hashtable.
*/
async import(keys, values) {
this.checkKeyAndValueTensor(keys, values);
// We only store the primitive values of the keys, this allows lookup
// to be O(1).
const $keys = await keys.data();
// Clear the hashTable before inserting new values.
this.tensorMap.forEach(value => value.dispose());
this.tensorMap.clear();
return Object(dist["tidy"])(() => {
const $values = Object(dist["unstack"])(values);
const keysLength = $keys.length;
const valuesLength = $values.length;
dist["util"].assert(keysLength === valuesLength, () => `The number of elements doesn't match, keys has ` +
`${keysLength} elements, the values has ${valuesLength} ` +
`elements.`);
for (let i = 0; i < keysLength; i++) {
const key = $keys[i];
const value = $values[i];
Object(dist["keep"])(value);
this.tensorMap.set(key, value);
}
return this.handle;
});
}
/**
* Looks up keys in a hash table, outputs the corresponding values.
*
* Performs batch lookups, for every element in the key tensor, `find`
* stacks the corresponding value into the return tensor.
*
* If an element is not present in the table, the given `defaultValue` is
* used.
*
* @param keys Keys to look up. Must have the same type as the keys of the
* table.
* @param defaultValue The scalar `defaultValue` is the value output for keys
* not present in the table. It must also be of the same type as the
* table values.
*/
async find(keys, defaultValue) {
this.checkKeyAndValueTensor(keys, defaultValue);
const $keys = await keys.data();
return Object(dist["tidy"])(() => {
const result = [];
for (let i = 0; i < $keys.length; i++) {
const key = $keys[i];
const value = this.findWithDefault(key, defaultValue);
result.push(value);
}
return Object(dist["stack"])(result);
});
}
// tslint:disable-next-line: no-any
findWithDefault(key, defaultValue) {
const result = this.tensorMap.get(key);
return result != null ? result : defaultValue;
}
checkKeyAndValueTensor(key, value) {
if (key.dtype !== this.keyDType) {
throw new Error(`Expect key dtype ${this.keyDType}, but got ` +
`${key.dtype}`);
}
if (value.dtype !== this.valueDType) {
throw new Error(`Expect value dtype ${this.valueDType}, but got ` +
`${value.dtype}`);
}
}
}
//# sourceMappingURL=hash_table.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/hash_table_executor.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 hash_table_executor_executeOp = async (node, tensorMap, context, resourceManager) => {
switch (node.op) {
case 'HashTable':
case 'HashTableV2': {
const keyDType = Object(utils["d" /* getParamValue */])('keyDType', node, tensorMap, context);
const valueDType = Object(utils["d" /* getParamValue */])('valueDType', node, tensorMap, context);
const hashTable = new hash_table_HashTable(keyDType, valueDType);
resourceManager.addHashTable(node.name, hashTable);
return [hashTable.handle];
}
case 'LookupTableImport':
case 'LookupTableImportV2': {
const handle = Object(utils["d" /* getParamValue */])('tableHandle', node, tensorMap, context, resourceManager);
const keys = Object(utils["d" /* getParamValue */])('keys', node, tensorMap, context);
const values = Object(utils["d" /* getParamValue */])('values', node, tensorMap, context);
const hashTable = resourceManager.getHashTableById(handle.id);
return [await hashTable.import(keys, values)];
}
case 'LookupTableFind':
case 'LookupTableFindV2': {
const handle = Object(utils["d" /* getParamValue */])('tableHandle', node, tensorMap, context, resourceManager);
const keys = Object(utils["d" /* getParamValue */])('keys', node, tensorMap, context);
const defaultValue = Object(utils["d" /* getParamValue */])('defaultValue', node, tensorMap, context);
const hashTable = resourceManager.getHashTableById(handle.id);
return [await hashTable.find(keys, defaultValue)];
}
case 'LookupTableSize':
case 'LookupTableSizeV2': {
const handle = Object(utils["d" /* getParamValue */])('tableHandle', node, tensorMap, context, resourceManager);
const hashTable = resourceManager.getHashTableById(handle.id);
return [hashTable.tensorSize()];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const hash_table_executor_CATEGORY = 'hash_table';
//# sourceMappingURL=hash_table_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/image_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
const image_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case 'ResizeBilinear': {
const images = Object(utils["d" /* getParamValue */])('images', node, tensorMap, context);
const size = Object(utils["d" /* getParamValue */])('size', node, tensorMap, context);
const alignCorners = Object(utils["d" /* getParamValue */])('alignCorners', node, tensorMap, context);
const halfPixelCenters = Object(utils["d" /* getParamValue */])('halfPixelCenters', node, tensorMap, context);
return [ops["xb" /* image */].resizeBilinear(images, [size[0], size[1]], alignCorners, halfPixelCenters)];
}
case 'ResizeNearestNeighbor': {
const images = Object(utils["d" /* getParamValue */])('images', node, tensorMap, context);
const size = Object(utils["d" /* getParamValue */])('size', node, tensorMap, context);
const alignCorners = Object(utils["d" /* getParamValue */])('alignCorners', node, tensorMap, context);
const halfPixelCenters = Object(utils["d" /* getParamValue */])('halfPixelCenters', node, tensorMap, context);
return [ops["xb" /* image */].resizeNearestNeighbor(images, [size[0], size[1]], alignCorners, halfPixelCenters)];
}
case 'CropAndResize': {
const image = Object(utils["d" /* getParamValue */])('image', node, tensorMap, context);
const boxes = Object(utils["d" /* getParamValue */])('boxes', node, tensorMap, context);
const boxInd = Object(utils["d" /* getParamValue */])('boxInd', node, tensorMap, context);
const cropSize = Object(utils["d" /* getParamValue */])('cropSize', node, tensorMap, context);
const method = Object(utils["d" /* getParamValue */])('method', node, tensorMap, context);
const extrapolationValue = Object(utils["d" /* getParamValue */])('extrapolationValue', node, tensorMap, context);
return [ops["xb" /* image */].cropAndResize(image, boxes, boxInd, cropSize, method, extrapolationValue)];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const image_executor_CATEGORY = 'image';
//# sourceMappingURL=image_executor.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/equal.js
var equal = __webpack_require__(93);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/not_equal.js
var not_equal = __webpack_require__(128);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/greater.js
var greater = __webpack_require__(50);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/greater_equal.js
var greater_equal = __webpack_require__(66);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/less.js
var less = __webpack_require__(123);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/less_equal.js
var less_equal = __webpack_require__(67);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/logical_and.js
var logical_and = __webpack_require__(59);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/logical_not.js
var logical_not = __webpack_require__(95);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/logical_or.js
var logical_or = __webpack_require__(125);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/where.js
var where = __webpack_require__(36);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/logical_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
const logical_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case 'Equal': {
return [equal["a" /* equal */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
case 'NotEqual': {
return [not_equal["a" /* notEqual */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
case 'Greater': {
return [greater["a" /* greater */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
case 'GreaterEqual': {
return [greater_equal["a" /* greaterEqual */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
case 'Less': {
return [less["a" /* less */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
case 'LessEqual': {
return [less_equal["a" /* lessEqual */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
case 'LogicalAnd': {
return [logical_and["a" /* logicalAnd */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
case 'LogicalNot': {
return [logical_not["a" /* logicalNot */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context))];
}
case 'LogicalOr': {
return [logical_or["a" /* logicalOr */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
case 'Select':
case 'SelectV2': {
return [where["a" /* where */](Object(utils["d" /* getParamValue */])('condition', node, tensorMap, context), Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context))];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const logical_executor_CATEGORY = 'logical';
//# sourceMappingURL=logical_executor.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/mat_mul.js
var mat_mul = __webpack_require__(24);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/einsum.js
var einsum = __webpack_require__(229);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/transpose.js
var transpose = __webpack_require__(52);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/matrices_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
const matrices_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case 'BatchMatMul':
case 'BatchMatMulV2':
case 'MatMul':
return [mat_mul["a" /* matMul */](Object(utils["d" /* getParamValue */])('a', node, tensorMap, context), Object(utils["d" /* getParamValue */])('b', node, tensorMap, context), Object(utils["d" /* getParamValue */])('transposeA', node, tensorMap, context), Object(utils["d" /* getParamValue */])('transposeB', node, tensorMap, context))];
case 'Einsum':
return [einsum["a" /* einsum */](Object(utils["d" /* getParamValue */])('equation', node, tensorMap, context), ...Object(utils["d" /* getParamValue */])('tensors', node, tensorMap, context))];
case 'Transpose':
return [transpose["a" /* transpose */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('perm', node, tensorMap, context))];
case '_FusedMatMul':
const [extraOp, activationFunc] = Object(utils["d" /* getParamValue */])('fusedOps', node, tensorMap, context);
const isBiasAdd = extraOp === 'biasadd';
const isPrelu = activationFunc === 'prelu';
const numArgs = Object(utils["d" /* getParamValue */])('numArgs', node, tensorMap, context);
const leakyreluAlpha = Object(utils["d" /* getParamValue */])('leakyreluAlpha', node, tensorMap, context);
if (isBiasAdd) {
if (isPrelu && numArgs !== 2) {
throw new Error('Fused MatMul with BiasAdd and Prelu must have two ' +
'extra arguments: bias and alpha.');
}
if (!isPrelu && numArgs !== 1) {
throw new Error('Fused MatMul with BiasAdd must have one extra argument: bias.');
}
}
const [biasArg, preluArg] = Object(utils["d" /* getParamValue */])('args', node, tensorMap, context);
return [ops["qb" /* fused */].matMul({
a: Object(utils["d" /* getParamValue */])('a', node, tensorMap, context),
b: Object(utils["d" /* getParamValue */])('b', node, tensorMap, context),
transposeA: Object(utils["d" /* getParamValue */])('transposeA', node, tensorMap, context),
transposeB: Object(utils["d" /* getParamValue */])('transposeB', node, tensorMap, context),
bias: biasArg,
activation: activationFunc,
preluActivationWeights: preluArg,
leakyreluAlpha
})];
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const matrices_executor_CATEGORY = 'matrices';
//# sourceMappingURL=matrices_executor.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/batchnorm.js + 1 modules
var batchnorm = __webpack_require__(84);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/local_response_normalization.js
var local_response_normalization = __webpack_require__(163);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/softmax.js
var softmax = __webpack_require__(246);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/log_softmax.js
var log_softmax = __webpack_require__(237);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/sparse_to_dense.js + 1 modules
var sparse_to_dense = __webpack_require__(253);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/normalization_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
const normalization_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case 'FusedBatchNorm':
case 'FusedBatchNormV2': {
return [batchnorm["a" /* batchNorm */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('mean', node, tensorMap, context), Object(utils["d" /* getParamValue */])('variance', node, tensorMap, context), Object(utils["d" /* getParamValue */])('offset', node, tensorMap, context), Object(utils["d" /* getParamValue */])('scale', node, tensorMap, context), Object(utils["d" /* getParamValue */])('epsilon', node, tensorMap, context))];
}
case 'FusedBatchNormV3': {
return [batchnorm["a" /* batchNorm */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('mean', node, tensorMap, context), Object(utils["d" /* getParamValue */])('variance', node, tensorMap, context), Object(utils["d" /* getParamValue */])('offset', node, tensorMap, context), Object(utils["d" /* getParamValue */])('scale', node, tensorMap, context), Object(utils["d" /* getParamValue */])('epsilon', node, tensorMap, context))];
}
case 'LRN': {
return [local_response_normalization["a" /* localResponseNormalization */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('radius', node, tensorMap, context), Object(utils["d" /* getParamValue */])('bias', node, tensorMap, context), Object(utils["d" /* getParamValue */])('alpha', node, tensorMap, context), Object(utils["d" /* getParamValue */])('beta', node, tensorMap, context))];
}
case 'Softmax': {
return [softmax["a" /* softmax */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
case 'LogSoftmax': {
return [log_softmax["a" /* logSoftmax */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
case 'SparseToDense': {
return [sparse_to_dense["a" /* sparseToDense */](Object(utils["d" /* getParamValue */])('sparseIndices', node, tensorMap, context), Object(utils["d" /* getParamValue */])('outputShape', node, tensorMap, context), Object(utils["d" /* getParamValue */])('sparseValues', node, tensorMap, context), Object(utils["d" /* getParamValue */])('defaultValue', node, tensorMap, context))];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const normalization_executor_CATEGORY = 'normalization';
//# sourceMappingURL=normalization_executor.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/max.js
var max = __webpack_require__(72);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/mean.js
var ops_mean = __webpack_require__(88);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/min.js
var min = __webpack_require__(105);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/sum.js
var sum = __webpack_require__(19);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/all.js
var ops_all = __webpack_require__(151);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/any.js
var any = __webpack_require__(152);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/arg_max.js
var arg_max = __webpack_require__(153);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/arg_min.js
var arg_min = __webpack_require__(154);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/cumsum.js
var cumsum = __webpack_require__(118);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/bincount.js
var bincount = __webpack_require__(224);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/dense_bincount.js
var dense_bincount = __webpack_require__(228);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/reduction_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
const reduction_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case 'Max': {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
const keepDims = Object(utils["d" /* getParamValue */])('keepDims', node, tensorMap, context);
return [max["a" /* max */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), axis, keepDims)];
}
case 'Mean': {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
const keepDims = Object(utils["d" /* getParamValue */])('keepDims', node, tensorMap, context);
return [ops_mean["a" /* mean */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), axis, keepDims)];
}
case 'Min': {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
const keepDims = Object(utils["d" /* getParamValue */])('keepDims', node, tensorMap, context);
return [min["a" /* min */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), axis, keepDims)];
}
case 'Sum': {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
const keepDims = Object(utils["d" /* getParamValue */])('keepDims', node, tensorMap, context);
return [sum["a" /* sum */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), axis, keepDims)];
}
case 'All': {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
const keepDims = Object(utils["d" /* getParamValue */])('keepDims', node, tensorMap, context);
return [ops_all["a" /* all */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), axis, keepDims)];
}
case 'Any': {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
const keepDims = Object(utils["d" /* getParamValue */])('keepDims', node, tensorMap, context);
return [any["a" /* any */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), axis, keepDims)];
}
case 'ArgMax': {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
return [arg_max["a" /* argMax */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), axis)];
}
case 'ArgMin': {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
return [arg_min["a" /* argMin */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), axis)];
}
case 'Prod': {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
const keepDims = Object(utils["d" /* getParamValue */])('keepDims', node, tensorMap, context);
return [prod["a" /* prod */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), axis, keepDims)];
}
case 'Cumsum': {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
const exclusive = Object(utils["d" /* getParamValue */])('exclusive', node, tensorMap, context);
const reverse = Object(utils["d" /* getParamValue */])('reverse', node, tensorMap, context);
return [cumsum["a" /* cumsum */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), axis, exclusive, reverse)];
}
case 'Bincount':
const x = Object(utils["d" /* getParamValue */])('x', node, tensorMap, context);
const weights = Object(utils["d" /* getParamValue */])('weights', node, tensorMap, context);
const size = Object(utils["d" /* getParamValue */])('size', node, tensorMap, context);
return [bincount["a" /* bincount */](x, weights, size)];
case 'DenseBincount': {
const x = Object(utils["d" /* getParamValue */])('x', node, tensorMap, context);
const weights = Object(utils["d" /* getParamValue */])('weights', node, tensorMap, context);
const size = Object(utils["d" /* getParamValue */])('size', node, tensorMap, context);
const binaryOutput = Object(utils["d" /* getParamValue */])('binaryOutput', node, tensorMap, context);
return [dense_bincount["a" /* denseBincount */](x, weights, size, binaryOutput)];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const reduction_executor_CATEGORY = 'reduction';
//# sourceMappingURL=reduction_executor.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/concat.js
var concat = __webpack_require__(32);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/gather.js
var gather = __webpack_require__(94);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/reverse.js
var ops_reverse = __webpack_require__(48);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/slice.js
var slice = __webpack_require__(28);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/strided_slice.js
var strided_slice = __webpack_require__(247);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/squeeze.js
var squeeze = __webpack_require__(97);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/reshape.js
var reshape = __webpack_require__(7);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/stack.js
var ops_stack = __webpack_require__(60);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/unstack.js
var unstack = __webpack_require__(83);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/tile.js
var tile = __webpack_require__(85);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/split.js
var ops_split = __webpack_require__(76);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/scatter_nd.js
var scatter_nd = __webpack_require__(250);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/gather_nd.js
var gather_nd = __webpack_require__(251);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/slice_join_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
const slice_join_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case 'ConcatV2':
case 'Concat': {
const n = Object(utils["d" /* getParamValue */])('n', node, tensorMap, context);
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
let inputs = Object(utils["d" /* getParamValue */])('tensors', node, tensorMap, context);
inputs = inputs.slice(0, n);
return [concat["a" /* concat */](inputs, axis)];
}
case 'Gather': {
const input = Object(utils["d" /* getParamValue */])('x', node, tensorMap, context);
const indices = Object(utils["d" /* getParamValue */])('indices', node, tensorMap, context);
return [gather["a" /* gather */](input, cast["a" /* cast */](indices, 'int32'), 0)];
}
case 'GatherV2': {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
const batchDims = Object(utils["d" /* getParamValue */])('batchDims', node, tensorMap, context);
const input = Object(utils["d" /* getParamValue */])('x', node, tensorMap, context);
const indices = Object(utils["d" /* getParamValue */])('indices', node, tensorMap, context);
return [gather["a" /* gather */](input, cast["a" /* cast */](indices, 'int32'), axis, batchDims)];
}
case 'Reverse': {
const dims = Object(utils["d" /* getParamValue */])('dims', node, tensorMap, context);
const axis = [];
for (let i = 0; i < dims.length; i++) {
if (dims[i]) {
axis.push(i);
}
}
const input = Object(utils["d" /* getParamValue */])('x', node, tensorMap, context);
return [ops_reverse["a" /* reverse */](input, axis)];
}
case 'ReverseV2': {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
const input = Object(utils["d" /* getParamValue */])('x', node, tensorMap, context);
return [ops_reverse["a" /* reverse */](input, axis)];
}
case 'Slice': {
// tslint:disable-next-line:no-any
const begin = Object(utils["d" /* getParamValue */])('begin', node, tensorMap, context);
// tslint:disable-next-line:no-any
const size = Object(utils["d" /* getParamValue */])('size', node, tensorMap, context);
return [slice["a" /* slice */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), begin, size)];
}
case 'StridedSlice': {
const begin = Object(utils["d" /* getParamValue */])('begin', node, tensorMap, context);
const end = Object(utils["d" /* getParamValue */])('end', node, tensorMap, context);
const strides = Object(utils["d" /* getParamValue */])('strides', node, tensorMap, context);
const beginMask = Object(utils["d" /* getParamValue */])('beginMask', node, tensorMap, context);
const endMask = Object(utils["d" /* getParamValue */])('endMask', node, tensorMap, context);
const ellipsisMask = Object(utils["d" /* getParamValue */])('ellipsisMask', node, tensorMap, context);
const newAxisMask = Object(utils["d" /* getParamValue */])('newAxisMask', node, tensorMap, context);
const shrinkAxisMask = Object(utils["d" /* getParamValue */])('shrinkAxisMask', node, tensorMap, context);
const tensor = Object(utils["d" /* getParamValue */])('x', node, tensorMap, context);
return [strided_slice["a" /* stridedSlice */](tensor, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask)];
}
case 'Pack': {
return Object(dist["tidy"])(() => {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
const tensors = Object(utils["d" /* getParamValue */])('tensors', node, tensorMap, context);
// Reshape the tensors to the first tensor's shape if they don't
// match.
const shape = tensors[0].shape;
const squeezedShape = squeeze["a" /* squeeze */](tensors[0]).shape;
const mapped = tensors.map(tensor => {
const sameShape = dist["util"].arraysEqual(tensor.shape, shape);
if (!sameShape &&
!dist["util"].arraysEqual(squeeze["a" /* squeeze */](tensor).shape, squeezedShape)) {
throw new Error('the input tensors shape does not match');
}
return sameShape ? tensor : reshape["a" /* reshape */](tensor, shape);
});
return [ops_stack["a" /* stack */](mapped, axis)];
});
}
case 'Unpack': {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
const tensor = Object(utils["d" /* getParamValue */])('tensor', node, tensorMap, context);
return unstack["a" /* unstack */](tensor, axis);
}
case 'Tile': {
const reps = Object(utils["d" /* getParamValue */])('reps', node, tensorMap, context);
return [tile["a" /* tile */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), reps)];
}
case 'Split':
case 'SplitV': {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
const numOrSizeSplits = Object(utils["d" /* getParamValue */])('numOrSizeSplits', node, tensorMap, context);
const tensor = Object(utils["d" /* getParamValue */])('x', node, tensorMap, context);
return ops_split["a" /* split */](tensor, numOrSizeSplits, axis);
}
case 'ScatterNd': {
const indices = Object(utils["d" /* getParamValue */])('indices', node, tensorMap, context);
const values = Object(utils["d" /* getParamValue */])('values', node, tensorMap, context);
const shape = Object(utils["d" /* getParamValue */])('shape', node, tensorMap, context);
return [scatter_nd["a" /* scatterND */](indices, values, shape)];
}
case 'GatherNd': {
const x = Object(utils["d" /* getParamValue */])('x', node, tensorMap, context);
const indices = Object(utils["d" /* getParamValue */])('indices', node, tensorMap, context);
return [gather_nd["a" /* gatherND */](x, indices)];
}
case 'SparseToDense': {
const indices = Object(utils["d" /* getParamValue */])('sparseIndices', node, tensorMap, context);
const shape = Object(utils["d" /* getParamValue */])('outputShape', node, tensorMap, context);
const sparseValues = Object(utils["d" /* getParamValue */])('sparseValues', node, tensorMap, context);
const defaultValue = Object(utils["d" /* getParamValue */])('defaultValue', node, tensorMap, context);
return [sparse_to_dense["a" /* sparseToDense */](indices, sparseValues, shape, sparseValues.dtype === defaultValue.dtype ?
defaultValue :
cast["a" /* cast */](defaultValue, sparseValues.dtype))];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const slice_join_executor_CATEGORY = 'slice_join';
//# sourceMappingURL=slice_join_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/sparse_executor.js
/**
* @license
* Copyright 2021 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
const sparse_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case 'SparseReshape': {
const { outputIndices, outputShape } = ops["md" /* sparse */].sparseReshape(Object(utils["d" /* getParamValue */])('inputIndices', node, tensorMap, context), Object(utils["d" /* getParamValue */])('inputShape', node, tensorMap, context), Object(utils["d" /* getParamValue */])('newShape', node, tensorMap, context));
return [outputIndices, outputShape];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const sparse_executor_CATEGORY = 'convolution';
//# sourceMappingURL=sparse_executor.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/spectral/fft.js
var fft = __webpack_require__(131);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/spectral/ifft.js
var ifft = __webpack_require__(108);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/spectral/rfft.js
var rfft = __webpack_require__(132);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/spectral/irfft.js
var irfft = __webpack_require__(177);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/spectral_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
const spectral_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case 'FFT': {
return [fft["a" /* fft */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
case 'IFFT': {
return [ifft["a" /* ifft */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
case 'RFFT': {
return [rfft["a" /* rfft */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
case 'IRFFT': {
return [irfft["a" /* irfft */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context))];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const spectral_executor_CATEGORY = 'spectral';
//# sourceMappingURL=spectral_executor.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/expand_dims.js
var expand_dims = __webpack_require__(63);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/mirror_pad.js
var mirror_pad = __webpack_require__(167);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/pad.js
var ops_pad = __webpack_require__(56);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/space_to_batch_nd.js
var space_to_batch_nd = __webpack_require__(96);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/batch_to_space_nd.js
var batch_to_space_nd = __webpack_require__(91);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/depth_to_space.js
var depth_to_space = __webpack_require__(159);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/broadcast_to.js
var broadcast_to = __webpack_require__(101);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/executors/transformation_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// tslint:disable-next-line: no-imports-from-dist
const transformation_executor_executeOp = (node, tensorMap, context) => {
switch (node.op) {
case 'Cast': {
return [cast["a" /* cast */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('dtype', node, tensorMap, context))];
}
case 'ExpandDims': {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
return [expand_dims["a" /* expandDims */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), axis)];
}
case 'Squeeze': {
const axis = Object(utils["d" /* getParamValue */])('axis', node, tensorMap, context);
return [squeeze["a" /* squeeze */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), axis)];
}
case 'Reshape': {
return [reshape["a" /* reshape */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('shape', node, tensorMap, context))];
}
case 'MirrorPad': {
return [mirror_pad["a" /* mirrorPad */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('padding', node, tensorMap, context), Object(utils["d" /* getParamValue */])('mode', node, tensorMap, context))];
}
case 'PadV2':
case 'Pad': {
return [ops_pad["a" /* pad */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('padding', node, tensorMap, context), Object(utils["d" /* getParamValue */])('constantValue', node, tensorMap, context))];
}
case 'SpaceToBatchND': {
const blockShape = Object(utils["d" /* getParamValue */])('blockShape', node, tensorMap, context);
const paddings = Object(utils["d" /* getParamValue */])('paddings', node, tensorMap, context);
return [space_to_batch_nd["a" /* spaceToBatchND */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), blockShape, paddings)];
}
case 'BatchToSpaceND': {
const blockShape = Object(utils["d" /* getParamValue */])('blockShape', node, tensorMap, context);
const crops = Object(utils["d" /* getParamValue */])('crops', node, tensorMap, context);
return [batch_to_space_nd["a" /* batchToSpaceND */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), blockShape, crops)];
}
case 'DepthToSpace': {
const blockSize = Object(utils["d" /* getParamValue */])('blockSize', node, tensorMap, context);
const dataFormat = Object(utils["d" /* getParamValue */])('dataFormat', node, tensorMap, context).toUpperCase();
return [depth_to_space["a" /* depthToSpace */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), blockSize, dataFormat)];
}
case 'BroadcastTo': {
return [broadcast_to["a" /* broadcastTo */](Object(utils["d" /* getParamValue */])('x', node, tensorMap, context), Object(utils["d" /* getParamValue */])('shape', node, tensorMap, context))];
}
default:
throw TypeError(`Node type ${node.op} is not implemented`);
}
};
const transformation_executor_CATEGORY = 'transformation';
//# sourceMappingURL=transformation_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/operations/operation_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Executes the op defined by the node object.
* @param node
* @param tensorMap contains tensors for executed nodes and weights
* @param context contains tensors and information for running the current node.
* @param resourceManager Optional. Contains global resources of the model.
*/
function operation_executor_executeOp(node, tensorMap, context, resourceManager) {
const value = ((node, tensorMap, context) => {
switch (node.category) {
case 'arithmetic':
return dist["tidy"](() => executeOp(node, tensorMap, context));
case 'basic_math':
return dist["tidy"](() => basic_math_executor_executeOp(node, tensorMap, context));
case 'control':
return control_executor_executeOp(node, tensorMap, context);
case 'convolution':
return dist["tidy"](() => convolution_executor_executeOp(node, tensorMap, context));
case 'creation':
return dist["tidy"](() => creation_executor_executeOp(node, tensorMap, context));
case 'dynamic':
return dynamic_executor_executeOp(node, tensorMap, context);
case 'evaluation':
return dist["tidy"](() => evaluation_executor_executeOp(node, tensorMap, context));
case 'image':
return dist["tidy"](() => image_executor_executeOp(node, tensorMap, context));
case 'graph':
return dist["tidy"](() => graph_executor_executeOp(node, tensorMap, context));
case 'logical':
return dist["tidy"](() => logical_executor_executeOp(node, tensorMap, context));
case 'matrices':
return dist["tidy"](() => matrices_executor_executeOp(node, tensorMap, context));
case 'normalization':
return dist["tidy"](() => normalization_executor_executeOp(node, tensorMap, context));
case 'reduction':
return dist["tidy"](() => reduction_executor_executeOp(node, tensorMap, context));
case 'slice_join':
return dist["tidy"](() => slice_join_executor_executeOp(node, tensorMap, context));
case 'sparse':
return dist["tidy"](() => sparse_executor_executeOp(node, tensorMap, context));
case 'spectral':
return dist["tidy"](() => spectral_executor_executeOp(node, tensorMap, context));
case 'transformation':
return dist["tidy"](() => transformation_executor_executeOp(node, tensorMap, context));
case 'hash_table':
return hash_table_executor_executeOp(node, tensorMap, context, resourceManager);
case 'custom':
const opMapper = Object(register["b" /* getRegisteredOp */])(node.op);
if (opMapper && opMapper.customExecutor) {
return opMapper.customExecutor(new node_value_impl_NodeValueImpl(node, tensorMap, context));
}
else {
throw TypeError(`Custom op ${node.op} is not registered.`);
}
default:
throw TypeError(`Unknown op '${node.op}'. File an issue at ` +
`https://github.com/tensorflow/tfjs/issues so we can add it` +
`, or register a custom execution with tf.registerOp()`);
}
})(node, tensorMap, context);
if (dist["util"].isPromise(value)) {
return value.then((data) => [].concat(data));
}
return [].concat(value);
}
//# sourceMappingURL=operation_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/executor/execution_context.js
/**
* ExecutionContext captures the runtime environment of the node. It keeps
* track of the current frame and iteration for the control flow ops.
*
* For example, typical Dynamic RNN model may contain loops, for which
* TensorFlow will generate graphs with Enter/Exit nodes to control the
* current execution frame, and NextIteration Nodes for iteration id increment.
* For model with branch logic, TensorFLow will generate Switch/Merge ops.
*/
class ExecutionContext {
constructor(weightMap = {}, tensorArrayMap = {}, tensorListMap = {}, functionMap = {}) {
this.weightMap = weightMap;
this.tensorArrayMap = tensorArrayMap;
this.tensorListMap = tensorListMap;
this.functionMap = functionMap;
this.rootContext = { id: 0, frameName: '', iterationId: 0 };
this.contexts = [this.rootContext];
this.lastId = 0;
this.generateCurrentContextIds();
}
newFrame(id, frameName) {
return { id, frameName, iterationId: 0 };
}
/**
* Set the current context
* @param contexts: ExecutionContextInfo[] the current path of execution
* frames
*/
set currentContext(contexts) {
if (this.contexts !== contexts) {
this.contexts = contexts;
this.generateCurrentContextIds();
}
}
get currentContext() {
return this.contexts;
}
/**
* Returns the current context in string format.
*/
get currentContextId() {
return this._currentContextIds[0];
}
/**
* Returns the current context and all parent contexts in string format.
* This allow access to the nodes in the current and parent frames.
*/
get currentContextIds() {
return this._currentContextIds;
}
generateCurrentContextIds() {
const names = [];
for (let i = 0; i < this.contexts.length - 1; i++) {
const contexts = this.contexts.slice(0, this.contexts.length - i);
names.push(this.contextIdforContexts(contexts));
}
names.push('');
this._currentContextIds = names;
}
contextIdforContexts(contexts) {
return contexts ?
contexts
.map(context => (context.id === 0 && context.iterationId === 0) ?
'' :
`${context.frameName}-${context.iterationId}`)
.join('/') :
'';
}
/**
* Enter a new frame, a new context is pushed on the current context list.
* @param frameId new frame id
*/
enterFrame(frameId) {
if (this.contexts) {
this.lastId++;
this.contexts = this.contexts.slice();
this.contexts.push(this.newFrame(this.lastId, frameId));
this._currentContextIds.unshift(this.contextIdforContexts(this.contexts));
}
}
/**
* Exit the current frame, the last context is removed from the current
* context list.
*/
exitFrame() {
if (this.contexts && this.contexts.length > 1) {
this.contexts = this.contexts.slice();
this.contexts.splice(-1);
this.currentContextIds.shift();
}
else {
throw new Error('Cannot exit frame, the context is empty');
}
}
/**
* Enter the next iteration of a loop, the iteration id of last context is
* increased.
*/
nextIteration() {
if (this.contexts && this.contexts.length > 0) {
this.contexts = this.contexts.slice();
this.lastId++;
const context = Object.assign({}, this.contexts[this.contexts.length - 1]);
context.iterationId += 1;
context.id = this.lastId;
this.contexts.splice(-1, 1, context);
this._currentContextIds.splice(0, 1, this.contextIdforContexts(this.contexts));
}
else {
throw new Error('Cannot increase frame iteration, the context is empty');
}
}
getWeight(name) {
return this.weightMap[name];
}
addTensorArray(tensorArray) {
this.tensorArrayMap[tensorArray.id] = tensorArray;
}
getTensorArray(id) {
return this.tensorArrayMap[id];
}
addTensorList(tensorList) {
this.tensorListMap[tensorList.id] = tensorList;
}
getTensorList(id) {
return this.tensorListMap[id];
}
dispose(keepIds) {
for (const key in this.tensorArrayMap) {
this.tensorArrayMap[key].clearAndClose(keepIds);
}
for (const key in this.tensorListMap) {
this.tensorListMap[key].clearAndClose(keepIds);
}
}
}
//# sourceMappingURL=execution_context.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/executor/model_analysis.js
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Given graph inputs and desired outputs, find the minimal set of nodes
* to execute in order to compute the outputs. In addition return other useful
* info such:
* - Missing inputs needed to compute the output.
* - Whether the subgraph contains dynamic ops (control flow, dynamic shape).
* - Alternative inputs in order to avoid async (dynamic op) execution.
*/
function getExecutionSubgraph(inputs, outputs, weightMap, initNodes) {
const usedNodes = new Set();
const missingInputs = [];
let dynamicNode = null;
let syncInputs = null;
// Start with the outputs, going backwards and find all the nodes that are
// needed to compute those outputs.
const seen = new Set();
const inputNodeNames = Object.keys(inputs).map(name => Object(utils["g" /* parseNodeName */])(name)[0]);
let initNodeNames = [];
if (initNodes != null) {
initNodeNames = initNodes.map(node => Object(utils["g" /* parseNodeName */])(node.name)[0]);
}
const frontier = [...outputs];
while (frontier.length > 0) {
const node = frontier.pop();
if (isControlFlow(node) || isDynamicShape(node) || isHashTable(node)) {
if (dynamicNode == null) {
dynamicNode = node;
syncInputs = dynamicNode.children.map(child => child.name)
.filter(name => usedNodes.has(name));
}
}
usedNodes.add(node.name);
// Weights are dead end since we already have their values.
if (weightMap[node.name] != null) {
continue;
}
// This node is a dead end since it's one of the user-provided inputs.
if (inputNodeNames.indexOf(node.name) !== -1) {
continue;
}
// This node is a dead end since it doesn't have any inputs.
if (initNodeNames.indexOf(node.name) !== -1) {
continue;
}
if (node.inputs.length === 0) {
missingInputs.push(node.name);
continue;
}
node.inputs.forEach(input => {
// Don't add to the frontier if it is already there.
if (seen.has(input.name)) {
return;
}
seen.add(input.name);
frontier.push(input);
});
}
return { inputs, outputs, usedNodes, missingInputs, dynamicNode, syncInputs };
}
/**
* Given the execution info, return a list of nodes in topological order that
* need to be executed to compute the output.
*/
function getNodesInTopologicalOrder(graph, weightMap, executionInfo) {
const { usedNodes, inputs } = executionInfo;
const frontier = [];
const inputNodes = Object.keys(inputs)
.map(name => Object(utils["g" /* parseNodeName */])(name)[0])
.map(name => graph.nodes[name]);
const initNodes = graph.initNodes;
inputNodes.forEach(input => {
if (usedNodes.has(input.name)) {
frontier.push(input);
}
});
graph.weights.forEach(weight => {
if (usedNodes.has(weight.name)) {
frontier.push(weight);
}
});
if (initNodes != null) {
initNodes.forEach(node => {
if (usedNodes.has(node.name)) {
frontier.push(node);
}
});
}
const seen = new Set();
const orderedNodes = [];
while (frontier.length > 0) {
const node = frontier.pop();
seen.add(node.name);
if (!weightMap[node.name]) {
orderedNodes.push(node);
}
node.children.forEach(child => {
if (!seen.has(child.name) && usedNodes.has(child.name) &&
child.inputs.every(input => seen.has(input.name))) {
frontier.push(child);
}
});
}
return orderedNodes;
}
const CONTROL_FLOW_OPS = [
'Switch', 'Merge', 'Enter', 'Exit', 'NextIteration', 'StatelessIf',
'StatelessWhile', 'if', 'While'
];
const DYNAMIC_SHAPE_OPS = [
'NonMaxSuppressionV2', 'NonMaxSuppressionV3', 'NonMaxSuppressionV5', 'Where'
];
const HASH_TABLE_OPS = [
'HashTable', 'HashTableV2', 'LookupTableImport', 'LookupTableImportV2',
'LookupTableFind', 'LookupTableFindV2', 'LookupTableSize', 'LookupTableSizeV2'
];
function isControlFlow(node) {
return CONTROL_FLOW_OPS.indexOf(node.op) >= 0;
}
function isDynamicShape(node) {
return DYNAMIC_SHAPE_OPS.indexOf(node.op) >= 0;
}
function isHashTable(node) {
return HASH_TABLE_OPS.indexOf(node.op) >= 0;
}
//# sourceMappingURL=model_analysis.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/executor/graph_executor.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class graph_executor_GraphExecutor {
/**
*
* @param graph Graph the model or function graph to be executed.
* @param parent When building function exector you need to set the parent
* executor. Since the weights and function executor maps are set at parant
* level, that function executor can access the function maps and weight maps
* through the parent.
*/
constructor(graph, parent) {
this.graph = graph;
this.parent = parent;
this.compiledMap = new Map();
this._weightMap = {};
this.SEPERATOR = ',';
this._functions = {};
this._functionExecutorMap = {};
this._outputs = graph.outputs;
this._inputs = graph.inputs;
this._initNodes = graph.initNodes;
this._signature = graph.signature;
this._functions = graph.functions;
// create sub-graph executors
if (graph.functions != null) {
Object.keys(graph.functions).forEach(name => {
this._functionExecutorMap[name] =
new graph_executor_GraphExecutor(graph.functions[name], this);
});
}
}
get weightIds() {
return this.parent ? this.parent.weightIds : this._weightIds;
}
get functionExecutorMap() {
return this.parent ? this.parent.functionExecutorMap :
this._functionExecutorMap;
}
get weightMap() {
return this.parent ? this.parent.weightMap : this._weightMap;
}
set weightMap(weightMap) {
const weightIds = Object.keys(weightMap).map(key => weightMap[key].map(tensor => tensor.id));
this._weightIds = [].concat(...weightIds);
this._weightMap = weightMap;
}
/**
* Set `ResourceManager` shared by executors of a model.
* @param resourceManager: `ResourceManager` of the `GraphModel`.
*/
set resourceManager(resourceManager) {
this._resourceManager = resourceManager;
}
get inputs() {
return this._inputs.map(node => {
return {
name: node.name,
shape: node.attrParams['shape'] ?
node.attrParams['shape'].value :
undefined,
dtype: node.attrParams['dtype'] ?
node.attrParams['dtype'].value :
undefined
};
});
}
get outputs() {
return this._outputs.map(node => {
return {
name: node.name,
shape: node.attrParams['shape'] ?
node.attrParams['shape'].value :
undefined,
dtype: node.attrParams['dtype'] ?
node.attrParams['dtype'].value :
undefined
};
});
}
get inputNodes() {
return this._inputs.map(node => node.signatureKey || node.name);
}
get outputNodes() {
return this._outputs.map((node) => {
const name = node.signatureKey || node.name;
return node.defaultOutput ? (`${name}:${node.defaultOutput}`) : name;
});
}
get functions() {
return Object.keys(this._functions).reduce((map, key) => {
map[key] = this._functions[key].signature;
return map;
}, {});
}
getCompilationKey(inputs, outputs) {
const sortedInputs = inputs.map(node => node.name).sort();
const sortedOutputs = outputs.map(node => node.name).sort();
return sortedInputs.join(this.SEPERATOR) + '--' +
sortedOutputs.join(this.SEPERATOR);
}
/**
* Compiles the inference graph and returns the minimal set of nodes that are
* required for execution, in the correct execution order.
*/
compile(inputs, outputs) {
const executionInfo = getExecutionSubgraph(inputs, outputs, this.weightMap, this._initNodes);
const { missingInputs, dynamicNode, syncInputs } = executionInfo;
if (dynamicNode != null) {
throw new Error(`This execution contains the node '${dynamicNode.name}', which has ` +
`the dynamic op '${dynamicNode.op}'. Please use ` +
`model.executeAsync() instead. Alternatively, to avoid the ` +
`dynamic ops, specify the inputs [${syncInputs}]`);
}
if (missingInputs.length > 0) {
const outNames = outputs.map(n => n.name);
const inNames = Object.keys(inputs);
throw new Error(`Cannot compute the outputs [${outNames}] from the provided inputs ` +
`[${inNames}]. Missing the following inputs: [${missingInputs}]`);
}
return getNodesInTopologicalOrder(this.graph, this.weightMap, executionInfo);
}
/**
* Executes the inference for given input tensors.
* @param inputs Tensor map for the model inputs, keyed by the input node
* names.
* @param outputs Optional. output node name from the Tensorflow model, if
* no outputs are specified, the default outputs of the model would be used.
* You can inspect intermediate nodes of the model by adding them to the
* outputs array.
*/
execute(inputs, outputs) {
inputs = this.mapInputs(inputs);
const names = Object.keys(inputs).sort();
this.checkInputs(inputs);
this.checkInputShapeAndType(inputs);
outputs = this.mapOutputs(outputs);
this.checkOutputs(outputs);
const inputNodes = names.map(name => this.graph.nodes[Object(utils["g" /* parseNodeName */])(name)[0]]);
const outputNodeNames = outputs.map(name => Object(utils["g" /* parseNodeName */])(name)[0]);
let outputNodes = outputNodeNames.map(name => this.graph.nodes[name]);
// If no outputs are specified, then use the default outputs of the model.
if (outputNodes.length === 0) {
outputNodes = this._outputs;
}
const compilationKey = this.getCompilationKey(inputNodes, outputNodes);
// Do nothing if the compiled graph cache contains the input.
let orderedNodes = this.compiledMap.get(compilationKey);
if (orderedNodes == null) {
orderedNodes = this.compile(inputs, outputNodes);
this.compiledMap.set(compilationKey, orderedNodes);
}
const tensorArrayMap = {};
const tensorListMap = {};
return Object(dist["tidy"])(() => {
const context = new ExecutionContext(this.weightMap, tensorArrayMap, tensorListMap, this.functionExecutorMap);
const tensorsMap = Object.assign({}, this.weightMap);
Object.keys(inputs).forEach(name => {
const [nodeName, index] = Object(utils["g" /* parseNodeName */])(name);
const tensors = [];
tensors[index] = inputs[name];
tensorsMap[nodeName] = tensors;
});
const tensorsToKeep = this.getFrozenTensorIds(tensorsMap);
const intermediateTensorConsumerCount = {};
for (let i = 0; i < orderedNodes.length; i++) {
const node = orderedNodes[i];
if (!tensorsMap[node.name]) {
const tensors = operation_executor_executeOp(node, tensorsMap, context, this._resourceManager);
if (dist["util"].isPromise(tensors)) {
throw new Error(`The execution of the op '${node.op}' returned a promise. ` +
`Please use model.executeAsync() instead.`);
}
tensorsMap[node.name] = tensors;
this.checkTensorForDisposal(node.name, node, tensorsMap, context, tensorsToKeep, outputNodeNames, intermediateTensorConsumerCount);
}
}
// dispose the context for the root executor
if (this.parent == null) {
context.dispose(tensorsToKeep);
}
return outputs.map(name => Object(utils["e" /* getTensor */])(name, tensorsMap, context));
});
}
getFrozenTensorIds(tensorMap) {
const ids = [].concat.apply([], Object.keys(tensorMap)
.map(key => tensorMap[key])
.map(tensors => tensors.map(tensor => tensor.id)));
return new Set(ids);
}
checkTensorForDisposal(nodeName, node, tensorMap, context, tensorsToKeep, outputNames, intermediateTensorConsumerCount) {
// Skip output nodes and any control flow nodes, since its dependency is
// tricky to track correctly.
if (node.category === 'control' || outputNames.indexOf(nodeName) !== -1) {
return;
}
tensorMap[nodeName].forEach(tensor => {
if (tensor != null) {
intermediateTensorConsumerCount[tensor.id] =
(intermediateTensorConsumerCount[tensor.id] || 0) +
node.children.length;
}
});
node.inputs.forEach(input => {
// Skip any control flow nodes, since its dependency is tricky to track
// correctly.
if (input.category !== 'control') {
const tensors = Object(utils["f" /* getTensorsForCurrentContenxt */])(input.name, tensorMap, context);
if (tensors != null) {
tensors.forEach(tensor => {
if (tensor && !tensor.kept && !tensorsToKeep.has(tensor.id)) {
const count = intermediateTensorConsumerCount[tensor.id];
if (count === 1) {
tensor.dispose();
delete intermediateTensorConsumerCount[tensor.id];
}
else if (count != null) {
// only intermediate nodes has count set, inputs and weights are
// not.
intermediateTensorConsumerCount[tensor.id]--;
}
}
});
}
}
});
}
/**
* Executes the inference for given input tensors in Async fashion.
* @param inputs Tensor map for the model inputs, keyed by the input node
* names.
* @param outputs output node name from the Tensorflow model, if no outputs
* are specified, the default outputs of the model would be used. You can
* inspect intermediate nodes of the model by adding them to the outputs
* array.
*/
async executeAsync(inputs, outputs) {
return this._executeAsync(inputs, outputs);
}
/**
* Executes the inference for given input tensors in Async fashion.
* @param inputs Tensor map for the model inputs, keyed by the input node
* names.
* @param outputs Optional. output node name from the Tensorflow model,
* if no outputs are specified, the default outputs of the model would be
* used. You can inspect intermediate nodes of the model by adding them to the
* outputs array.
* @param isFunctionExecution Optional. Flag for executing a function.
* @param tensorArrayMap Optional, global TensorArray map by id. Used for
* function execution.
* @param tensorArrayMap Optinal global TensorList map by id. Used for
* function execution.
*/
async _executeAsync(inputs, outputs, isFunctionExecution = false, tensorArrayMap = {}, tensorListMap = {}) {
if (!isFunctionExecution) {
inputs = this.mapInputs(inputs);
this.checkInputs(inputs);
this.checkInputShapeAndType(inputs);
outputs = this.mapOutputs(outputs);
this.checkOutputs(outputs);
}
const context = new ExecutionContext(this.weightMap, tensorArrayMap, tensorListMap, this.functionExecutorMap);
// Graph with control flow op requires runtime evaluation of the execution
// order, while without control flow the execution order is pre-determined
// in the compile method.
const tensorMap = await this.executeWithControlFlow(inputs, context, outputs, isFunctionExecution);
const results = outputs.map(name => Object(utils["e" /* getTensor */])(name, tensorMap, context));
// dispose all the intermediate tensors
const outputIds = results.map(t => t.id);
const inputIds = Object.keys(inputs).map(name => inputs[name].id);
const keepIds = new Set([...outputIds, ...inputIds, ...this.weightIds]);
Object.keys(tensorMap).forEach(key => {
const tensorArray = tensorMap[key];
tensorArray.forEach(tensor => {
if (tensor && !tensor.kept && !tensor.isDisposed &&
!keepIds.has(tensor.id)) {
tensor.dispose();
}
});
});
// dispose the context for the root executor
if (this.parent == null) {
context.dispose(keepIds);
}
return results;
}
async executeFunctionAsync(inputs, tensorArrayMap, tensorListMap) {
const mappedInputs = inputs.reduce((map, tensor, index) => {
map[this.inputs[index].name] = tensor;
return map;
}, {});
return this._executeAsync(mappedInputs, this.outputNodes, true, tensorArrayMap, tensorListMap);
}
/**
* When there are control flow nodes in the graph, the graph execution use
* ExecutionContext to keep track of the frames and loop iterators.
* @param inputs placeholder tensors for the graph.
* @param context the execution context object for current execution.
* @param outputNames Optional. output node name from the Tensorflow model,
* if no outputs are specified, the default outputs of the model would be
* used. You can inspect intermediate nodes of the model by adding them to the
* outputs array.
* @param isFunctionExecution Flag for executing a function.
*/
async executeWithControlFlow(inputs, context, outputNames, isFunctionExecution) {
const names = Object.keys(inputs);
const inputNodes = names.map(name => this.graph.nodes[Object(utils["g" /* parseNodeName */])(name)[0]]);
const outputNodeNames = outputNames.map(name => Object(utils["g" /* parseNodeName */])(name)[0]);
let outputNodes = outputNodeNames.map(name => this.graph.nodes[name]);
// If no outputs are specified, then use the default outputs of the model.
if (outputNodes.length === 0) {
outputNodes = this._outputs;
}
const { usedNodes, missingInputs, dynamicNode, syncInputs } = getExecutionSubgraph(inputs, outputNodes, this.weightMap, this._initNodes);
// First nodes to execute include inputNodes, weights, and initNodes.
const stack = [
...inputNodes, ...this.graph.weights, ...(this._initNodes || [])
].map(node => {
return { node, contexts: context.currentContext };
});
const tensorsMap = Object.assign({}, this.weightMap);
Object.keys(inputs).forEach(name => {
const [nodeName, index] = Object(utils["g" /* parseNodeName */])(name);
const tensors = [];
tensors[index] = inputs[name];
tensorsMap[nodeName] = tensors;
});
const intermediateTensorConsumerCount = {};
const tensorsToKeep = this.getFrozenTensorIds(tensorsMap);
const added = {};
while (stack.length > 0) {
const promises = this.processStack(inputNodes, stack, context, tensorsMap, added, tensorsToKeep, outputNodeNames, intermediateTensorConsumerCount, usedNodes);
await Promise.all(promises);
}
if (dynamicNode == null && !isFunctionExecution) {
console.warn(`This model execution did not contain any nodes with control flow ` +
`or dynamic output shapes. You can use model.execute() instead.`);
}
const missingOutputs = outputNodes
.filter(node => !isControlFlow(node) &&
!Object(utils["e" /* getTensor */])(node.name, tensorsMap, context))
.map(node => node.name);
if (missingOutputs.length > 0) {
let alternativeMsg = '';
if (dynamicNode != null) {
alternativeMsg =
`Alternatively, to avoid the dynamic ops, use model.execute() ` +
`and specify the inputs [${syncInputs}]`;
}
throw new Error(`Cannot compute the outputs [${missingOutputs}] from the provided ` +
`inputs [${names}]. Consider providing the following inputs: ` +
`[${missingInputs}]. ${alternativeMsg}`);
}
return tensorsMap;
}
processStack(inputNodes, stack, context, tensorMap, added, tensorsToKeep, outputNames, intermediateTensorConsumerCount, usedNodes) {
const promises = [];
while (stack.length > 0) {
const item = stack.pop();
context.currentContext = item.contexts;
let nodeName = '';
// The tensor of the Enter op with isConstant set should be set
// in the parent scope, so it will be available as constant for the
// whole loop.
if (item.node.op === 'Enter' &&
Object(utils["d" /* getParamValue */])('isConstant', item.node, tensorMap, context)) {
[nodeName] = Object(utils["b" /* getNodeNameAndIndex */])(item.node.name, context);
}
// only process nodes that are not in the tensorMap yet, this include
// inputNodes and internal initNodes.
if (tensorMap[item.node.name] == null) {
const tensors = operation_executor_executeOp(item.node, tensorMap, context, this._resourceManager);
if (!nodeName) {
[nodeName] = Object(utils["b" /* getNodeNameAndIndex */])(item.node.name, context);
}
const currentContext = context.currentContext;
if (dist["util"].isPromise(tensors)) {
promises.push(tensors.then(t => {
tensorMap[nodeName] = t;
context.currentContext = currentContext;
this.checkTensorForDisposal(nodeName, item.node, tensorMap, context, tensorsToKeep, outputNames, intermediateTensorConsumerCount);
this.processChildNodes(item.node, stack, context, tensorMap, added, usedNodes);
return t;
}));
}
else {
tensorMap[nodeName] = tensors;
this.checkTensorForDisposal(nodeName, item.node, tensorMap, context, tensorsToKeep, outputNames, intermediateTensorConsumerCount);
this.processChildNodes(item.node, stack, context, tensorMap, added, usedNodes);
}
}
else {
this.processChildNodes(item.node, stack, context, tensorMap, added, usedNodes);
}
}
return promises;
}
processChildNodes(node, stack, context, tensorMap, added, usedNodes) {
node.children.forEach((childNode) => {
const [nodeName,] = Object(utils["b" /* getNodeNameAndIndex */])(childNode.name, context);
if (added[nodeName] || !usedNodes.has(childNode.name)) {
return;
}
// Merge op can be pushed if any of its inputs has value.
if (childNode.op === 'Merge') {
if (childNode.inputNames.some(name => {
return !!Object(utils["e" /* getTensor */])(name, tensorMap, context);
})) {
added[nodeName] = true;
stack.push({ contexts: context.currentContext, node: childNode });
}
}
else // Otherwise all inputs must to have value.
if (childNode.inputNames.every(name => {
return !!Object(utils["e" /* getTensor */])(name, tensorMap, context);
})) {
added[nodeName] = true;
stack.push({ contexts: context.currentContext, node: childNode });
}
});
}
/**
* Releases the memory used by the weight tensors.
*/
dispose() {
Object.keys(this.weightMap)
.forEach(key => this.weightMap[key].forEach(tensor => tensor.dispose()));
}
checkInputShapeAndType(inputs) {
Object.keys(inputs).forEach(name => {
const input = inputs[name];
const [nodeName,] = Object(utils["g" /* parseNodeName */])(name);
const node = this.graph.nodes[nodeName];
if (node.attrParams['shape'] && node.attrParams['shape'].value) {
const shape = node.attrParams['shape'].value;
const match = shape.length === input.shape.length &&
input.shape.every((dim, index) => shape[index] === -1 || shape[index] === dim);
dist["util"].assert(match, () => `The shape of dict['${node.name}'] provided in ` +
`model.execute(dict) must be [${shape}], but was ` +
`[${input.shape}]`);
}
if (node.attrParams['dtype'] && node.attrParams['dtype'].value) {
dist["util"].assert(input.dtype === node.attrParams['dtype'].value, () => `The dtype of dict['${node.name}'] provided in ` +
`model.execute(dict) must be ` +
`${node.attrParams['dtype'].value}, but was ${input.dtype}`);
}
});
}
mapInputs(inputs) {
const result = {};
for (const inputName in inputs) {
if (this._signature != null && this._signature.inputs != null &&
this._signature.inputs[inputName] != null) {
const tensor = this._signature.inputs[inputName];
result[tensor.name] = inputs[inputName];
}
else {
result[inputName] = inputs[inputName];
}
}
return result;
}
checkInputs(inputs) {
const notInGraph = Object.keys(inputs).filter(name => {
const [nodeName] = Object(utils["g" /* parseNodeName */])(name);
return this.graph.nodes[nodeName] == null;
});
if (notInGraph.length > 0) {
throw new Error(`The dict provided in model.execute(dict) has ` +
`keys: [${notInGraph}] that are not part of graph`);
}
}
mapOutputs(outputs) {
return outputs.map(name => {
if (this._signature != null && this._signature.outputs != null &&
this._signature.outputs[name] != null) {
const tensor = this._signature.outputs[name];
return tensor.name;
}
return name;
}, {});
}
checkOutputs(outputs) {
outputs.forEach(name => {
const [normalizedName] = Object(utils["g" /* parseNodeName */])(name);
if (!this.graph.nodes[normalizedName]) {
throw new Error(`The output '${name}' is not found in the graph`);
}
});
}
}
//# sourceMappingURL=graph_executor.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/executor/resource_manager.js
/**
* Contains global resources of a model.
*/
class ResourceManager {
constructor(hashTableNameToHandle = {}, hashTableMap = {}) {
this.hashTableNameToHandle = hashTableNameToHandle;
this.hashTableMap = hashTableMap;
}
/**
* Register a `HashTable` in the resource manager.
*
* The `HashTable` can be retrieved by `resourceManager.getHashTableById`,
* where id is the table handle tensor's id.
*
* @param name Op node name that creates the `HashTable`.
* @param hashTable The `HashTable` to be added to resource manager.
*/
addHashTable(name, hashTable) {
this.hashTableNameToHandle[name] = hashTable.handle;
this.hashTableMap[hashTable.id] = hashTable;
}
/**
* Get the table handle by node name.
* @param name Op node name that creates the `HashTable`. This name is also
* used in the inputs list of lookup and import `HashTable` ops.
*/
getHashTableHandleByName(name) {
return this.hashTableNameToHandle[name];
}
/**
* Get the actual `HashTable` by its handle tensor's id.
* @param id The id of the handle tensor.
*/
getHashTableById(id) {
return this.hashTableMap[id];
}
/**
* Dispose `ResourceManager`, including its hashTables and tensors in them.
*/
dispose() {
for (const key in this.hashTableMap) {
this.hashTableMap[key].clearAndClose();
delete this.hashTableMap[key];
}
for (const name in this.hashTableNameToHandle) {
this.hashTableNameToHandle[name].dispose();
delete this.hashTableNameToHandle[name];
}
}
}
//# sourceMappingURL=resource_manager.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/executor/graph_model.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const TFHUB_SEARCH_PARAM = '?tfjs-format=file';
const DEFAULT_MODEL_NAME = 'model.json';
/**
* A `tf.GraphModel` is a directed, acyclic graph built from a
* SavedModel GraphDef and allows inference execution.
*
* A `tf.GraphModel` can only be created by loading from a model converted from
* a [TensorFlow SavedModel](https://www.tensorflow.org/guide/saved_model) using
* the command line converter tool and loaded via `tf.loadGraphModel`.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
class graph_model_GraphModel {
/**
* @param modelUrl url for the model, or an `io.IOHandler`.
* @param weightManifestUrl url for the weight file generated by
* scripts/convert.py script.
* @param requestOption options for Request, which allows to send credentials
* and custom headers.
* @param onProgress Optional, progress callback function, fired periodically
* before the load is completed.
*/
constructor(modelUrl, loadOptions = {}) {
this.modelUrl = modelUrl;
this.loadOptions = loadOptions;
this.version = 'n/a';
if (loadOptions == null) {
this.loadOptions = {};
}
this.resourceManager = new ResourceManager();
}
// Returns the version information for the tensorflow model GraphDef.
get modelVersion() {
return this.version;
}
get inputNodes() {
return this.executor.inputNodes;
}
get outputNodes() {
return this.executor.outputNodes;
}
get inputs() {
return this.executor.inputs;
}
get outputs() {
return this.executor.outputs;
}
get weights() {
return this.executor.weightMap;
}
get metadata() {
return this.artifacts.userDefinedMetadata;
}
get modelSignature() {
return this.signature;
}
findIOHandler() {
const path = this.modelUrl;
if (path.load != null) {
// Path is an IO Handler.
this.handler = path;
}
else if (this.loadOptions.requestInit != null) {
this.handler = dist["io"].browserHTTPRequest(path, this.loadOptions);
}
else {
const handlers = dist["io"].getLoadHandlers(path, this.loadOptions);
if (handlers.length === 0) {
// For backward compatibility: if no load handler can be found,
// assume it is a relative http path.
handlers.push(dist["io"].browserHTTPRequest(path, this.loadOptions));
}
else if (handlers.length > 1) {
throw new Error(`Found more than one (${handlers.length}) load handlers for ` +
`URL '${[path]}'`);
}
this.handler = handlers[0];
}
}
/**
* Loads the model and weight files, construct the in memory weight map and
* compile the inference graph.
*/
async load() {
this.findIOHandler();
if (this.handler.load == null) {
throw new Error('Cannot proceed with model loading because the IOHandler provided ' +
'does not have the `load` method implemented.');
}
const artifacts = await this.handler.load();
return this.loadSync(artifacts);
}
/**
* Synchronously construct the in memory weight map and
* compile the inference graph. Also initialize hashtable if any.
*
* @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}
*/
loadSync(artifacts) {
this.artifacts = artifacts;
const graph = this.artifacts.modelTopology;
let signature;
if (this.artifacts.userDefinedMetadata != null &&
this.artifacts.userDefinedMetadata.signature != null) {
signature = // tslint:disable-next-line:no-any
this.artifacts.userDefinedMetadata.signature;
}
else {
signature = this.artifacts.signature;
}
this.signature = signature;
this.version = `${graph.versions.producer}.${graph.versions.minConsumer}`;
const weightMap = dist["io"].decodeWeights(this.artifacts.weightData, this.artifacts.weightSpecs);
this.executor = new graph_executor_GraphExecutor(operation_mapper["a" /* OperationMapper */].Instance.transformGraph(graph, this.signature));
this.executor.weightMap = this.convertTensorMapToTensorsMap(weightMap);
// Attach a model-level resourceManager to each executor to share resources,
// such as `HashTable`.
this.executor.resourceManager = this.resourceManager;
if (artifacts.modelInitializer != null &&
artifacts.modelInitializer.node != null) {
const initializer = operation_mapper["a" /* OperationMapper */].Instance.transformGraph(artifacts.modelInitializer);
this.initializer = new graph_executor_GraphExecutor(initializer);
this.initializer.weightMap = this.executor.weightMap;
// Attach a model-level resourceManager to the initializer, the
// hashTables created from when executing the initializer will be stored
// in the resourceManager.
this.initializer.resourceManager = this.resourceManager;
this.initializer.executeAsync({}, []);
}
return true;
}
/**
* Save the configuration and/or weights of the GraphModel.
*
* An `IOHandler` is an object that has a `save` method of the proper
* signature defined. The `save` method manages the storing or
* transmission of serialized data ("artifacts") that represent the
* model's topology and weights onto or via a specific medium, such as
* file downloads, local storage, IndexedDB in the web browser and HTTP
* requests to a server. TensorFlow.js provides `IOHandler`
* implementations for a number of frequently used saving mediums, such as
* `tf.io.browserDownloads` and `tf.io.browserLocalStorage`. See `tf.io`
* for more details.
*
* This method also allows you to refer to certain types of `IOHandler`s
* as URL-like string shortcuts, such as 'localstorage://' and
* 'indexeddb://'.
*
* Example 1: Save `model`'s topology and weights to browser [local
* storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage);
* then load it back.
*
* ```js
* const modelUrl =
* 'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';
* const model = await tf.loadGraphModel(modelUrl);
* const zeros = tf.zeros([1, 224, 224, 3]);
* model.predict(zeros).print();
*
* const saveResults = await model.save('localstorage://my-model-1');
*
* const loadedModel = await tf.loadGraphModel('localstorage://my-model-1');
* console.log('Prediction from loaded model:');
* model.predict(zeros).print();
* ```
*
* @param handlerOrURL An instance of `IOHandler` or a URL-like,
* scheme-based string shortcut for `IOHandler`.
* @param config Options for saving the model.
* @returns A `Promise` of `SaveResult`, which summarizes the result of
* the saving, such as byte sizes of the saved artifacts for the model's
* topology and weight values.
*
* @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}
*/
async save(handlerOrURL, config) {
if (typeof handlerOrURL === 'string') {
const handlers = dist["io"].getSaveHandlers(handlerOrURL);
if (handlers.length === 0) {
throw new Error(`Cannot find any save handlers for URL '${handlerOrURL}'`);
}
else if (handlers.length > 1) {
throw new Error(`Found more than one (${handlers.length}) save handlers for ` +
`URL '${handlerOrURL}'`);
}
handlerOrURL = handlers[0];
}
if (handlerOrURL.save == null) {
throw new Error('GraphModel.save() cannot proceed because the IOHandler ' +
'provided does not have the `save` attribute defined.');
}
return handlerOrURL.save(this.artifacts);
}
/**
* Execute the inference for the input tensors.
*
* @param input The input tensors, when there is single input for the model,
* inputs param should be a `tf.Tensor`. For models with mutliple inputs,
* inputs params should be in either `tf.Tensor`[] if the input order is
* fixed, or otherwise NamedTensorMap format.
*
* For model with multiple inputs, we recommend you use NamedTensorMap as the
* input type, if you use `tf.Tensor`[], the order of the array needs to
* follow the
* order of inputNodes array. @see {@link GraphModel.inputNodes}
*
* You can also feed any intermediate nodes using the NamedTensorMap as the
* input type. For example, given the graph
* InputNode => Intermediate => OutputNode,
* you can execute the subgraph Intermediate => OutputNode by calling
* model.execute('IntermediateNode' : tf.tensor(...));
*
* This is useful for models that uses tf.dynamic_rnn, where the intermediate
* state needs to be fed manually.
*
* For batch inference execution, the tensors for each input need to be
* concatenated together. For example with mobilenet, the required input shape
* is [1, 244, 244, 3], which represents the [batch, height, width, channel].
* If we are provide a batched data of 100 images, the input tensor should be
* in the shape of [100, 244, 244, 3].
*
* @param config Prediction configuration for specifying the batch size and
* output node names. Currently the batch size option is ignored for graph
* model.
*
* @returns Inference result tensors. The output would be single `tf.Tensor`
* if model has single output node, otherwise Tensor[] or NamedTensorMap[]
* will be returned for model with multiple outputs.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
predict(inputs, config) {
return this.execute(inputs, this.outputNodes);
}
normalizeInputs(inputs) {
if (!(inputs instanceof dist["Tensor"]) && !Array.isArray(inputs)) {
// The input is already a NamedTensorMap.
return inputs;
}
inputs = Array.isArray(inputs) ? inputs : [inputs];
if (inputs.length !== this.inputNodes.length) {
throw new Error('Input tensor count mismatch,' +
`the graph model has ${this.inputNodes.length} placeholders, ` +
`while there are ${inputs.length} input tensors.`);
}
return this.inputNodes.reduce((map, inputName, i) => {
map[inputName] = inputs[i];
return map;
}, {});
}
normalizeOutputs(outputs) {
outputs = outputs || this.outputNodes;
return !Array.isArray(outputs) ? [outputs] : outputs;
}
/**
* Executes inference for the model for given input tensors.
* @param inputs tensor, tensor array or tensor map of the inputs for the
* model, keyed by the input node names.
* @param outputs output node name from the Tensorflow model, if no
* outputs are specified, the default outputs of the model would be used.
* You can inspect intermediate nodes of the model by adding them to the
* outputs array.
*
* @returns A single tensor if provided with a single output or no outputs
* are provided and there is only one default output, otherwise return a
* tensor array. The order of the tensor array is the same as the outputs
* if provided, otherwise the order of outputNodes attribute of the model.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
execute(inputs, outputs) {
inputs = this.normalizeInputs(inputs);
outputs = this.normalizeOutputs(outputs);
const result = this.executor.execute(inputs, outputs);
return result.length > 1 ? result : result[0];
}
/**
* Executes inference for the model for given input tensors in async
* fashion, use this method when your model contains control flow ops.
* @param inputs tensor, tensor array or tensor map of the inputs for the
* model, keyed by the input node names.
* @param outputs output node name from the Tensorflow model, if no outputs
* are specified, the default outputs of the model would be used. You can
* inspect intermediate nodes of the model by adding them to the outputs
* array.
*
* @returns A Promise of single tensor if provided with a single output or
* no outputs are provided and there is only one default output, otherwise
* return a tensor map.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
async executeAsync(inputs, outputs) {
inputs = this.normalizeInputs(inputs);
outputs = this.normalizeOutputs(outputs);
const result = await this.executor.executeAsync(inputs, outputs);
return result.length > 1 ? result : result[0];
}
convertTensorMapToTensorsMap(map) {
return Object.keys(map).reduce((newMap, key) => {
newMap[key] = [map[key]];
return newMap;
}, {});
}
/**
* Releases the memory used by the weight tensors and resourceManager.
*
* @doc {heading: 'Models', subheading: 'Classes'}
*/
dispose() {
this.executor.dispose();
if (this.initializer) {
this.initializer.dispose();
}
this.resourceManager.dispose();
}
}
/**
* Load a graph model given a URL to the model definition.
*
* Example of loading MobileNetV2 from a URL and making a prediction with a
* zeros input:
*
* ```js
* const modelUrl =
* 'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';
* const model = await tf.loadGraphModel(modelUrl);
* const zeros = tf.zeros([1, 224, 224, 3]);
* model.predict(zeros).print();
* ```
*
* Example of loading MobileNetV2 from a TF Hub URL and making a prediction with
* a zeros input:
*
* ```js
* const modelUrl =
* 'https://tfhub.dev/google/imagenet/mobilenet_v2_140_224/classification/2';
* const model = await tf.loadGraphModel(modelUrl, {fromTFHub: true});
* const zeros = tf.zeros([1, 224, 224, 3]);
* model.predict(zeros).print();
* ```
* @param modelUrl The url or an `io.IOHandler` that loads the model.
* @param options Options for the HTTP request, which allows to send credentials
* and custom headers.
*
* @doc {heading: 'Models', subheading: 'Loading'}
*/
async function loadGraphModel(modelUrl, options = {}) {
if (modelUrl == null) {
throw new Error('modelUrl in loadGraphModel() cannot be null. Please provide a url ' +
'or an IOHandler that loads the model');
}
if (options == null) {
options = {};
}
if (options.fromTFHub) {
if (modelUrl.load == null) {
if (!modelUrl.endsWith('/')) {
modelUrl = modelUrl + '/';
}
modelUrl = `${modelUrl}${DEFAULT_MODEL_NAME}${TFHUB_SEARCH_PARAM}`;
}
}
const model = new graph_model_GraphModel(modelUrl, options);
await model.load();
return model;
}
//# sourceMappingURL=graph_model.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/version.js
/** @license See the LICENSE file. */
// This code is auto-generated, do not modify this file!
const version = '3.5.0';
//# sourceMappingURL=version.js.map
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/index.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
//# sourceMappingURL=index.js.map
/***/ }),
/* 209 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return conv3DBackpropInput; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the derivative of the input of a 3D convolution.
*
* @param xShape The shape of the input: [batch, depth, height, width,
* in_channels]. If length of 4, batch of 1 is assumed.
* @param dy The derivative of the output, of rank 5 or rank 4 of shape
* `[batch, outDepth, outHeight, outWidth, in_channels]`.
* If rank 4, batch of 1 is assumed.
* @param filter The filter, rank 5, of shape
* `[filterDepth, filterHeight, filterWidth, inDepth, outDepth]`.
* @param strides The strides of the convolution: `[strideDepth, strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm used:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
*/
function conv3DBackpropInput_(xShape, dy, filter, strides, pad) {
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](xShape.length === dy.rank, () => `Length of inShape ` +
`(${xShape.length}) and rank of dy (${dy.rank}) must match`);
let xShape5D = xShape;
let dy5D = dy;
let reshapedTo5D = false;
if (dy.rank === 4) {
reshapedTo5D = true;
dy5D = Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);
xShape5D = [1, xShape[0], xShape[1], xShape[2], xShape[3]];
}
const inDepth = xShape5D[4];
const outDepth = dy5D.shape[4];
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](xShape5D.length === 5, () => `Error in conv3dDerInput: inShape must be length 5, but got length ` +
`${xShape5D.length}.`);
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](dy5D.rank === 5, () => `Error in conv3dDerInput: dy must be rank 5, but got ` +
`rank ${dy5D.rank}`);
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](filter.rank === 5, () => `Error in conv3dDerInput: filter must be rank 5, but got ` +
`rank ${filter.rank}`);
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](inDepth === filter.shape[3], () => `Error in conv3dDerInput: depth of input (${inDepth}) must ` +
`match input depth for filter ${filter.shape[3]}.`);
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"](outDepth === filter.shape[4], () => `Error in conv3dDerInput: depth of output (${outDepth}) must ` +
`match output depth for filter ${filter.shape[4]}.`);
const inputs = { dy: dy5D, filter };
const attrs = { pad, strides, inputShape: xShape5D };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Conv3DBackpropInputV2 */ "H"], inputs, attrs);
if (reshapedTo5D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const conv3DBackpropInput = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ conv3DBackpropInput_ });
//# sourceMappingURL=conv3d_backprop_input.js.map
/***/ }),
/* 210 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return resizeNearestNeighbor; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* NearestNeighbor resize a batch of 3D images to a new shape.
*
* @param images The images, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param size The new shape `[newHeight, newWidth]` to resize the
* images to. Each channel is resized individually.
* @param alignCorners Defaults to False. If true, rescale
* input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4
* corners of images and resized images. If false, rescale by
* `new_height / height`. Treat similarly the width dimension.
* @param halfPixelCenters Defaults to `false`. Whether to assumes pixels are of
* half the actual dimensions, and yields more accurate resizes. This flag
* would also make the floating point coordinates of the top left pixel
* 0.5, 0.5.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function resizeNearestNeighbor_(images, size, alignCorners = false, halfPixelCenters = false) {
const $images = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(images, 'images', 'resizeNearestNeighbor');
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($images.rank === 3 || $images.rank === 4, () => `Error in resizeNearestNeighbor: x must be rank 3 or 4, but got ` +
`rank ${$images.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](size.length === 2, () => `Error in resizeNearestNeighbor: new shape must 2D, but got shape ` +
`${size}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($images.dtype === 'float32' || $images.dtype === 'int32', () => '`images` must have `int32` or `float32` as dtype');
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](halfPixelCenters === false || alignCorners === false, () => `Error in resizeNearestNeighbor: If halfPixelCenters is true, ` +
`alignCorners must be false.`);
let batchImages = $images;
let reshapedTo4D = false;
if ($images.rank === 3) {
reshapedTo4D = true;
batchImages = Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])($images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);
}
const [] = size;
const inputs = { images: batchImages };
const attrs = { alignCorners, halfPixelCenters, size };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* ResizeNearestNeighbor */ "sc"], inputs, attrs);
if (reshapedTo4D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const resizeNearestNeighbor = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ resizeNearestNeighbor_ });
//# sourceMappingURL=resize_nearest_neighbor.js.map
/***/ }),
/* 211 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return resizeBilinear; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Bilinear resize a single 3D image or a batch of 3D images to a new shape.
*
* @param images The images, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param size The new shape `[newHeight, newWidth]` to resize the
* images to. Each channel is resized individually.
* @param alignCorners Defaults to `false`. If true, rescale
* input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4
* corners of images and resized images. If false, rescale by
* `new_height / height`. Treat similarly the width dimension.
* @param halfPixelCenters Defaults to `false`. Whether to assume pixel centers
* are at 0.5, which would make the floating point coordinates of the top
* left pixel 0.5, 0.5.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function resizeBilinear_(images, size, alignCorners = false, halfPixelCenters = false) {
const $images = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(images, 'images', 'resizeBilinear');
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($images.rank === 3 || $images.rank === 4, () => `Error in resizeBilinear: x must be rank 3 or 4, but got ` +
`rank ${$images.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](size.length === 2, () => `Error in resizeBilinear: new shape must 2D, but got shape ` +
`${size}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](halfPixelCenters === false || alignCorners === false, () => `Error in resizeBilinear: If halfPixelCenters is true, ` +
`alignCorners must be false.`);
let batchImages = $images;
let reshapedTo4D = false;
if ($images.rank === 3) {
reshapedTo4D = true;
batchImages = Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])($images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);
}
const [] = size;
const inputs = { images: batchImages };
const attrs = { alignCorners, halfPixelCenters, size };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* ResizeBilinear */ "qc"], inputs, attrs);
if (reshapedTo4D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const resizeBilinear = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ resizeBilinear_ });
//# sourceMappingURL=resize_bilinear.js.map
/***/ }),
/* 212 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return depthwiseConv2dNativeBackpropInput; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function depthwiseConv2dNativeBackpropInput_(xShape, dy, filter, strides, pad, dilations = [1, 1], dimRoundingMode) {
let dy4D = dy;
let reshapedTo4D = false;
if (dy.rank === 3) {
reshapedTo4D = true;
dy4D = Object(_reshape__WEBPACK_IMPORTED_MODULE_3__[/* reshape */ "a"])(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
}
const inputs = { dy: dy4D, filter };
const attrs = { strides, pad, dimRoundingMode, dilations, inputShape: xShape };
const res =
// tslint:disable-next-line: no-unnecessary-type-assertion
_engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* DepthwiseConv2dNativeBackpropInput */ "Q"], inputs, attrs);
if (reshapedTo4D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_3__[/* reshape */ "a"])(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const depthwiseConv2dNativeBackpropInput = Object(_operation__WEBPACK_IMPORTED_MODULE_2__[/* op */ "b"])({ depthwiseConv2dNativeBackpropInput_ });
//# sourceMappingURL=depthwise_conv2d_native_backprop_input.js.map
/***/ }),
/* 213 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return depthwiseConv2dNativeBackpropFilter; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function depthwiseConv2dNativeBackpropFilter_(x, dy, filterShape, strides, pad, dilations = [1, 1], dimRoundingMode) {
let x4D = x;
if (x.rank === 3) {
x4D = Object(_reshape__WEBPACK_IMPORTED_MODULE_3__[/* reshape */ "a"])(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
}
let dy4D = dy;
if (dy4D.rank === 3) {
dy4D = Object(_reshape__WEBPACK_IMPORTED_MODULE_3__[/* reshape */ "a"])(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
}
const inputs = { x: x4D, dy: dy4D };
const attrs = { strides, pad, dimRoundingMode, dilations, filterShape };
// tslint:disable-next-line: no-unnecessary-type-assertion
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* DepthwiseConv2dNativeBackpropFilter */ "P"], inputs, attrs);
}
const depthwiseConv2dNativeBackpropFilter = Object(_operation__WEBPACK_IMPORTED_MODULE_2__[/* op */ "b"])({ depthwiseConv2dNativeBackpropFilter_ });
//# sourceMappingURL=depthwise_conv2d_native_backprop_filter.js.map
/***/ }),
/* 214 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return zeros; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _kernels_Complex__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(38);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Generates a tensorInfo with all zeros value.
* @param backend cpu backend.
* @param shape Shape for the zeros tensor.
* @param dtype Optional. If set, the result has this dtype.
*/
function zeros(backend, shape, dtype = 'float32') {
if (dtype === 'complex64') {
const real = zeros(backend, shape, 'float32');
const imag = zeros(backend, shape, 'float32');
return Object(_kernels_Complex__WEBPACK_IMPORTED_MODULE_1__[/* complex */ "a"])({ inputs: { real, imag }, backend });
}
const values = _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].makeZerosTypedArray(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(shape), dtype);
return backend.makeTensorInfo(shape, dtype, values);
}
//# sourceMappingURL=zeros_impl.js.map
/***/ }),
/* 215 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh
* @license MIT
*/
/* eslint-disable no-proto */
var base64 = __webpack_require__(275)
var ieee754 = __webpack_require__(276)
var isArray = __webpack_require__(277)
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport()
/*
* Export kMaxLength after typed array support is determined.
*/
exports.kMaxLength = kMaxLength()
function typedArraySupport () {
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
}
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
function createBuffer (that, length) {
if (kMaxLength() < length) {
throw new RangeError('Invalid typed array length')
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array(length)
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
if (that === null) {
that = new Buffer(length)
}
that.length = length
}
return that
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
return new Buffer(arg, encodingOrOffset, length)
}
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(this, arg)
}
return from(this, arg, encodingOrOffset, length)
}
Buffer.poolSize = 8192 // not used by this implementation
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
arr.__proto__ = Buffer.prototype
return arr
}
function from (that, value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
return fromArrayBuffer(that, value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(that, value, encodingOrOffset)
}
return fromObject(that, value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(null, value, encodingOrOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true
})
}
}
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (that, size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(that, size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(that, size).fill(fill, encoding)
: createBuffer(that, size).fill(fill)
}
return createBuffer(that, size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(null, size, fill, encoding)
}
function allocUnsafe (that, size) {
assertSize(size)
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < size; ++i) {
that[i] = 0
}
}
return that
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(null, size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(null, size)
}
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
that = createBuffer(that, length)
var actual = that.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
that = that.slice(0, actual)
}
return that
}
function fromArrayLike (that, array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
that = createBuffer(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function fromArrayBuffer (that, array, byteOffset, length) {
array.byteLength // this throws if `array` is not a valid ArrayBuffer
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
if (byteOffset === undefined && length === undefined) {
array = new Uint8Array(array)
} else if (length === undefined) {
array = new Uint8Array(array, byteOffset)
} else {
array = new Uint8Array(array, byteOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = array
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
that = fromArrayLike(that, array)
}
return that
}
function fromObject (that, obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
that = createBuffer(that, len)
if (that.length === 0) {
return that
}
obj.copy(that, 0, 0, len)
return that
}
if (obj) {
if ((typeof ArrayBuffer !== 'undefined' &&
obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
if (typeof obj.length !== 'number' || isnan(obj.length)) {
return createBuffer(that, 0)
}
return fromArrayLike(that, obj)
}
if (obj.type === 'Buffer' && isArray(obj.data)) {
return fromArrayLike(that, obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < kMaxLength()` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
(ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length | 0
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return ''
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (isNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (Buffer.TYPED_ARRAY_SUPPORT &&
typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0
if (isFinite(length)) {
length = length | 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = this.subarray(start, end)
newBuf.__proto__ = Buffer.prototype
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; ++i) {
newBuf[i] = this[i + start]
}
}
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = (value & 0xff)
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if (code < 256) {
val = code
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: utf8ToBytes(new Buffer(val, encoding).toString())
var len = bytes.length
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
function isnan (val) {
return val !== val // eslint-disable-line no-self-compare
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(103)))
/***/ }),
/* 216 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return acos; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes acos of the input `tf.Tensor` element-wise: `acos(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.acos().print(); // or tf.acos(x)
* ```
* @param x The input tensor.
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function acos_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'acos');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Acos */ "b"], inputs);
}
const acos = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ acos_ });
//# sourceMappingURL=acos.js.map
/***/ }),
/* 217 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return acosh; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the inverse hyperbolic cos of the input `tf.Tensor` element-wise:
* `acosh(x)`
*
* ```js
* const x = tf.tensor1d([10, 1, 3, 5.7]);
*
* x.acosh().print(); // or tf.acosh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function acosh_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'acosh');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Acosh */ "c"], inputs);
}
const acosh = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ acosh_ });
//# sourceMappingURL=acosh.js.map
/***/ }),
/* 218 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return addN; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Adds a list of `tf.Tensor`s element-wise, each with the same shape and dtype.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* const c = tf.tensor1d([5, 6]);
*
* tf.addN([a, b, c]).print();
* ```
* @param tensors A list of tensors with the same shape and dtype.
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function addN_(tensors) {
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](Array.isArray(tensors), () => 'The argument passed to tf.addN() must be a list of tensors');
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](tensors.length >= 1, () => `Must pass at least one tensor to tf.addN(), but got ` +
`${tensors.length}`);
const $tensors = tensors.map((t, i) => Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(t, `tensors${i}`, 'addN'));
const firstTensor = $tensors[0];
$tensors.forEach(t => {
if (t.dtype !== firstTensor.dtype) {
throw new Error('All tensors passed to tf.addN() must have the same dtype');
}
});
$tensors.forEach(t => {
if (!_util__WEBPACK_IMPORTED_MODULE_3__[/* arraysEqual */ "a"](t.shape, firstTensor.shape)) {
throw new Error('All tensors passed to tf.addN() must have the same shape');
}
});
const inputs = $tensors;
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* AddN */ "e"], inputs);
}
const addN = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ addN_ });
//# sourceMappingURL=add_n.js.map
/***/ }),
/* 219 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return asin; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes asin of the input `tf.Tensor` element-wise: `asin(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.asin().print(); // or tf.asin(x)
* ```
* @param x The input tensor.
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function asin_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'asin');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Asin */ "j"], inputs);
}
const asin = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ asin_ });
//# sourceMappingURL=asin.js.map
/***/ }),
/* 220 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return asinh; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes inverse hyperbolic sin of the input `tf.Tensor` element-wise:
* `asinh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.asinh().print(); // or tf.asinh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function asinh_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'asinh');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Asinh */ "k"], inputs);
}
const asinh = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ asinh_ });
//# sourceMappingURL=asinh.js.map
/***/ }),
/* 221 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return atan; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes atan of the input `tf.Tensor` element-wise: `atan(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.atan().print(); // or tf.atan(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function atan_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'atan');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Atan */ "l"], inputs);
}
const atan = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ atan_ });
//# sourceMappingURL=atan.js.map
/***/ }),
/* 222 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return atanh; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes inverse hyperbolic tan of the input `tf.Tensor` element-wise:
* `atanh(x)`
*
* ```js
* const x = tf.tensor1d([0, .1, -.1, .7]);
*
* x.atanh().print(); // or tf.atanh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function atanh_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'atanh');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Atanh */ "n"], inputs);
}
const atanh = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ atanh_ });
//# sourceMappingURL=atanh.js.map
/***/ }),
/* 223 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return avgPool3d; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _cast__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(12);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the 3D average pooling.
*
* ```js
* const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);
* const result = tf.avgPool3d(x, 2, 1, 'valid');
* result.print();
* ```
*
* @param x The input tensor, of rank 5 or rank 4 of shape
* `[batch, depth, height, width, inChannels]`.
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* If `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideDepth == strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
* @param dataFormat An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function avgPool3d_(x, filterSize, strides, pad, dimRoundingMode, dataFormat = 'NDHWC') {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'avgPool3d', 'float32');
let x5D = $x;
let reshapedTo5D = false;
if ($x.rank === 4) {
reshapedTo5D = true;
x5D = Object(_reshape__WEBPACK_IMPORTED_MODULE_6__[/* reshape */ "a"])($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
}
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](x5D.rank === 5, () => `Error in avgPool3d: x must be rank 5 but got rank ${x5D.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](dataFormat === 'NDHWC', () => `Error in avgPool3d: Only NDHWC is currently supported, ` +
`but got dataFormat of ${dataFormat}`);
if (dimRoundingMode != null) {
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](_util__WEBPACK_IMPORTED_MODULE_3__[/* isInt */ "v"](pad), () => `Error in avgPool3d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x5D };
const attrs = { filterSize, strides, pad, dimRoundingMode, dataFormat };
// tslint:disable-next-line: no-unnecessary-type-assertion
let res = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* AvgPool3D */ "p"], inputs, attrs);
res = Object(_cast__WEBPACK_IMPORTED_MODULE_4__[/* cast */ "a"])(res, x5D.dtype);
if (reshapedTo5D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_6__[/* reshape */ "a"])(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const avgPool3d = Object(_operation__WEBPACK_IMPORTED_MODULE_5__[/* op */ "b"])({ avgPool3d_ });
//# sourceMappingURL=avg_pool_3d.js.map
/***/ }),
/* 224 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return bincount; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Outputs a vector with length `size` and the same dtype as `weights`.
*
* If `weights` are empty, then index `i` stores the number of times the value
* `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the
* sum of the value in `weights` at each index where the corresponding value in
* `x` is `i`.
*
* Values in `x` outside of the range [0, size) are ignored.
*
* @param x The input int tensor, rank 1.
* @param weights The weights tensor, must have the same shape as x, or a
* length-0 Tensor, in which case it acts as all weights equal to 1.
* @param size Non-negative integer.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function bincount_(x, weights, size) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'bincount');
const $weights = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(weights, 'weights', 'bincount');
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($x.dtype === 'int32', () => `Error in bincount: input ` +
`dtype must be int32, but got ${$x.dtype}`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](size >= 0, () => `size must be non-negative, but got ${size}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($weights.size === $x.size || $weights.size === 0, () => `Error in bincount: weights must have the same size as input or` +
`0-length, but got input shape: ${$x.shape}, weights shape: ` +
`${$weights.shape}.`);
const inputs = { x: $x, weights: $weights };
const attrs = { size };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Bincount */ "u"], inputs, attrs);
}
const bincount = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ bincount_ });
//# sourceMappingURL=bincount.js.map
/***/ }),
/* 225 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ceil; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes ceiling of input `tf.Tensor` element-wise: `ceil(x)`
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3]);
*
* x.ceil().print(); // or tf.ceil(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function ceil_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'ceil');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Ceil */ "x"], inputs);
}
const ceil = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ ceil_ });
//# sourceMappingURL=ceil.js.map
/***/ }),
/* 226 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return clipByValue; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Clips values element-wise. `max(min(x, clipValueMax), clipValueMin)`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.clipByValue(-2, 3).print(); // or tf.clipByValue(x, -2, 3)
* ```
* @param x The input tensor.
* @param clipValueMin Lower-bound of range to be clipped to.
* @param clipValueMax Upper-bound of range to be clipped to.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function clipByValue_(x, clipValueMin, clipValueMax) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'clipByValue');
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]((clipValueMin <= clipValueMax), () => `Error in clip: min (${clipValueMin}) must be ` +
`less than or equal to max (${clipValueMax}).`);
const inputs = { x: $x };
const attrs = { clipValueMin, clipValueMax };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* ClipByValue */ "y"], inputs, attrs);
}
const clipByValue = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ clipByValue_ });
//# sourceMappingURL=clip_by_value.js.map
/***/ }),
/* 227 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return conv3d; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _conv_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(31);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes a 3D convolution over the input x.
*
* @param x The input tensor, of rank 5 or rank 4, of shape
* `[batch, depth, height, width, channels]`. If rank 4,
* batch of 1 is assumed.
* @param filter The filter, rank 5, of shape
* `[filterDepth, filterHeight, filterWidth, inChannels, outChannels]`.
* inChannels must match between input and filter.
* @param strides The strides of the convolution: `[strideDepth, strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dataFormat: An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
* @param dilations The dilation rates: `[dilationDepth, dilationHeight,
* dilationWidth]` in which we sample input values across the height
* and width dimensions in atrous convolution. Defaults to `[1, 1, 1]`.
* If `dilations` is a single number, then
* `dilationDepth == dilationHeight == dilationWidth`. If it is greater
* than 1, then all values of `strides` must be 1.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function conv3d_(x, filter, strides, pad, dataFormat = 'NDHWC', dilations = [1, 1, 1]) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'conv3d');
const $filter = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(filter, 'filter', 'conv3d');
let x5D = $x;
let reshapedTo5D = false;
if ($x.rank === 4) {
reshapedTo5D = true;
x5D = Object(_reshape__WEBPACK_IMPORTED_MODULE_6__[/* reshape */ "a"])($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
}
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](x5D.rank === 5, () => `Error in conv3d: input must be rank 5, but got rank ${x5D.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($filter.rank === 5, () => `Error in conv3d: filter must be rank 5, but got rank ` +
`${$filter.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](x5D.shape[4] === $filter.shape[3], () => `Error in conv3d: depth of input (${x5D.shape[4]}) must match ` +
`input depth for filter ${$filter.shape[3]}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](Object(_conv_util__WEBPACK_IMPORTED_MODULE_4__[/* eitherStridesOrDilationsAreOne */ "h"])(strides, dilations), () => 'Error in conv3D: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](dataFormat === 'NDHWC', () => `Error in conv3d: got dataFormat of ${dataFormat} but only NDHWC is currently supported.`);
const inputs = { x: x5D, filter: $filter };
const attrs = { strides, pad, dataFormat, dilations };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Conv3D */ "F"], inputs, attrs);
if (reshapedTo5D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_6__[/* reshape */ "a"])(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const conv3d = Object(_operation__WEBPACK_IMPORTED_MODULE_5__[/* op */ "b"])({ conv3d_ });
//# sourceMappingURL=conv3d.js.map
/***/ }),
/* 228 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return denseBincount; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Outputs a vector with length `size` and the same dtype as `weights`.
*
* If `weights` are empty, then index `i` stores the number of times the value
* `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the
* sum of the value in `weights` at each index where the corresponding value in
* `x` is `i`.
*
* Values in `x` outside of the range [0, size) are ignored.
*
* @param x The input int tensor, rank 1 or rank 2.
* @param weights The weights tensor, must have the same shape as x, or a
* length-0 Tensor, in which case it acts as all weights equal to 1.
* @param size Non-negative integer.
* @param binaryOutput Optional. Whether the kernel should count the appearance
* or number of occurrences. Defaults to False.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function denseBincount_(x, weights, size, binaryOutput = false) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'denseBincount');
const $weights = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(weights, 'weights', 'denseBincount');
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($x.dtype === 'int32', () => `Error in denseBincount: input ` +
`dtype must be int32, but got ${$x.dtype}`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($x.rank <= 2, () => `Error in denseBincount: input must be at most rank 2, but got ` +
`rank ${$x.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](size >= 0, () => `size must be non-negative, but got ${size}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($weights.size === $x.size || $weights.size === 0, () => `Error in denseBincount: weights must have the same shape as x or ` +
`0-length, but got x shape: ${$x.shape}, weights shape: ` +
`${$weights.shape}.`);
const inputs = { x: $x, weights: $weights };
const attrs = { size, binaryOutput };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* DenseBincount */ "M"], inputs, attrs);
}
const denseBincount = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ denseBincount_ });
//# sourceMappingURL=dense_bincount.js.map
/***/ }),
/* 229 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export einsum_ */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return einsum; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @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.
* =============================================================================
*/
/**
* Tensor contraction over specified indices and outer product.
*
* `einsum` allows defining Tensors by defining their element-wise computation.
* This computation is based on
* [Einstein summation](https://en.wikipedia.org/wiki/Einstein_notation).
*
* Some special cases include:
*
* Matrix multiplication:
* ```js
* const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);
* const y = tf.tensor2d([[0, 1], [2, 3], [4, 5]]);
* x.print();
* y.print();
* tf.einsum('ij,jk->ik', x, y).print();
* ```
*
* Dot product:
* ```js
* const x = tf.tensor1d([1, 2, 3]);
* const y = tf.tensor1d([0, 1, 2]);
* x.print();
* y.print();
* tf.einsum('i,i->', x, y).print();
* ```
*
* Batch dot product:
* ```js
* const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);
* const y = tf.tensor2d([[0, 1, 2], [3, 4, 5]]);
* x.print();
* y.print();
* tf.einsum('bi,bi->b', x, y).print();
* ```
*
* Outer prouduct:
* ```js
* const x = tf.tensor1d([1, 3, 5]);
* const y = tf.tensor1d([2, 4, 6]);
* x.print();
* y.print();
* tf.einsum('i,j->ij', x, y).print();
* ```
*
* Matrix transpose:
* ```js
* const x = tf.tensor2d([[1, 2], [3, 4]]);
* x.print();
* tf.einsum('ij->ji', x).print();
* ```
*
* Batch matrix transpose:
* ```js
* const x = tf.tensor3d([[[1, 2], [3, 4]], [[-1, -2], [-3, -4]]]);
* x.print();
* tf.einsum('bij->bji', x).print();
* ```
*
* Limitations:
*
* This implementation of einsum has the following limitations:
*
* - Does not support >2 input tensors.
* - Does not support duplicate axes for any given input tensor. E.g., equation
* 'ii->' is not suppoted.
* - The `...` notation is not supported.
*
* @param equation a string describing the contraction, in the same format as
* [numpy.einsum](https://numpy.org/doc/stable/reference/generated/numpy.einsum.html).
* @param tensors the input(s) to contract (each one a Tensor), whose shapes
* should be consistent with equation.
* @returns The output tensor.
*
* @doc {heading: 'Tensors', subheading: 'Matrices'}
*/
function einsum_(equation, ...tensors) {
const $tensors = tensors.map((t, i) => Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(t, `tensors${i}`, 'einsum'));
const attrs = { equation };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Einsum */ "V"], $tensors, attrs);
}
const einsum = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ einsum_ });
//# sourceMappingURL=einsum.js.map
/***/ }),
/* 230 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return erf; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _cast__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(12);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes gause error function of the input `tf.Tensor` element-wise:
* `erf(x)`
*
* ```js
* const x = tf.tensor1d([0, .1, -.1, .7]);
*
* x.erf().print(); // or tf.erf(x);
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function erf_(x) {
let $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'erf');
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"]($x.dtype === 'int32' || $x.dtype === 'float32', () => 'Input dtype must be `int32` or `float32`.');
if ($x.dtype === 'int32') {
$x = Object(_cast__WEBPACK_IMPORTED_MODULE_4__[/* cast */ "a"])($x, 'float32');
}
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Erf */ "Z"], inputs);
}
const erf = Object(_operation__WEBPACK_IMPORTED_MODULE_5__[/* op */ "b"])({ erf_ });
//# sourceMappingURL=erf.js.map
/***/ }),
/* 231 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return expm1; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes exponential of the input `tf.Tensor` minus one element-wise.
* `e ^ x - 1`
*
* ```js
* const x = tf.tensor1d([1, 2, -3]);
*
* x.expm1().print(); // or tf.expm1(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function expm1_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'expm1');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Expm1 */ "cb"], inputs);
}
const expm1 = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ expm1_ });
//# sourceMappingURL=expm1.js.map
/***/ }),
/* 232 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isFinite; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns which elements of x are finite.
*
* ```js
* const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);
*
* x.isFinite().print(); // or tf.isNaN(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function isFinite_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'isFinite');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* IsFinite */ "tb"], inputs);
}
const isFinite = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ isFinite_ });
//# sourceMappingURL=is_finite.js.map
/***/ }),
/* 233 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isInf; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns which elements of x are Infinity or -Infinity.
*
* ```js
* const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);
*
* x.isInf().print(); // or tf.isNaN(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function isInf_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'isInf');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* IsInf */ "ub"], inputs);
}
const isInf = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ isInf_ });
//# sourceMappingURL=is_inf.js.map
/***/ }),
/* 234 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isNaN; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* RReturns which elements of x are NaN.
*
* ```js
* const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);
*
* x.isNaN().print(); // or tf.isNaN(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function isNaN_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'isNaN');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* IsNan */ "vb"], inputs);
}
const isNaN = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ isNaN_ });
//# sourceMappingURL=is_nan.js.map
/***/ }),
/* 235 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return linspace; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(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.
* =============================================================================
*/
/**
* Return an evenly spaced sequence of numbers over the given interval.
*
* ```js
* tf.linspace(0, 9, 10).print();
* ```
* @param start The start value of the sequence.
* @param stop The end value of the sequence.
* @param num The number of values to generate.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function linspace(start, stop, num) {
if (num <= 0) {
throw new Error('The number of values should be positive.');
}
const attrs = { start, stop, num };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* LinSpace */ "Bb"], {}, attrs);
}
//# sourceMappingURL=linspace.js.map
/***/ }),
/* 236 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return logSigmoid; });
/* harmony import */ var _gradients__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(34);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _mul__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9);
/* harmony import */ var _neg__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/* harmony import */ var _sigmoid__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(71);
/* harmony import */ var _softplus__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(165);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes log sigmoid of the input `tf.Tensor` element-wise:
* `logSigmoid(x)`. For numerical stability, we use `-tf.softplus(-x)`.
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.logSigmoid().print(); // or tf.logSigmoid(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function logSigmoid_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_1__[/* convertToTensor */ "a"])(x, 'x', 'logSigmoid');
// Use a custom gradient to maintain previous implementation.
// There is no LogSigmoid kernel in TF so we can't use engine.runKernel
// directly
const customOp = Object(_gradients__WEBPACK_IMPORTED_MODULE_0__[/* customGrad */ "a"])((x) => {
// TODO(yassogba) we can remove the chained softplus call here only
// after backends have modualrized softplus at which point we can call
// engine runKernel(..., Sotfplus, ...) directly.
const value = Object(_neg__WEBPACK_IMPORTED_MODULE_3__[/* neg */ "a"])(Object(_softplus__WEBPACK_IMPORTED_MODULE_6__[/* softplus */ "a"])(Object(_neg__WEBPACK_IMPORTED_MODULE_3__[/* neg */ "a"])(x)));
const gradFunc = (dy) => {
const derX = Object(_mul__WEBPACK_IMPORTED_MODULE_2__[/* mul */ "a"])(dy, Object(_sigmoid__WEBPACK_IMPORTED_MODULE_5__[/* sigmoid */ "a"])(Object(_neg__WEBPACK_IMPORTED_MODULE_3__[/* neg */ "a"])(x)));
return derX;
};
return { value, gradFunc };
});
return customOp($x);
}
const logSigmoid = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ logSigmoid_ });
//# sourceMappingURL=log_sigmoid.js.map
/***/ }),
/* 237 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return logSoftmax; });
/* harmony import */ var _gradients__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(34);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _cast__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(12);
/* harmony import */ var _exp__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(41);
/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(75);
/* harmony import */ var _max__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(72);
/* harmony import */ var _mul__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(9);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(4);
/* harmony import */ var _sub__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(14);
/* harmony import */ var _sum__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(19);
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the log softmax.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
*
* a.logSoftmax().print(); // or tf.logSoftmax(a)
* ```
*
* ```js
* const a = tf.tensor2d([2, 4, 6, 1, 2, 3], [2, 3]);
*
* a.logSoftmax().print(); // or tf.logSoftmax(a)
* ```
*
* @param logits The logits array.
* @param axis The dimension softmax would be performed on. Defaults to `-1`
* which indicates the last dimension.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function logSoftmax_(logits, axis = -1) {
const $logits = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_1__[/* convertToTensor */ "a"])(logits, 'logits', 'logSoftmax');
if (axis === -1) {
axis = $logits.rank - 1;
}
if (axis !== $logits.rank - 1) {
throw Error('Log Softmax along a non-last dimension is not yet supported. ' +
`Logits was rank ${$logits.rank} and axis was ${axis}`);
}
// const forward: ForwardFunc = (backend, save) => {
// const keepDims = true;
// const xMax = max(logits, axis, true);
// const shifted = sub(logits, xMax);
// const value =
// sub(cast(shifted, 'float32'), log(sum(exp(shifted), axis,
// keepDims)));
// save([value]);
// return value;
// };
// Use a custom gradient for numerical stability.
const customOp = Object(_gradients__WEBPACK_IMPORTED_MODULE_0__[/* customGrad */ "a"])((logits, save) => {
const keepDims = true;
const xMax = Object(_max__WEBPACK_IMPORTED_MODULE_5__[/* max */ "a"])(logits, axis, true);
const shifted = Object(_sub__WEBPACK_IMPORTED_MODULE_8__[/* sub */ "a"])(logits, xMax);
const value = Object(_sub__WEBPACK_IMPORTED_MODULE_8__[/* sub */ "a"])(Object(_cast__WEBPACK_IMPORTED_MODULE_2__[/* cast */ "a"])(shifted, 'float32'), Object(_log__WEBPACK_IMPORTED_MODULE_4__[/* log */ "a"])(Object(_sum__WEBPACK_IMPORTED_MODULE_9__[/* sum */ "a"])(Object(_exp__WEBPACK_IMPORTED_MODULE_3__[/* exp */ "a"])(shifted), axis, keepDims)));
save([value]);
const gradFunc = (dy, saved) => {
const [value] = saved;
const keepDims = true;
const softmax = Object(_exp__WEBPACK_IMPORTED_MODULE_3__[/* exp */ "a"])(value);
return Object(_sub__WEBPACK_IMPORTED_MODULE_8__[/* sub */ "a"])(dy, Object(_mul__WEBPACK_IMPORTED_MODULE_6__[/* mul */ "a"])(Object(_sum__WEBPACK_IMPORTED_MODULE_9__[/* sum */ "a"])(dy, axis, keepDims), softmax));
};
return { value, gradFunc };
});
return customOp($logits);
// TODO Use Engine.runKernel when CPU/WebGL/WASM backends implement this.
// const inputs: LogSoftmaxInputs = {logits: $logits};
// const attrs: LogSoftmaxAttrs = {axis};
// return ENGINE.runKernel(
// LogSoftmax, inputs as {} as NamedTensorMap,
// attrs as {} as NamedAttrMap);
}
const logSoftmax = Object(_operation__WEBPACK_IMPORTED_MODULE_7__[/* op */ "b"])({ logSoftmax_ });
//# sourceMappingURL=log_softmax.js.map
/***/ }),
/* 238 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return maxPool3d; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the 3D max pooling.
*
* ```js
* const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);
* const result = tf.maxPool3d(x, 2, 1, 'valid');
* result.print();
* ```
*
* @param x The input tensor, of rank 5 or rank 4 of shape
* `[batch, depth, height, width, inChannels]`.
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* If `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideDepth == strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
* @param dataFormat An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function maxPool3d_(x, filterSize = [1, 1, 1], strides, pad, dimRoundingMode, dataFormat = 'NDHWC') {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'maxPool3d');
let x5D = $x;
let reshapedTo5D = false;
if ($x.rank === 4) {
reshapedTo5D = true;
x5D = Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
}
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](x5D.rank === 5, () => `Error in maxPool3d: x must be rank 5 but got rank ${x5D.rank}.`);
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](dataFormat === 'NDHWC', () => `Error in maxPool3d: Only NDHWC is currently supported, ` +
`but got dataFormat of ${dataFormat}`);
if (dimRoundingMode != null) {
_util__WEBPACK_IMPORTED_MODULE_3__[/* assert */ "b"](_util__WEBPACK_IMPORTED_MODULE_3__[/* isInt */ "v"](pad), () => `Error in maxPool3d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x5D };
const attrs = { filterSize, strides, pad, dimRoundingMode, dataFormat };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* MaxPool3D */ "Kb"], inputs, attrs);
if (reshapedTo5D) {
return Object(_reshape__WEBPACK_IMPORTED_MODULE_5__[/* reshape */ "a"])(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const maxPool3d = Object(_operation__WEBPACK_IMPORTED_MODULE_4__[/* op */ "b"])({ maxPool3d_ });
//# sourceMappingURL=max_pool_3d.js.map
/***/ }),
/* 239 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return maxPoolWithArgmax; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the 2D max pooling of an image with Argmax index.
* The indices in argmax are flattened, so that a maximum value at position `[b,
* y, x, c]` becomes flattened index: `(y * width + x) * channels + c` if
* include_batch_in_index is False; `((b * height + y) * width + x) * channels
* +c` if include_batch_in_index is True.
*
* The indices returned are always in `[0, height) x [0, width)` before
* flattening.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param dataFormat An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param includeBatchIndex Defaults to False. Whether to include batch
* dimension in flattened index of argmax.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function maxPoolWithArgmax_(x, filterSize, strides, pad, includeBatchInIndex = false) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'maxPoolWithArgmax');
const inputs = { x: $x };
const attrs = { filterSize, strides, pad, includeBatchInIndex };
// tslint:disable-next-line: no-unnecessary-type-assertion
const result = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* MaxPoolWithArgmax */ "Nb"], inputs, attrs);
return { result: result[0], indexes: result[1] };
}
const maxPoolWithArgmax = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ maxPoolWithArgmax_ });
//# sourceMappingURL=max_pool_with_argmax.js.map
/***/ }),
/* 240 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return multinomial; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/* harmony import */ var _reshape__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values drawn from a multinomial distribution.
*
* ```js
* const probs = tf.tensor([.75, .25]);
* tf.multinomial(probs, 3).print();
* ```
*
* @param logits 1D array with unnormalized log-probabilities, or
* 2D array of shape `[batchSize, numOutcomes]`. See the `normalized`
* parameter.
* @param numSamples Number of samples to draw for each row slice.
* @param seed The seed number.
* @param normalized Whether the provided `logits` are normalized true
* probabilities (sum to 1). Defaults to false.
* @return 1D array of shape `[numSamples]`, or 2D array of shape
* `[batchSize, numSamples]`, depending on the rank of the input.
*
* @doc {heading: 'Tensors', subheading: 'Random'}
*/
function multinomial_(logits, numSamples, seed, normalized = false) {
const $logits = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(logits, 'logits', 'multinomial');
const numOutcomes = $logits.size;
const origRank = $logits.rank;
if (numOutcomes < 2) {
throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ` +
`${numOutcomes}.`);
}
if (origRank > 2) {
throw new Error(`Rank of probabilities must be 1 or 2, but is ${origRank}`);
}
// TODO(lina128): Investigate correct seed behavior. The code seems not allow
// setting see to 0.
seed = seed || Math.random();
// The kernel only accepts (and returns) rank 2 tensors.
const logits2D = origRank === 1 ? Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])($logits, [1, -1]) : $logits;
const inputs = { logits: logits2D };
const attrs = { numSamples, seed, normalized };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Multinomial */ "Ub"], inputs, attrs);
// tslint:disable-next-line:no-unnecessary-type-assertion
return origRank === 1 ? Object(_reshape__WEBPACK_IMPORTED_MODULE_4__[/* reshape */ "a"])(res, [res.size]) : res;
}
const multinomial = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ multinomial_ });
//# sourceMappingURL=multinomial.js.map
/***/ }),
/* 241 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return onesLike; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with all elements set to 1 with the same shape as the
* given tensor.
*
* ```js
* const x = tf.tensor([1, 2]);
* tf.onesLike(x).print();
* ```
* @param x A tensor.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function onesLike_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'onesLike');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* OnesLike */ "cc"], inputs);
}
const onesLike = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ onesLike_ });
//# sourceMappingURL=ones_like.js.map
/***/ }),
/* 242 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return reciprocal; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes reciprocal of x element-wise: `1 / x`
*
* ```js
* const x = tf.tensor1d([0, 1, 2]);
*
* x.reciprocal().print(); // or tf.reciprocal(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function reciprocal_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'reciprocal');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Reciprocal */ "mc"], inputs);
}
const reciprocal = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ reciprocal_ });
//# sourceMappingURL=reciprocal.js.map
/***/ }),
/* 243 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return round; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes round of input `tf.Tensor` element-wise: `round(x)`.
* It implements banker's rounding.
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3]);
*
* x.round().print(); // or tf.round(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function round_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'round');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Round */ "wc"], inputs);
}
const round = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ round_ });
//# sourceMappingURL=round.js.map
/***/ }),
/* 244 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return setdiff1dAsync; });
/* harmony import */ var _tensor__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8);
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the difference between two lists of numbers.
*
* Given a Tensor `x` and a Tensor `y`, this operation returns a Tensor `out`
* that represents all values that are in `x` but not in `y`. The returned
* Tensor `out` is sorted in the same order that the numbers appear in `x`
* (duplicates are preserved). This operation also returns a Tensor indices that
* represents the position of each out element in `x`. In other words:
*
* `out[i] = x[idx[i]] for i in [0, 1, ..., out.length - 1]`
*
* ```js
* const x = [1, 2, 3, 4, 5, 6];
* const y = [1, 3, 5];
*
* const [out, indices] = await tf.setdiff1dAsync(x, y);
* out.print(); // [2, 4, 6]
* indices.print(); // [1, 3, 5]
* ```
*
* @param x 1-D Tensor. Values to keep.
* @param y 1-D Tensor. Must have the same type as x. Values to exclude in the
* output.
* @returns Promise of Tensor tuple [out, indices].
* out: Tensor with the same type as x.
* indices: A Tensor of type int32.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
async function setdiff1dAsync_(x, y) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_1__[/* convertToTensor */ "a"])(x, 'x', 'setdiff1d');
const $y = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_1__[/* convertToTensor */ "a"])(y, 'y', 'setdiff1d');
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"]($x.dtype === $y.dtype, () => `x and y should have the same dtype, but got x (${$x.dtype}) and y (${$y.dtype}).`);
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"]($x.rank === 1, () => `x should be 1D tensor, but got x (${$x.shape}).`);
_util__WEBPACK_IMPORTED_MODULE_2__[/* assert */ "b"]($y.rank === 1, () => `y should be 1D tensor, but got y (${$y.shape}).`);
const xVals = await $x.data();
const yVals = await $y.data();
const ySet = new Set(yVals);
let outputSize = 0;
for (let i = 0; i < xVals.length; i++) {
if (!ySet.has(xVals[i])) {
outputSize++;
}
}
const buffer = new _tensor__WEBPACK_IMPORTED_MODULE_0__[/* TensorBuffer */ "b"]([outputSize], $x.dtype);
const indices = new _tensor__WEBPACK_IMPORTED_MODULE_0__[/* TensorBuffer */ "b"]([outputSize], 'int32');
for (let i = 0, p = 0; i < xVals.length; i++) {
if (!ySet.has(xVals[i])) {
buffer.values[p] = xVals[i];
indices.values[p] = i;
p++;
}
}
return [buffer.toTensor(), indices.toTensor()];
}
const setdiff1dAsync = setdiff1dAsync_;
//# sourceMappingURL=setdiff1d_async.js.map
/***/ }),
/* 245 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return sign; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns an element-wise indication of the sign of a number.
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3, NaN, 0]);
*
* x.sign().print(); // or tf.sign(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function sign_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'sign');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Sign */ "Cc"], inputs);
}
const sign = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ sign_ });
//# sourceMappingURL=sign.js.map
/***/ }),
/* 246 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return softmax; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the softmax normalized vector given the logits.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
*
* a.softmax().print(); // or tf.softmax(a)
* ```
*
* ```js
* const a = tf.tensor2d([2, 4, 6, 1, 2, 3], [2, 3]);
*
* a.softmax().print(); // or tf.softmax(a)
* ```
*
* @param logits The logits array.
* @param dim The dimension softmax would be performed on. Defaults to `-1`
* which indicates the last dimension.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function softmax_(logits, dim = -1) {
const $logits = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(logits, 'logits', 'softmax', 'float32');
if (dim === -1) {
dim = $logits.rank - 1;
}
if (dim !== $logits.rank - 1) {
throw Error('Softmax along a non-last dimension is not yet supported. ' +
`Logits was rank ${$logits.rank} and dim was ${dim}`);
}
const inputs = { logits: $logits };
const attrs = { dim };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Softmax */ "Gc"], inputs, attrs);
}
const softmax = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ softmax_ });
//# sourceMappingURL=softmax.js.map
/***/ }),
/* 247 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return stridedSlice; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Extracts a strided slice of a tensor.
*
* Roughly speaking, this op extracts a slice of size (end-begin)/stride from
* the given input tensor (x). Starting at the location specified by begin the
* slice continues by adding stride to the index until all dimensions are not
* less than end. Note that a stride can be negative, which causes a reverse
* slice.
*
* ```js
* const t = tf.tensor3d([1, 1, 1 ,2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6],
* [3, 2, 3]);
* t.stridedSlice([1, 0, 0], [2, 1, 3], [1, 1, 1]).print() // [[[3, 3, 3]]]
* t.stridedSlice([1, 0, 0], [2, 2, 3], [1, 1, 1]).print() // [[[3, 3, 3],
* // [4, 4, 4]]]
* t.stridedSlice([1, -1, 0], [2, -3, 3], [1, -1, 1]).print() // [[[4, 4, 4],
* // [3, 3, 3]]]
* ```
*
* @param x The tensor to stride slice.
* @param begin The coordinates to start the slice from.
* @param end: The coordinates to end the slice at.
* @param strides: The size of the slice.
* @param beginMask: If the ith bit of beginMask is set, begin[i] is ignored
* and the fullest possible range in that dimension is used instead.
* @param endMask: If the ith bit of endMask is set, end[i] is ignored
* and the fullest possible range in that dimension is used instead.
* @param shrinkAxisMask: a bitmask where bit i implies that
* the ith specification should shrink the dimensionality. begin and end must
* imply a slice of size 1 in the dimension.
*
* @doc {heading: 'Operations', subheading: 'Slicing and Joining'}
*/
function stridedSlice_(x, begin, end, strides, beginMask = 0, endMask = 0, ellipsisMask = 0, newAxisMask = 0, shrinkAxisMask = 0) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'stridedSlice');
const inputs = { x: $x };
const attrs = {
begin,
end,
strides,
beginMask,
endMask,
ellipsisMask,
newAxisMask,
shrinkAxisMask
};
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* StridedSlice */ "Qc"], inputs, attrs);
}
const stridedSlice = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ stridedSlice_ });
//# sourceMappingURL=strided_slice.js.map
/***/ }),
/* 248 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return tan; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes tan of the input `tf.Tensor` element-wise, `tan(x)`
*
* ```js
* const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);
*
* x.tan().print(); // or tf.tan(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function tan_(x) {
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'tan');
const inputs = { x: $x };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* Tan */ "Tc"], inputs);
}
const tan = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ tan_ });
//# sourceMappingURL=tan.js.map
/***/ }),
/* 249 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return truncatedNormal; });
/* harmony import */ var _buffer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var _rand_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(102);
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a truncated normal
* distribution.
*
* ```js
* tf.truncatedNormal([2, 2]).print();
* ```
*
* The generated values follow a normal distribution with specified mean and
* standard deviation, except that values whose magnitude is more than 2
* standard deviations from the mean are dropped and re-picked.
*
* @param shape An array of integers defining the output tensor shape.
* @param mean The mean of the normal distribution.
* @param stdDev The standard deviation of the normal distribution.
* @param dtype The data type of the output tensor.
* @param seed The seed for the random number generator.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function truncatedNormal_(shape, mean = 0, stdDev = 1, dtype, seed) {
if (dtype != null && dtype === 'bool') {
throw new Error(`Unsupported data type $ { dtype }`);
}
const randGauss = new _rand_util__WEBPACK_IMPORTED_MODULE_2__[/* MPRandGauss */ "a"](mean, stdDev, dtype, true /* truncated */, seed);
const res = Object(_buffer__WEBPACK_IMPORTED_MODULE_0__[/* buffer */ "a"])(shape, dtype);
for (let i = 0; i < res.values.length; i++) {
res.values[i] = randGauss.nextValue();
}
return res.toTensor();
}
const truncatedNormal = Object(_operation__WEBPACK_IMPORTED_MODULE_1__[/* op */ "b"])({ truncatedNormal_ });
//# sourceMappingURL=truncated_normal.js.map
/***/ }),
/* 250 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return scatterND; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/* harmony import */ var _scatter_nd_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(112);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a new tensor by applying sparse updates to individual
* values or slices within a zero tensor of the given shape tensor according to
* indices. This operator is the inverse of the `tf.gatherND` operator which
* extracts values or slices from a given tensor.
*
* ```js
* const indices = tf.tensor2d([4, 3, 1, 7], [4, 1], 'int32');
* const updates = tf.tensor1d([9, 10, 11, 12]);
* const shape = [8];
* tf.scatterND(indices, updates, shape).print() //[0, 11, 0, 10, 9, 0, 0, 12]
* ```
*
* @param indices The tensor contains the indices into the output tensor.
* @param updates The tensor contains the value for the indices.
* @param shape: The shape of the output tensor.
*
* @doc {heading: 'Operations', subheading: 'Slicing and Joining'}
*/
function scatterND_(indices, updates, shape) {
const $indices = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(indices, 'indices', 'scatterND', 'int32');
const $updates = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(updates, 'updates', 'scatterND');
_scatter_nd_util__WEBPACK_IMPORTED_MODULE_4__["validateInput"]($updates, $indices, shape);
const inputs = { indices: $indices, updates: $updates };
const attrs = { shape };
// tslint:disable-next-line: no-unnecessary-type-assertion
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* ScatterNd */ "yc"], inputs, attrs);
}
const scatterND = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ scatterND_ });
//# sourceMappingURL=scatter_nd.js.map
/***/ }),
/* 251 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return gatherND; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _kernel_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _tensor_util_env__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _operation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Gather slices from input tensor into a Tensor with shape specified by
* `indices`.
*
* `indices` is an K-dimensional integer tensor, best thought of as a
* (K-1)-dimensional tensor of indices into input, where each element defines a
* slice of input:
* output[\\(i_0, ..., i_{K-2}\\)] = input[indices[\\(i_0, ..., i_{K-2}\\)]]
*
* Whereas in `tf.gather`, `indices` defines slices into the first dimension of
* input, in `tf.gatherND`, `indices` defines slices into the first N dimensions
* of input, where N = indices.shape[-1].
*
* The last dimension of indices can be at most the rank of input:
* indices.shape[-1] <= input.rank
*
* The last dimension of `indices` corresponds to elements
* (if indices.shape[-1] == input.rank) or slices
* (if indices.shape[-1] < input.rank) along dimension indices.shape[-1] of
* input.
* The output tensor has shape
* indices.shape[:-1] + input.shape[indices.shape[-1]:]
*
* Note that on CPU, if an out of bound index is found, an error is returned. On
* GPU, if an out of bound index is found, a 0 is stored in the corresponding
* output value.
*
* ```js
* const indices = tf.tensor2d([0, 1, 1, 0], [2,2], 'int32');
* const input = tf.tensor2d([9, 10, 11, 12], [2, 2]);
* tf.gatherND(input, indices).print() // [10, 11]
* ```
*
* @param x The tensor from which to gather values.
* @param indices Index tensor, must be of type int32.
*
* @doc {heading: 'Operations', subheading: 'Slicing and Joining'}
*/
function gatherND_(x, indices) {
const $indices = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(indices, 'indices', 'gatherND', 'int32');
const $x = Object(_tensor_util_env__WEBPACK_IMPORTED_MODULE_2__[/* convertToTensor */ "a"])(x, 'x', 'gatherND');
const inputs = { params: $x, indices: $indices };
return _engine__WEBPACK_IMPORTED_MODULE_0__[/* ENGINE */ "a"].runKernel(_kernel_names__WEBPACK_IMPORTED_MODULE_1__[/* GatherNd */ "mb"], inputs);
}
const gatherND = Object(_operation__WEBPACK_IMPORTED_MODULE_3__[/* op */ "b"])({ gatherND_ });
//# sourceMappingURL=gather_nd.js.map
/***/ }),
/* 252 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(setImmediate) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return nextFrame; });
/**
* @license
* Copyright 2017 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const delayCallback = (() => {
if (typeof requestAnimationFrame !== 'undefined') {
return requestAnimationFrame;
}
else if (typeof setImmediate !== 'undefined') {
return setImmediate;
}
return (f) => f(); // no delays
})();
/**
* Returns a promise that resolve when a requestAnimationFrame has completed.
*
* On Node.js this uses setImmediate instead of requestAnimationFrame.
*
* This is simply a sugar method so that users can do the following:
* `await tf.nextFrame();`
*
* @doc {heading: 'Performance', subheading: 'Timing'}
*/
function nextFrame() {
return new Promise(resolve => delayCallback(() => resolve()));
}
//# sourceMappingURL=browser_util.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(289).setImmediate))
/***/ }),
/* 253 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ sparseToDense; });
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/engine.js + 2 modules
var engine = __webpack_require__(5);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/kernel_names.js
var kernel_names = __webpack_require__(3);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/sparse_to_dense_util.js
/**
* Validate sparseToDense inputs.
*
* @param sparseIndices A 0-D, 1-D, or 2-D Tensor of type int32.
* sparseIndices[i] contains the complete index where sparseValues[i] will be
* placed.
* @param sparseValues A 0-D or 1-D Tensor. Values
* corresponding to each row of sparseIndices, or a scalar value to be used for
* all sparse indices.
* @param outputShape number[]. Shape of the dense output tensor.
* @param validateIndices boolean. indice validation is not supported, error
* will be thrown if it is set.
*/
function validateInput(sparseIndices, sparseValues, outputShape, defaultValues) {
if (sparseIndices.dtype !== 'int32') {
throw new Error('tf.sparseToDense() expects the indices to be int32 type,' +
` but the dtype was ${sparseIndices.dtype}.`);
}
if (sparseIndices.rank > 2) {
throw new Error('sparseIndices should be a scalar, vector, or matrix,' +
` but got shape ${sparseIndices.shape}.`);
}
const numElems = sparseIndices.rank > 0 ? sparseIndices.shape[0] : 1;
const numDims = sparseIndices.rank > 1 ? sparseIndices.shape[1] : 1;
if (outputShape.length !== numDims) {
throw new Error('outputShape has incorrect number of elements:,' +
` ${outputShape.length}, should be: ${numDims}.`);
}
const numValues = sparseValues.size;
if (!(sparseValues.rank === 0 ||
sparseValues.rank === 1 && numValues === numElems)) {
throw new Error('sparseValues has incorrect shape ' +
`${sparseValues.shape}, should be [] or [${numElems}]`);
}
if (sparseValues.dtype !== defaultValues.dtype) {
throw new Error('sparseValues.dtype must match defaultValues.dtype');
}
}
//# sourceMappingURL=sparse_to_dense_util.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/tensor_util_env.js
var tensor_util_env = __webpack_require__(2);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/operation.js
var operation = __webpack_require__(4);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-core/dist/ops/sparse_to_dense.js
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Converts a sparse representation into a dense tensor.
*
* Builds an array dense with shape outputShape such that:
*
* // If sparseIndices is scalar
* dense[i] = (i == sparseIndices ? sparseValues : defaultValue)
*
* // If sparseIndices is a vector, then for each i
* dense[sparseIndices[i]] = sparseValues[i]
*
* // If sparseIndices is an n by d matrix, then for each i in [0, n)
* dense[sparseIndices[i][0], ..., sparseIndices[i][d-1]] = sparseValues[i]
* All other values in dense are set to defaultValue. If sparseValues is a
* scalar, all sparse indices are set to this single value.
*
* If indices are repeated the final value is summed over all values for those
* indices.
*
* ```js
* const indices = tf.tensor1d([4, 5, 6, 1, 2, 3], 'int32');
* const values = tf.tensor1d([10, 11, 12, 13, 14, 15], 'float32');
* const shape = [8];
* tf.sparseToDense(indices, values, shape).print();
* ```
*
* @param sparseIndices A 0-D, 1-D, or 2-D Tensor of type int32.
* sparseIndices[i] contains the complete index where sparseValues[i] will be
* placed.
* @param sparseValues A 0-D or 1-D Tensor. Values
* corresponding to each row of sparseIndices, or a scalar value to be used for
* all sparse indices.
* @param outputShape Shape of the dense output tensor. the type is inferred.
* @param defaultValue Scalar. Value to set for indices not specified in
* sparseIndices. Defaults to zero.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function sparseToDense_(sparseIndices, sparseValues, outputShape, defaultValue = 0) {
const $sparseIndices = Object(tensor_util_env["a" /* convertToTensor */])(sparseIndices, 'sparseIndices', 'sparseToDense', 'int32');
const $sparseValues = Object(tensor_util_env["a" /* convertToTensor */])(sparseValues, 'sparseValues', 'sparseToDense');
const $defaultValue = Object(tensor_util_env["a" /* convertToTensor */])(defaultValue, 'defaultValue', 'sparseToDense', $sparseValues.dtype);
validateInput($sparseIndices, $sparseValues, outputShape, $defaultValue);
const inputs = {
sparseIndices: $sparseIndices,
sparseValues: $sparseValues,
defaultValue: $defaultValue
};
const attrs = { outputShape };
return engine["a" /* ENGINE */].runKernel(kernel_names["Kc" /* SparseToDense */], inputs, attrs);
}
const sparseToDense = Object(operation["b" /* op */])({ sparseToDense_ });
//# sourceMappingURL=sparse_to_dense.js.map
/***/ }),
/* 254 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
'tfOpName': 'Add',
'category': 'arithmetic',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'AddV2',
'category': 'arithmetic',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'AddN',
'category': 'arithmetic',
'inputs': [{ 'start': 0, 'end': 0, 'name': 'tensors', 'type': 'tensors' }]
},
{
'tfOpName': 'BiasAdd',
'category': 'arithmetic',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }, {
'tfName': 'data_format',
'name': 'dataFormat',
'type': 'string',
'notSupported': true
}
]
},
{
'tfOpName': 'Sub',
'category': 'arithmetic',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'RealDiv',
'category': 'arithmetic',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Div',
'category': 'arithmetic',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'DivNoNan',
'category': 'arithmetic',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'FloorDiv',
'category': 'arithmetic',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Mul',
'category': 'arithmetic',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Maximum',
'category': 'arithmetic',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' }
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Minimum',
'category': 'arithmetic',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' }
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Pow',
'category': 'arithmetic',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'SquaredDifference',
'category': 'arithmetic',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Mod',
'category': 'arithmetic',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'FloorMod',
'category': 'arithmetic',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [{
'tfName': 'T',
'name': 'dtype',
'type': 'dtype',
'notSupported': true
}]
}
];
//# sourceMappingURL=arithmetic.js.map
/***/ }),
/* 255 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
'tfOpName': 'Abs',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Acos',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Asin',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Atan',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Atan2',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'y', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Ceil',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'ClipByValue',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'clipValueMin', 'type': 'number' },
{ 'start': 2, 'name': 'clipValueMax', 'type': 'number' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Complex',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'real', 'type': 'tensor' },
{ 'start': 1, 'name': 'imag', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'ComplexAbs',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Cos',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Cosh',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Elu',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Exp',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Floor',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Log',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Imag',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }, {
'tfName': 'Tout',
'name': 'outputType',
'type': 'dtype',
'notSupported': true
}
]
},
{
'tfOpName': 'Neg',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Real',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }, {
'tfName': 'Tout',
'name': 'outputType',
'type': 'dtype',
'notSupported': true
}
]
},
{
'tfOpName': 'Prelu',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'alpha', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Relu',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Relu6',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Selu',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Sigmoid',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Sin',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Sinh',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Sqrt',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Rsqrt',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Square',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Tan',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Tanh',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Sign',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Round',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Expm1',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Log1p',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Reciprocal',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Softplus',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Asinh',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Acosh',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Atanh',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Erf',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Prod',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'axes', 'type': 'number[]' },
],
'attrs': [
{
'tfName': 'keep_dims',
'name': 'keepDims',
'type': 'bool',
'notSupported': true
},
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'LeakyRelu',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{
'tfName': 'alpha',
'name': 'alpha',
'type': 'number',
'defaultValue': 0.2
},
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'IsNan',
'category': 'basic_math',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [{
'tfName': 'T',
'name': 'dtype',
'type': 'dtype',
'notSupported': true
}]
}
];
//# sourceMappingURL=basic_math.js.map
/***/ }),
/* 256 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
const json = [
{
'tfOpName': 'EmptyTensorList',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'elementShape', 'type': 'shape' },
{ 'start': 1, 'name': 'maxNumElements', 'type': 'number' },
],
'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
},
{
'tfOpName': 'LoopCond',
'category': 'control',
'inputs': [{ 'start': 0, 'name': 'pred', 'type': 'tensor' }]
},
{
'tfOpName': 'Switch',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'data', 'type': 'tensor' },
{ 'start': 1, 'name': 'pred', 'type': 'tensor' }
]
},
{
'tfOpName': 'Merge',
'category': 'control',
'inputs': [{ 'start': 0, 'end': 0, 'name': 'tensors', 'type': 'tensors' }]
},
{
'tfOpName': 'Enter',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensor', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true },
{ 'tfName': 'frame_name', 'name': 'frameName', 'type': 'string' },
{ 'tfName': 'is_constant', 'name': 'isConstant', 'type': 'bool' }
]
},
{
'tfOpName': 'Exit',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensor', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'NextIteration',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensor', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'TensorArrayV3',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'size', 'type': 'number' },
],
'attrs': [
{ 'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype' },
{ 'tfName': 'element_shape', 'name': 'elementShape', 'type': 'shape' },
{ 'tfName': 'dynamic_size', 'name': 'dynamicSize', 'type': 'bool' },
{ 'tfName': 'clear_after_read', 'name': 'clearAfterRead', 'type': 'bool' },
{
'tfName': 'identical_element_shapes',
'name': 'identicalElementShapes',
'type': 'bool'
},
{ 'tfName': 'tensor_array_name', 'name': 'name', 'type': 'string' }
]
},
{
'tfOpName': 'TensorArrayWriteV3',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensorArrayId', 'type': 'tensor' },
{ 'start': 1, 'name': 'index', 'type': 'number' },
{ 'start': 2, 'name': 'tensor', 'type': 'tensor' },
{ 'start': 3, 'name': 'flowIn', 'type': 'number' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'TensorArrayReadV3',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensorArrayId', 'type': 'tensor' },
{ 'start': 1, 'name': 'index', 'type': 'number' },
{ 'start': 2, 'name': 'flowIn', 'type': 'number' },
],
'attrs': [{
'tfName': 'dtype',
'name': 'dtype',
'type': 'dtype',
'notSupported': true
}]
},
{
'tfOpName': 'TensorArrayGatherV3',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensorArrayId', 'type': 'tensor' },
{ 'start': 1, 'name': 'indices', 'type': 'number[]' },
{ 'start': 2, 'name': 'flowIn', 'type': 'number' },
],
'attrs': [
{ 'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype' },
{ 'tfName': 'element_shape', 'name': 'elementShape', 'type': 'shape' }
]
},
{
'tfOpName': 'TensorArrayScatterV3',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensorArrayId', 'type': 'tensor' },
{ 'start': 1, 'name': 'indices', 'type': 'number[]' },
{ 'start': 2, 'name': 'tensor', 'type': 'tensor' },
{ 'start': 3, 'name': 'flowIn', 'type': 'number' },
],
'attrs': [{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype' }]
},
{
'tfOpName': 'TensorArrayConcatV3',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensorArrayId', 'type': 'tensor' },
{ 'start': 1, 'name': 'flowIn', 'type': 'number' },
],
'attrs': [
{ 'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype' }, {
'tfName': 'element_shape_except0',
'name': 'elementShapeExcept0',
'type': 'shape',
'notSupported': true
}
]
},
{
'tfOpName': 'TensorArraySplitV3',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensorArrayId', 'type': 'tensor' },
{ 'start': 1, 'name': 'tensor', 'type': 'tensor' },
{ 'start': 2, 'name': 'lengths', 'type': 'number[]' },
{ 'start': 3, 'name': 'flowIn', 'type': 'number' },
],
'attrs': [{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype' }]
},
{
'tfOpName': 'TensorArraySizeV3',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensorArrayId', 'type': 'tensor' },
{ 'start': 1, 'name': 'flowIn', 'type': 'number' }
]
},
{
'tfOpName': 'TensorArrayCloseV3',
'category': 'control',
'inputs': [{ 'start': 0, 'name': 'tensorArrayId', 'type': 'tensor' }]
},
{
'tfOpName': 'StatelessIf',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'cond', 'type': 'tensor' },
{ 'start': 1, 'end': 0, 'name': 'args', 'type': 'tensors' }
],
'attrs': [
{ 'tfName': 'then_branch', 'name': 'thenBranch', 'type': 'func' },
{ 'tfName': 'else_branch', 'name': 'elseBranch', 'type': 'func' }
]
},
{
'tfOpName': 'If',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'cond', 'type': 'tensor' },
{ 'start': 1, 'end': 0, 'name': 'args', 'type': 'tensors' }
],
'attrs': [
{ 'tfName': 'then_branch', 'name': 'thenBranch', 'type': 'func' },
{ 'tfName': 'else_branch', 'name': 'elseBranch', 'type': 'func' }
]
},
{
'tfOpName': 'StatelessWhile',
'category': 'control',
'inputs': [
{ 'start': 0, 'end': 0, 'name': 'args', 'type': 'tensors' },
],
'attrs': [
{ 'tfName': 'cond', 'name': 'cond', 'type': 'func' },
{ 'tfName': 'body', 'name': 'body', 'type': 'func' }
]
},
{
'tfOpName': 'While',
'category': 'control',
'inputs': [
{ 'start': 0, 'end': 0, 'name': 'args', 'type': 'tensors' },
],
'attrs': [
{ 'tfName': 'cond', 'name': 'cond', 'type': 'func' },
{ 'tfName': 'body', 'name': 'body', 'type': 'func' }
]
},
{
'tfOpName': 'TensorListScatter',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensor', 'type': 'tensor' },
{ 'start': 1, 'name': 'indices', 'type': 'number[]' },
{ 'start': 2, 'name': 'elementShape', 'type': 'shape' }
],
'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
},
{
'tfOpName': 'TensorListScatterV2',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensor', 'type': 'tensor' },
{ 'start': 1, 'name': 'indices', 'type': 'number[]' },
{ 'start': 2, 'name': 'elementShape', 'type': 'shape' },
{ 'start': 3, 'name': 'numElements', 'type': 'number' },
],
'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
},
{
'tfOpName': 'TensorListGather',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensorListId', 'type': 'tensor' },
{ 'start': 1, 'name': 'indices', 'type': 'number[]' },
{ 'start': 2, 'name': 'elementShape', 'type': 'shape' },
],
'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
},
{
'tfOpName': 'TensorListGetItem',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensorListId', 'type': 'tensor' },
{ 'start': 1, 'name': 'index', 'type': 'number' },
{ 'start': 2, 'name': 'elementShape', 'type': 'shape' },
],
'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
},
{
'tfOpName': 'TensorListSetItem',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensorListId', 'type': 'tensor' },
{ 'start': 1, 'name': 'index', 'type': 'number' },
{ 'start': 2, 'name': 'tensor', 'type': 'tensor' },
],
'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
},
{
'tfOpName': 'TensorListReserve',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'elementShape', 'type': 'shape' },
{ 'start': 1, 'name': 'numElements', 'type': 'number' },
],
'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
},
{
'tfOpName': 'TensorListFromTensor',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensor', 'type': 'tensor' },
{ 'start': 1, 'name': 'elementShape', 'type': 'shape' }
],
'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
},
{
'tfOpName': 'TensorListStack',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensorListId', 'type': 'tensor' },
{ 'start': 1, 'name': 'elementShape', 'type': 'shape' },
],
'attrs': [
{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' },
{ 'tfName': 'num_elements', 'name': 'numElements', 'type': 'dtype' }
]
},
{
'tfOpName': 'TensorListSplit',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensor', 'type': 'tensor' },
{ 'start': 1, 'name': 'elementShape', 'type': 'shape' },
{ 'start': 2, 'name': 'lengths', 'type': 'number[]' },
],
'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
},
{
'tfOpName': 'TensorListConcat',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensorListId', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'element_shape', 'name': 'elementShape', 'type': 'shape' },
{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }
]
},
{
'tfOpName': 'TensorListPopBack',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensorListId', 'type': 'tensor' },
{ 'start': 1, 'name': 'elementShape', 'type': 'shape' },
],
'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
},
{
'tfOpName': 'TensorListPushBack',
'category': 'control',
'inputs': [
{ 'start': 0, 'name': 'tensorListId', 'type': 'tensor' },
{ 'start': 1, 'name': 'tensor', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }
]
}
];
//# sourceMappingURL=control.js.map
/***/ }),
/* 257 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
'tfOpName': 'AvgPool',
'category': 'convolution',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
{ 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
'tfName': 'data_format',
'name': 'dataFormat',
'type': 'string',
'notSupported': true
},
{ 'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]' },
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'MaxPool',
'category': 'convolution',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
{ 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
'tfName': 'data_format',
'name': 'dataFormat',
'type': 'string',
'notSupported': true
},
{ 'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]' }, {
'tfName': 'explicit_paddings',
'name': 'explicitPaddings',
'type': 'number[]',
'defaultValue': [],
'notSupported': true
},
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'MaxPoolWithArgmax',
'category': 'convolution',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
{ 'tfName': 'padding', 'name': 'pad', 'type': 'string' },
{ 'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]' }, {
'tfName': 'include_batch_in_index',
'name': 'includeBatchInIndex',
'type': 'bool'
},
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'AvgPool3D',
'category': 'convolution',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
{ 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
'tfName': 'data_format',
'name': 'dataFormat',
'type': 'string',
'notSupported': true
},
{ 'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]' },
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'MaxPool3D',
'category': 'convolution',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
{ 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
'tfName': 'data_format',
'name': 'dataFormat',
'type': 'string',
'notSupported': true
},
{ 'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]' },
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Conv1D',
'category': 'convolution',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'filter', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'stride', 'name': 'stride', 'type': 'number' },
{ 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
'tfName': 'data_format',
'name': 'dataFormat',
'type': 'string',
'defaultValue': 'NWC'
},
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }, {
'tfName': 'dilation',
'name': 'dilation',
'type': 'number',
'defaultValue': 1
}
]
},
{
'tfOpName': 'Conv2D',
'category': 'convolution',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'filter', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true },
{ 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
{ 'tfName': 'padding', 'name': 'pad', 'type': 'string' },
{ 'tfName': 'useCudnnOnGpu', 'name': 'useCudnnOnGpu', 'type': 'bool' }, {
'tfName': 'data_format',
'name': 'dataFormat',
'type': 'string',
'defaultValue': 'NHWC'
},
{
'tfName': 'explicit_paddings',
'name': 'explicitPaddings',
'type': 'number[]',
'defaultValue': []
},
{ 'tfName': 'dilations', 'name': 'dilations', 'type': 'number[]' }
]
},
{
'tfOpName': '_FusedConv2D',
'category': 'convolution',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'filter', 'type': 'tensor' },
{ 'start': 2, end: 0, 'name': 'args', 'type': 'tensors' },
],
'attrs': [
{ 'tfName': 'num_args', 'name': 'numArgs', 'type': 'number' },
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true },
{ 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
{ 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
'tfName': 'explicit_paddings',
'name': 'explicitPaddings',
'type': 'number[]',
'defaultValue': []
},
{
'tfName': 'use_cudnn_on_gpu',
'name': 'useCudnnOnGpu',
'type': 'bool',
'defaultValue': true
},
{
'tfName': 'data_format',
'name': 'dataFormat',
'type': 'string',
'defaultValue': 'NHWC'
},
{
'tfName': 'dilations',
'name': 'dilations',
'type': 'number[]',
'defaultValue': [1, 1, 1, 1]
},
{
'tfName': 'fused_ops',
'name': 'fusedOps',
'type': 'string[]',
'defaultValue': []
},
{
'tfName': 'epsilon',
'name': 'epsilon',
'type': 'number',
'defaultValue': 0.0001
},
{
'tfName': 'leakyrelu_alpha',
'name': 'leakyreluAlpha',
'type': 'number'
}
]
},
{
'tfOpName': 'Conv2DBackpropInput',
'category': 'convolution',
'inputs': [
{ 'start': 2, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'filter', 'type': 'tensor' },
{ 'start': 0, 'name': 'outputShape', 'type': 'number[]' },
],
'attrs': [
{ 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
{ 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
'tfName': 'data_format',
'name': 'dataFormat',
'type': 'string',
'notSupported': true
},
{
'tfName': 'explicit_paddings',
'name': 'explicitPaddings',
'type': 'number[]',
'defaultValue': []
},
{
'tfName': 'dilations',
'name': 'dilations',
'type': 'number[]',
'notSupported': true
}
]
},
{
'tfOpName': 'DepthwiseConv2d',
'category': 'convolution',
'inputs': [
{ 'start': 0, 'name': 'input', 'type': 'tensor' },
{ 'start': 1, 'name': 'filter', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
{ 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
'tfName': 'data_format',
'name': 'dataFormat',
'type': 'string',
'defaultValue': 'NHWC'
},
{
'tfName': 'explicit_paddings',
'name': 'explicitPaddings',
'type': 'number[]',
'defaultValue': []
},
{ 'tfName': 'dilations', 'name': 'dilations', 'type': 'number[]' }
]
},
{
'tfOpName': 'DepthwiseConv2dNative',
'category': 'convolution',
'inputs': [
{ 'start': 0, 'name': 'input', 'type': 'tensor' },
{ 'start': 1, 'name': 'filter', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
{ 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
'tfName': 'data_format',
'name': 'dataFormat',
'type': 'string',
'defaultValue': 'NHWC'
},
{
'tfName': 'explicit_paddings',
'name': 'explicitPaddings',
'type': 'number[]',
'defaultValue': []
},
{ 'tfName': 'dilations', 'name': 'dilations', 'type': 'number[]' }
]
},
{
'tfOpName': 'FusedDepthwiseConv2dNative',
'category': 'convolution',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'filter', 'type': 'tensor' },
{ 'start': 2, end: 0, 'name': 'args', 'type': 'tensors' },
],
'attrs': [
{ 'tfName': 'num_args', 'name': 'numArgs', 'type': 'number' },
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true },
{ 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
{ 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
'tfName': 'data_format',
'name': 'dataFormat',
'type': 'string',
'defaultValue': 'NHWC'
},
{
'tfName': 'dilations',
'name': 'dilations',
'type': 'number[]',
'defaultValue': [1, 1, 1, 1]
},
{
'tfName': 'fused_ops',
'name': 'fusedOps',
'type': 'string[]',
'defaultValue': []
},
{
'tfName': 'explicit_paddings',
'name': 'explicitPaddings',
'type': 'number[]',
'defaultValue': []
}
]
},
{
'tfOpName': 'Conv3D',
'category': 'convolution',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'filter', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
{ 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
'tfName': 'data_format',
'name': 'dataFormat',
'type': 'string',
'defaultValue': 'NHWC'
},
{ 'tfName': 'dilations', 'name': 'dilations', 'type': 'number[]' }
],
},
{
'tfOpName': 'Dilation2D',
'category': 'convolution',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'filter', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
{ 'tfName': 'rates', 'name': 'dilations', 'type': 'number[]' },
{ 'tfName': 'padding', 'name': 'pad', 'type': 'string' }
]
}
];
//# sourceMappingURL=convolution.js.map
/***/ }),
/* 258 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
'tfOpName': 'Fill',
'category': 'creation',
'inputs': [
{ 'start': 0, 'name': 'shape', 'type': 'number[]' },
{ 'start': 1, 'name': 'value', 'type': 'number' },
],
'attrs': [{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype' }]
},
{
'tfOpName': 'LinSpace',
'category': 'creation',
'inputs': [
{ 'start': 0, 'name': 'start', 'type': 'number' },
{ 'start': 1, 'name': 'stop', 'type': 'number' },
{ 'start': 2, 'name': 'num', 'type': 'number' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'OneHot',
'category': 'creation',
'inputs': [
{ 'start': 0, 'name': 'indices', 'type': 'tensor' },
{ 'start': 1, 'name': 'depth', 'type': 'number' },
{ 'start': 2, 'name': 'onValue', 'type': 'number', 'defaultValue': 1 },
{ 'start': 3, 'name': 'offValue', 'type': 'number', 'defaultValue': 0 },
],
'attrs': [
{
'tfName': 'axis',
'name': 'axis',
'type': 'number',
'notSupported': true
},
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Ones',
'category': 'creation',
'inputs': [
{ 'start': 0, 'name': 'shape', 'type': 'number[]' },
],
'attrs': [{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype' }]
},
{
'tfOpName': 'OnesLike',
'category': 'creation',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [{ 'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype' }]
},
{
'tfOpName': 'RandomUniform',
'category': 'creation',
'inputs': [
{ 'start': 0, 'name': 'shape', 'type': 'number[]' },
],
'attrs': [
{
'tfName': 'minval',
'name': 'minval',
'type': 'number',
'defaultValue': 0
},
{
'tfName': 'maxval',
'name': 'maxval',
'type': 'number',
'defaultValue': 1
},
{ 'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype' },
{ 'tfName': 'seed', 'name': 'seed', 'type': 'number', 'defaultValue': 0 }, {
'tfName': 'seed2',
'name': 'seed2',
'type': 'number',
'defaultValue': 0,
'notSupported': true
},
{ 'tfName': 'T', 'name': 'T', 'type': 'number', 'notSupported': true }
]
},
{
'tfOpName': 'Range',
'category': 'creation',
'inputs': [
{ 'start': 0, 'name': 'start', 'type': 'number' },
{ 'start': 1, 'name': 'stop', 'type': 'number' },
{ 'start': 2, 'name': 'step', 'type': 'number', 'defaultValue': 0 },
],
'attrs': [{ 'tfName': 'Tidx', 'name': 'dtype', 'type': 'dtype' }]
},
{
'tfOpName': 'TruncatedNormal',
'category': 'creation',
'inputs': [
{ 'start': 0, 'name': 'shape', 'type': 'number[]' },
],
'attrs': [
{
'tfName': 'means',
'name': 'mean',
'type': 'number',
'defaultValue': 0.0
},
{
'tfName': 'stddev',
'name': 'stdDev',
'type': 'number',
'defaultValue': 1.0
},
{ 'tfName': 'seed', 'name': 'seed', 'type': 'number' }, {
'tfName': 'seed2',
'name': 'seed2',
'type': 'number',
'defaultValue': 0,
'notSupported': true
},
{ 'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype' },
{ 'tfName': 'T', 'name': 'T', 'type': 'number', 'notSupported': true }
]
},
{
'tfOpName': 'Zeros',
'category': 'creation',
'inputs': [
{ 'start': 0, 'name': 'shape', 'type': 'number[]' },
],
'attrs': [{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype' }]
},
{
'tfOpName': 'ZerosLike',
'category': 'creation',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype' }]
},
{
'tfOpName': 'Multinomial',
'category': 'creation',
'inputs': [
{ 'start': 0, 'name': 'logits', 'type': 'tensor' },
{ 'start': 1, 'name': 'numSamples', 'type': 'number' },
],
'attrs': [
{ 'tfName': 'seed', 'name': 'seed', 'type': 'number' },
{ 'tfName': 'seed2', 'name': 'seed2', 'type': 'number' },
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype' },
{ 'tfName': 'output_dtype', 'name': 'output_dtype', 'type': 'dtype' }
]
}
];
//# sourceMappingURL=creation.js.map
/***/ }),
/* 259 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
'tfOpName': 'NonMaxSuppressionV2',
'category': 'dynamic',
'inputs': [
{ 'start': 0, 'name': 'boxes', 'type': 'tensor' },
{ 'start': 1, 'name': 'scores', 'type': 'tensor' },
{ 'start': 2, 'name': 'maxOutputSize', 'type': 'number' },
{ 'start': 3, 'name': 'iouThreshold', 'type': 'number' }
]
},
{
'tfOpName': 'NonMaxSuppressionV3',
'category': 'dynamic',
'inputs': [
{ 'start': 0, 'name': 'boxes', 'type': 'tensor' },
{ 'start': 1, 'name': 'scores', 'type': 'tensor' },
{ 'start': 2, 'name': 'maxOutputSize', 'type': 'number' },
{ 'start': 3, 'name': 'iouThreshold', 'type': 'number' },
{ 'start': 4, 'name': 'scoreThreshold', 'type': 'number' }
]
},
{
'tfOpName': 'NonMaxSuppressionV4',
'category': 'dynamic',
'inputs': [
{ 'start': 0, 'name': 'boxes', 'type': 'tensor' },
{ 'start': 1, 'name': 'scores', 'type': 'tensor' },
{ 'start': 2, 'name': 'maxOutputSize', 'type': 'number' },
{ 'start': 3, 'name': 'iouThreshold', 'type': 'number' },
{ 'start': 4, 'name': 'scoreThreshold', 'type': 'number' }
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }, {
'tfName': 'T_threshold',
'name': 'threshold',
'type': 'dtype',
'notSupported': true
},
{
'tfName': 'pad_to_max_output_size',
'name': 'padToMaxOutputSize',
'type': 'bool'
}
]
},
{
'tfOpName': 'NonMaxSuppressionV5',
'category': 'dynamic',
'inputs': [
{ 'start': 0, 'name': 'boxes', 'type': 'tensor' },
{ 'start': 1, 'name': 'scores', 'type': 'tensor' },
{ 'start': 2, 'name': 'maxOutputSize', 'type': 'number' },
{ 'start': 3, 'name': 'iouThreshold', 'type': 'number' },
{ 'start': 4, 'name': 'scoreThreshold', 'type': 'number' },
{ 'start': 5, 'name': 'softNmsSigma', 'type': 'number' }
]
},
{
'tfOpName': 'Where',
'category': 'dynamic',
'inputs': [
{ 'start': 0, 'name': 'condition', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'ListDiff',
'category': 'dynamic',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'y', 'type': 'tensor' },
],
'attrs': [{
'tfName': 'T',
'name': 'dtype',
'type': 'dtype',
'notSupported': true
}]
}
];
//# sourceMappingURL=dynamic.js.map
/***/ }),
/* 260 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
'tfOpName': 'TopKV2',
'category': 'evaluation',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'k', 'type': 'number' },
],
'attrs': [{ 'tfName': 'sorted', 'name': 'sorted', 'type': 'bool' }]
},
{
'tfOpName': 'Unique',
'category': 'evaluation',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
},
{
'tfOpName': 'UniqueV2',
'category': 'evaluation',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'axis', 'type': 'number' },
],
},
];
//# sourceMappingURL=evaluation.js.map
/***/ }),
/* 261 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
'tfOpName': 'PlaceholderWithDefault',
'category': 'graph',
'inputs': [
{ 'start': 0, 'name': 'default', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'shape', 'name': 'shape', 'type': 'shape' },
{ 'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype' }
]
},
{
'tfOpName': 'Placeholder',
'category': 'graph',
'attrs': [
{ 'tfName': 'shape', 'name': 'shape', 'type': 'shape' },
{ 'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype' }
]
},
{ 'tfOpName': 'Const', 'category': 'graph' }, {
'tfOpName': 'Identity',
'category': 'graph',
'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
},
{
'tfOpName': 'IdentityN',
'category': 'graph',
'inputs': [{ 'start': 0, 'end': 0, 'name': 'x', 'type': 'tensors' }]
},
{
'tfOpName': 'Snapshot',
'category': 'graph',
'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
},
{
'tfOpName': 'Rank',
'category': 'graph',
'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
},
{
'tfOpName': 'Size',
'category': 'graph',
'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
},
{
'tfOpName': 'Shape',
'category': 'graph',
'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
},
{
'tfOpName': 'ShapeN',
'category': 'graph',
'inputs': [{ 'start': 0, 'end': 0, 'name': 'x', 'type': 'tensors' }]
},
{
'tfOpName': 'Print',
'category': 'graph',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'data', 'type': 'tensors' },
],
'attrs': [
{ 'tfName': 'message', 'name': 'message', 'type': 'string' }, {
'tfName': 'first_n',
'name': 'firstN',
'type': 'number',
'notSupported': true
},
{
'tfName': 'summarize',
'name': 'summarize',
'type': 'number',
'defaultValue': 3
}
]
},
{ 'tfOpName': 'NoOp', 'category': 'graph', 'inputs': [] }, {
'tfOpName': 'StopGradient',
'category': 'graph',
'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
},
{
'tfOpName': 'FakeQuantWithMinMaxVars',
'category': 'graph',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'min', 'name': 'min', 'type': 'number' },
{ 'tfName': 'max', 'name': 'max', 'type': 'number' }
]
}
];
//# sourceMappingURL=graph.js.map
/***/ }),
/* 262 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
const json = [
{
'tfOpName': 'HashTable',
'category': 'hash_table',
'inputs': [],
'attrs': [
{ 'tfName': 'shared_name', 'name': 'sharedName', 'type': 'string' },
{
'tfName': 'use_node_name_sharing',
'name': 'useNodeNameSharing',
'type': 'bool'
},
{ 'tfName': 'key_dtype', 'name': 'keyDType', 'type': 'dtype' },
{ 'tfName': 'value_dtype', 'name': 'valueDType', 'type': 'dtype' },
]
},
{
'tfOpName': 'HashTableV2',
'category': 'hash_table',
'inputs': [],
'attrs': [
{ 'tfName': 'shared_name', 'name': 'sharedName', 'type': 'string' },
{
'tfName': 'use_node_name_sharing',
'name': 'useNodeNameSharing',
'type': 'bool'
},
{ 'tfName': 'key_dtype', 'name': 'keyDType', 'type': 'dtype' },
{ 'tfName': 'value_dtype', 'name': 'valueDType', 'type': 'dtype' },
]
},
{
'tfOpName': 'LookupTableImport',
'category': 'hash_table',
'inputs': [
{ 'start': 0, 'name': 'tableHandle', 'type': 'tensor' },
{ 'start': 1, 'name': 'keys', 'type': 'tensor' },
{ 'start': 2, 'name': 'values', 'type': 'tensor' }
],
'attrs': [
{ 'tfName': 'Tin', 'name': 'tIn', 'type': 'dtype', 'notSupported': true }, {
'tfName': 'Tout',
'name': 'tOut',
'type': 'dtype',
'notSupported': true
}
]
},
{
'tfOpName': 'LookupTableImportV2',
'category': 'hash_table',
'inputs': [
{ 'start': 0, 'name': 'tableHandle', 'type': 'tensor' },
{ 'start': 1, 'name': 'keys', 'type': 'tensor' },
{ 'start': 2, 'name': 'values', 'type': 'tensor' }
],
'attrs': [
{ 'tfName': 'Tin', 'name': 'tIn', 'type': 'dtype', 'notSupported': true }, {
'tfName': 'Tout',
'name': 'tOut',
'type': 'dtype',
'notSupported': true
}
]
},
{
'tfOpName': 'LookupTableFind',
'category': 'hash_table',
'inputs': [
{ 'start': 0, 'name': 'tableHandle', 'type': 'tensor' },
{ 'start': 1, 'name': 'keys', 'type': 'tensor' },
{ 'start': 2, 'name': 'defaultValue', 'type': 'tensor' }
],
'attrs': [
{ 'tfName': 'Tin', 'name': 'tIn', 'type': 'dtype', 'notSupported': true }, {
'tfName': 'Tout',
'name': 'tOut',
'type': 'dtype',
'notSupported': true
}
]
},
{
'tfOpName': 'LookupTableFindV2',
'category': 'hash_table',
'inputs': [
{ 'start': 0, 'name': 'tableHandle', 'type': 'tensor' },
{ 'start': 1, 'name': 'keys', 'type': 'tensor' },
{ 'start': 2, 'name': 'defaultValue', 'type': 'tensor' }
],
'attrs': [
{ 'tfName': 'Tin', 'name': 'tIn', 'type': 'dtype', 'notSupported': true }, {
'tfName': 'Tout',
'name': 'tOut',
'type': 'dtype',
'notSupported': true
}
]
},
{
'tfOpName': 'LookupTableSize',
'category': 'hash_table',
'inputs': [
{ 'start': 0, 'name': 'tableHandle', 'type': 'tensor' }
]
},
{
'tfOpName': 'LookupTableSizeV2',
'category': 'hash_table',
'inputs': [
{ 'start': 0, 'name': 'tableHandle', 'type': 'tensor' }
]
}
];
//# sourceMappingURL=hash_table.js.map
/***/ }),
/* 263 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
'tfOpName': 'ResizeBilinear',
'category': 'image',
'inputs': [
{ 'start': 0, 'name': 'images', 'type': 'tensor' },
{ 'start': 1, 'name': 'size', 'type': 'number[]' },
],
'attrs': [
{ 'tfName': 'align_corners', 'name': 'alignCorners', 'type': 'bool' }, {
'tfName': 'half_pixel_centers',
'name': 'halfPixelCenters',
'type': 'bool'
},
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'ResizeNearestNeighbor',
'category': 'image',
'inputs': [
{ 'start': 0, 'name': 'images', 'type': 'tensor' },
{ 'start': 1, 'name': 'size', 'type': 'number[]' },
],
'attrs': [
{ 'tfName': 'align_corners', 'name': 'alignCorners', 'type': 'bool' }, {
'tfName': 'half_pixel_centers',
'name': 'halfPixelCenters',
'type': 'bool'
},
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'CropAndResize',
'category': 'image',
'inputs': [
{ 'start': 0, 'name': 'image', 'type': 'tensor' },
{ 'start': 1, 'name': 'boxes', 'type': 'tensor' },
{ 'start': 2, 'name': 'boxInd', 'type': 'tensor' },
{ 'start': 3, 'name': 'cropSize', 'type': 'number[]' },
],
'attrs': [
{ 'tfName': 'method', 'name': 'method', 'type': 'string' }, {
'tfName': 'extrapolation_value',
'name': 'extrapolationValue',
'type': 'number'
}
]
}
];
//# sourceMappingURL=image.js.map
/***/ }),
/* 264 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
'tfOpName': 'Equal',
'category': 'logical',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'NotEqual',
'category': 'logical',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Greater',
'category': 'logical',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'GreaterEqual',
'category': 'logical',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Less',
'category': 'logical',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'LessEqual',
'category': 'logical',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'LogicalAnd',
'category': 'logical',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'LogicalNot',
'category': 'logical',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'LogicalOr',
'category': 'logical',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Select',
'category': 'logical',
'inputs': [
{ 'start': 0, 'name': 'condition', 'type': 'tensor' },
{ 'start': 1, 'name': 'a', 'type': 'tensor' },
{ 'start': 2, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'SelectV2',
'category': 'logical',
'inputs': [
{ 'start': 0, 'name': 'condition', 'type': 'tensor' },
{ 'start': 1, 'name': 'a', 'type': 'tensor' },
{ 'start': 2, 'name': 'b', 'type': 'tensor' },
],
'attrs': [{
'tfName': 'T',
'name': 'dtype',
'type': 'dtype',
'notSupported': true
}]
}
];
//# sourceMappingURL=logical.js.map
/***/ }),
/* 265 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
'tfOpName': '_FusedMatMul',
'category': 'matrices',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
{ 'start': 2, end: 0, 'name': 'args', 'type': 'tensors' },
],
'attrs': [
{ 'tfName': 'num_args', 'name': 'numArgs', 'type': 'number' }, {
'tfName': 'fused_ops',
'name': 'fusedOps',
'type': 'string[]',
'defaultValue': []
},
{
'tfName': 'epsilon',
'name': 'epsilon',
'type': 'number',
'defaultValue': 0.0001
},
{
'tfName': 'transpose_a',
'name': 'transposeA',
'type': 'bool',
'defaultValue': false
},
{
'tfName': 'transpose_b',
'name': 'transposeB',
'type': 'bool',
'defaultValue': false
},
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'MatMul',
'category': 'matrices',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{
'tfName': 'transpose_a',
'name': 'transposeA',
'type': 'bool',
'defaultValue': false
},
{
'tfName': 'transpose_b',
'name': 'transposeB',
'type': 'bool',
'defaultValue': false
},
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'BatchMatMul',
'category': 'matrices',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{
'tfName': 'adj_x',
'name': 'transposeA',
'type': 'bool',
'defaultValue': false
},
{
'tfName': 'adj_y',
'name': 'transposeB',
'type': 'bool',
'defaultValue': false
},
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'BatchMatMulV2',
'category': 'matrices',
'inputs': [
{ 'start': 0, 'name': 'a', 'type': 'tensor' },
{ 'start': 1, 'name': 'b', 'type': 'tensor' },
],
'attrs': [
{
'tfName': 'adj_x',
'name': 'transposeA',
'type': 'bool',
'defaultValue': false
},
{
'tfName': 'adj_y',
'name': 'transposeB',
'type': 'bool',
'defaultValue': false
},
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Transpose',
'category': 'matrices',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'perm', 'type': 'number[]' },
],
'attrs': [
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
]
},
{
'tfOpName': 'Einsum',
'category': 'matrices',
'inputs': [{ 'start': 0, 'end': 0, 'name': 'tensors', 'type': 'tensors' }],
'attrs': [
{ 'tfName': 'equation', 'name': 'equation', 'type': 'string' },
{ 'tfName': 'N', 'name': 'n', 'type': 'number', 'defaultValue': 2 },
{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype' }
]
}
];
//# sourceMappingURL=matrices.js.map
/***/ }),
/* 266 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
'tfOpName': 'FusedBatchNorm',
'category': 'normalization',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'scale', 'type': 'tensor' },
{ 'start': 2, 'name': 'offset', 'type': 'tensor' },
{ 'start': 3, 'name': 'mean', 'type': 'tensor' },
{ 'start': 4, 'name': 'variance', 'type': 'tensor' },
],
'attrs': [
{
'tfName': 'epsilon',
'name': 'epsilon',
'type': 'number',
'defaultValue': 0.001
},
{
'tfName': 'data_format',
'name': 'dataFormat',
'type': 'string',
'notSupported': true
}
]
},
{
'tfOpName': 'FusedBatchNormV2',
'category': 'normalization',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'scale', 'type': 'tensor' },
{ 'start': 2, 'name': 'offset', 'type': 'tensor' },
{ 'start': 3, 'name': 'mean', 'type': 'tensor' },
{ 'start': 4, 'name': 'variance', 'type': 'tensor' },
],
'attrs': [
{
'tfName': 'epsilon',
'name': 'epsilon',
'type': 'number',
'defaultValue': 0.001
},
{
'tfName': 'data_format',
'name': 'dataFormat',
'type': 'string',
'notSupported': true
}
]
},
{
'tfOpName': 'FusedBatchNormV3',
'category': 'normalization',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'scale', 'type': 'tensor' },
{ 'start': 2, 'name': 'offset', 'type': 'tensor' },
{ 'start': 3, 'name': 'mean', 'type': 'tensor' },
{ 'start': 4, 'name': 'variance', 'type': 'tensor' },
],
'attrs': [
{
'tfName': 'epsilon',
'name': 'epsilon',
'type': 'number',
'defaultValue': 0.001
},
{
'tfName': 'data_format',
'name': 'dataFormat',
'type': 'string',
'notSupported': true
}
]
},
{
'tfOpName': 'LRN',
'category': 'normalization',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{
'tfName': 'depth_radius',
'name': 'radius',
'type': 'number',
'defaultValue': 5
},
{ 'tfName': 'bias', 'name': 'bias', 'type': 'number', 'defaultValue': 1.0 },
{
'tfName': 'alpha',
'name': 'alpha',
'type': 'number',
'defaultValue': 1.0
},
{
'tfName': 'beta',
'name': 'beta',
'type': 'number',
'defaultValue': 0.5
}
]
},
{
'tfOpName': 'Softmax',
'category': 'normalization',
'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
},
{
'tfOpName': 'LogSoftmax',
'category': 'normalization',
'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
},
{
'tfOpName': 'SparseToDense',
'category': 'normalization',
'inputs': [
{ 'start': 0, 'name': 'sparseIndices', 'type': 'tensor' },
{ 'start': 1, 'name': 'outputShape', 'type': 'number[]' },
{ 'start': 2, 'name': 'sparseValues', 'type': 'tensor' },
{ 'start': 3, 'name': 'defaultValue', 'type': 'tensor' },
],
'attrs': [{
'tfName': 'validate_indices',
'name': 'validateIndices',
'type': 'bool',
'defaultValue': true,
'notSupported': true
}]
}
];
//# sourceMappingURL=normalization.js.map
/***/ }),
/* 267 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
'tfOpName': 'Bincount',
'category': 'reduction',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'size', 'type': 'number' },
{ 'start': 2, 'name': 'weights', 'type': 'tensor' }
]
},
{
'tfOpName': 'DenseBincount',
'category': 'reduction',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'size', 'type': 'number' },
{ 'start': 2, 'name': 'weights', 'type': 'tensor' }
],
'attrs': [{ 'tfName': 'binary_output', 'name': 'binaryOutput', 'type': 'bool' }]
},
{
'tfOpName': 'Max',
'category': 'reduction',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'axis', 'type': 'number[]' },
],
'attrs': [{ 'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool' }]
},
{
'tfOpName': 'Mean',
'category': 'reduction',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'axis', 'type': 'number[]' },
],
'attrs': [{ 'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool' }]
},
{
'tfOpName': 'Min',
'category': 'reduction',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'axis', 'type': 'number[]' },
],
'attrs': [{ 'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool' }]
},
{
'tfOpName': 'Sum',
'category': 'reduction',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'axis', 'type': 'number[]' },
],
'attrs': [{ 'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool' }]
},
{
'tfOpName': 'All',
'category': 'reduction',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'axis', 'type': 'number[]' },
],
'attrs': [{ 'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool' }]
},
{
'tfOpName': 'Any',
'category': 'reduction',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'axis', 'type': 'number[]' },
],
'attrs': [{ 'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool' }]
},
{
'tfOpName': 'ArgMax',
'category': 'reduction',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'axis', 'type': 'number' }
]
},
{
'tfOpName': 'ArgMin',
'category': 'reduction',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'axis', 'type': 'number' }
]
},
{
'tfOpName': 'Prod',
'category': 'reduction',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'axis', 'type': 'number[]' },
],
'attrs': [{ 'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool' }]
},
{
'tfOpName': 'Cumsum',
'category': 'reduction',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'axis', 'type': 'number' },
],
'attrs': [
{ 'tfName': 'exclusive', 'name': 'exclusive', 'type': 'bool' },
{ 'tfName': 'reverse', 'name': 'reverse', 'type': 'bool' }
]
}
];
//# sourceMappingURL=reduction.js.map
/***/ }),
/* 268 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
'tfOpName': 'ConcatV2',
'category': 'slice_join',
'inputs': [
{ 'start': 0, 'end': -1, 'name': 'tensors', 'type': 'tensors' },
{ 'start': -1, 'name': 'axis', 'type': 'number' }
],
'attrs': [{ 'tfName': 'N', 'name': 'n', 'type': 'number', 'defaultValue': 2 }]
},
{
'tfOpName': 'Concat',
'category': 'slice_join',
'inputs': [
{ 'start': 1, 'end': 0, 'name': 'tensors', 'type': 'tensors' },
{ 'start': 0, 'name': 'axis', 'type': 'number' }
],
'attrs': [{ 'tfName': 'N', 'name': 'n', 'type': 'number', 'defaultValue': 2 }]
},
{
'tfOpName': 'GatherV2',
'category': 'slice_join',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'indices', 'type': 'tensor' },
{ 'start': 2, 'name': 'axis', 'type': 'number', 'defaultValue': 0 }
],
'attrs': [{
'tfName': 'batch_dims',
'name': 'batchDims',
'type': 'number',
'defaultValue': 0
}]
},
{
'tfOpName': 'Gather',
'category': 'slice_join',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'indices', 'type': 'tensor' },
],
'attrs': [{
'tfName': 'validate_indices',
'name': 'validateIndices',
'type': 'bool',
'notSupported': true
}]
},
{
'tfOpName': 'Reverse',
'category': 'slice_join',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'dims', 'type': 'bool[]' }
]
},
{
'tfOpName': 'ReverseV2',
'category': 'slice_join',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'axis', 'type': 'number[]' }
]
},
{
'tfOpName': 'Slice',
'category': 'slice_join',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'begin', 'type': 'number[]' },
{ 'start': 2, 'name': 'size', 'type': 'number[]' }
]
},
{
'tfOpName': 'StridedSlice',
'category': 'slice_join',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'begin', 'type': 'number[]' },
{ 'start': 2, 'name': 'end', 'type': 'number[]' },
{ 'start': 3, 'name': 'strides', 'type': 'number[]' },
],
'attrs': [
{
'tfName': 'begin_mask',
'name': 'beginMask',
'type': 'number',
'defaultValue': 0
},
{
'tfName': 'end_mask',
'name': 'endMask',
'type': 'number',
'defaultValue': 0
},
{
'tfName': 'new_axis_mask',
'name': 'newAxisMask',
'type': 'number',
'defaultValue': 0
},
{
'tfName': 'ellipsis_mask',
'name': 'ellipsisMask',
'type': 'number',
'defaultValue': 0
},
{
'tfName': 'shrink_axis_mask',
'name': 'shrinkAxisMask',
'type': 'number',
'defaultValue': 0
}
]
},
{
'tfOpName': 'Pack',
'category': 'slice_join',
'inputs': [
{ 'start': 0, 'end': 0, 'name': 'tensors', 'type': 'tensors' },
],
'attrs': [
{ 'tfName': 'axis', 'name': 'axis', 'type': 'number', 'defaultValue': 0 }
]
},
{
'tfOpName': 'Unpack',
'category': 'slice_join',
'inputs': [
{ 'start': 0, 'name': 'tensor', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'axis', 'name': 'axis', 'type': 'number', 'defaultValue': 0 }, {
'tfName': 'num',
'name': 'num',
'type': 'number',
'defaultValue': 0,
'notSupported': true
}
]
},
{
'tfOpName': 'Tile',
'category': 'slice_join',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'reps', 'type': 'number[]' }
]
},
{
'tfOpName': 'Split',
'category': 'slice_join',
'inputs': [
{ 'start': 0, 'name': 'axis', 'type': 'number', 'defaultValue': 0 },
{ 'start': 1, 'name': 'x', 'type': 'tensor' },
],
'attrs': [{
'tfName': 'num_split',
'name': 'numOrSizeSplits',
'type': 'number',
'defaultValue': 1
}]
},
{
'tfOpName': 'SplitV',
'category': 'slice_join',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'numOrSizeSplits', 'type': 'number[]' },
{ 'start': 2, 'name': 'axis', 'type': 'number', 'defaultValue': 0 }
]
},
{
'tfOpName': 'ScatterNd',
'category': 'slice_join',
'inputs': [
{ 'start': 0, 'name': 'indices', 'type': 'tensor' },
{ 'start': 1, 'name': 'values', 'type': 'tensor' },
{ 'start': 2, 'name': 'shape', 'type': 'number[]' }
]
},
{
'tfOpName': 'GatherNd',
'category': 'slice_join',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'indices', 'type': 'tensor' }
]
},
{
'tfOpName': 'SparseToDense',
'category': 'slice_join',
'inputs': [
{ 'start': 0, 'name': 'sparseIndices', 'type': 'tensor' },
{ 'start': 1, 'name': 'outputShape', 'type': 'number[]' },
{ 'start': 2, 'name': 'sparseValues', 'type': 'tensor' },
{ 'start': 3, 'name': 'defaultValue', 'type': 'tensor' },
],
'attrs': [{
'tfName': 'validate_indices',
'name': 'validateIndices',
'type': 'bool',
'defaultValue': false,
'notSupported': true
}]
}
];
//# sourceMappingURL=slice_join.js.map
/***/ }),
/* 269 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
'tfOpName': 'FFT',
'category': 'spectral',
'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
},
{
'tfOpName': 'IFFT',
'category': 'spectral',
'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
},
{
'tfOpName': 'RFFT',
'category': 'spectral',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' }, {
'start': 1,
'name': 'fft_length',
'type': 'number',
'notSupported': true
}
]
},
{
'tfOpName': 'IRFFT',
'category': 'spectral',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' }, {
'start': 1,
'name': 'fft_length',
'type': 'number',
'notSupported': true
}
]
}
];
//# sourceMappingURL=spectral.js.map
/***/ }),
/* 270 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const json = [
{
'tfOpName': 'Cast',
'category': 'transformation',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{
'tfName': 'SrcT',
'name': 'sdtype',
'type': 'dtype',
'notSupported': true
},
{ 'tfName': 'DstT', 'name': 'dtype', 'type': 'dtype' }
]
},
{
'tfOpName': 'ExpandDims',
'category': 'transformation',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'axis', 'type': 'number' }
]
},
{
'tfOpName': 'MirrorPad',
'category': 'transformation',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'padding', 'type': 'number[]' },
],
'attrs': [{ 'tfName': 'mode', 'name': 'mode', 'type': 'string' }]
},
{
'tfOpName': 'Pad',
'category': 'transformation',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'padding', 'type': 'number[]' },
],
'attrs': [{
'tfName': 'constant_value',
'name': 'constantValue',
'type': 'number',
'defaultValue': 0
}]
},
{
'tfOpName': 'PadV2',
'category': 'transformation',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'padding', 'type': 'number[]' }, {
'start': 2,
'name': 'constantValue',
'type': 'number',
'defaultValue': 0
}
]
},
{
'tfOpName': 'Reshape',
'category': 'transformation',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'shape', 'type': 'number[]' }
]
},
{
'tfOpName': 'Squeeze',
'category': 'transformation',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [{
'tfName': 'axis',
'tfDeprecatedName': 'squeeze_dims',
'name': 'axis',
'type': 'number[]'
}]
},
{
'tfOpName': 'SpaceToBatchND',
'category': 'transformation',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'blockShape', 'type': 'number[]' },
{ 'start': 2, 'name': 'paddings', 'type': 'number[]' }
]
},
{
'tfOpName': 'BatchToSpaceND',
'category': 'transformation',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'blockShape', 'type': 'number[]' },
{ 'start': 2, 'name': 'crops', 'type': 'number[]' }
]
},
{
'tfOpName': 'DepthToSpace',
'category': 'transformation',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
],
'attrs': [
{ 'tfName': 'block_size', 'name': 'blockSize', 'type': 'number' },
{ 'tfName': 'data_format', 'name': 'dataFormat', 'type': 'string' }
]
},
{
'tfOpName': 'BroadcastTo',
'category': 'transformation',
'inputs': [
{ 'start': 0, 'name': 'x', 'type': 'tensor' },
{ 'start': 1, 'name': 'shape', 'type': 'number[]' },
],
'attrs': []
}
];
//# sourceMappingURL=transformation.js.map
/***/ }),
/* 271 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ByteChunkIterator; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _lazy_iterator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(45);
/* harmony import */ var _string_iterator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(272);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
class ByteChunkIterator extends _lazy_iterator__WEBPACK_IMPORTED_MODULE_1__[/* LazyIterator */ "a"] {
/**
* Decode a stream of UTF8-encoded byte arrays to a stream of strings.
*
* The byte arrays producetd from the ByteChunkIterator on which this is
* called will be interpreted as concatenated. No assumptions are made about
* the boundaries of the incoming chunks, so a multi-byte UTF8 encoding of a
* character may span the boundary between chunks. This naturally happens,
* for instance, when reading fixed-size byte arrays from a file.
*/
decodeUTF8() {
return new Utf8Iterator(this);
}
}
// ============================================================================
// The following private classes serve to implement the chainable methods
// on ByteChunkIterator. Unfortunately they can't be placed in separate files,
// due to resulting trouble with circular imports.
// ============================================================================
// We wanted multiple inheritance, e.g.
// class Utf8Iterator extends QueueIterator, StringIterator
// but the TypeScript mixin approach is a bit hacky, so we take this adapter
// approach instead.
class Utf8Iterator extends _string_iterator__WEBPACK_IMPORTED_MODULE_2__[/* StringIterator */ "a"] {
constructor(upstream) {
super();
this.upstream = upstream;
this.impl = new Utf8IteratorImpl(upstream);
}
summary() {
return this.impl.summary();
}
async next() {
return this.impl.next();
}
}
/**
* Decode a stream of UTF8-encoded byte arrays to a stream of strings.
*
* This is tricky because the incoming byte array boundaries may disrupt a
* multi-byte UTF8 character. Thus any incomplete character data at the end of
* a chunk must be carried over and prepended to the next chunk before
* decoding. Luckily with native decoder, TextDecoder in browser and
* string_decoder in node, byte array boundaries are handled automatically.
*
* In the context of an input pipeline for machine learning, UTF8 decoding is
* needed to parse text files containing training examples or prediction
* requests (e.g., formatted as CSV or JSON). We cannot use the built-in
* decoding provided by FileReader.readAsText() because here we are in a
* streaming context, which FileReader does not support.
*
* @param upstream A `LazyIterator` of `Uint8Arrays` containing UTF8-encoded
* text, which should be interpreted as concatenated. No assumptions are
* made about the boundaries of the incoming chunks, so a multi-byte UTF8
* encoding of a character may span the boundary between chunks. This
* naturally happens, for instance, when reading fixed-size byte arrays from a
* file.
*/
class Utf8IteratorImpl extends _lazy_iterator__WEBPACK_IMPORTED_MODULE_1__[/* OneToManyIterator */ "b"] {
constructor(upstream) {
super();
this.upstream = upstream;
if (Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().get('IS_BROWSER')) {
this.decoder = new TextDecoder('utf-8');
}
else {
// tslint:disable-next-line:no-require-imports
const { StringDecoder } = __webpack_require__(291);
this.decoder = new StringDecoder('utf8');
}
}
summary() {
return `${this.upstream.summary()} -> Utf8`;
}
async pump() {
const chunkResult = await this.upstream.next();
let chunk;
if (chunkResult.done) {
return false;
}
else {
chunk = chunkResult.value;
}
let text;
if (Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().get('IS_BROWSER')) {
text = this.decoder.decode(chunk, { stream: true });
}
else {
text = this.decoder.write(Buffer.from(chunk.buffer));
}
this.outputQueue.push(text);
return true;
}
}
//# sourceMappingURL=byte_chunk_iterator.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(215).Buffer))
/***/ }),
/* 272 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StringIterator; });
/* harmony import */ var _lazy_iterator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(45);
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
class StringIterator extends _lazy_iterator__WEBPACK_IMPORTED_MODULE_0__[/* LazyIterator */ "a"] {
/**
* Splits a string stream on a given separator.
*
* It is assumed that the incoming chunk boundaries have no semantic meaning,
* so conceptually the incoming stream is treated simply as the concatenation
* of its elements.
*
* The outgoing stream provides chunks corresponding to the results of the
* standard string split() operation (even if such a chunk spanned incoming
* chunks). The separators are not included.
*
* A typical usage is to split a text file (represented as a stream with
* arbitrary chunk boundaries) into lines.
*
* @param upstream A readable stream of strings that can be treated as
* concatenated.
* @param separator A character to split on.
*/
split(separator) {
return new SplitIterator(this, separator);
}
}
// ============================================================================
// The following private classes serve to implement the chainable methods
// on StringIterator. Unfortunately they can't be placed in separate files, due
// to resulting trouble with circular imports.
// ============================================================================
// We wanted multiple inheritance, e.g.
// class SplitIterator extends QueueIterator, StringIterator
// but the TypeScript mixin approach is a bit hacky, so we take this adapter
// approach instead.
class SplitIterator extends StringIterator {
constructor(upstream, separator) {
super();
this.upstream = upstream;
this.impl = new SplitIteratorImpl(upstream, separator);
}
summary() {
return this.impl.summary();
}
async next() {
return this.impl.next();
}
}
class SplitIteratorImpl extends _lazy_iterator__WEBPACK_IMPORTED_MODULE_0__[/* OneToManyIterator */ "b"] {
constructor(upstream, separator) {
super();
this.upstream = upstream;
this.separator = separator;
// A partial string at the end of an upstream chunk
this.carryover = '';
}
summary() {
return `${this.upstream.summary()} -> Split('${this.separator}')`;
}
async pump() {
const chunkResult = await this.upstream.next();
if (chunkResult.done) {
if (this.carryover === '') {
return false;
}
// Pretend that the pump succeeded in order to emit the small last batch.
// The next pump() call will actually fail.
this.outputQueue.push(this.carryover);
this.carryover = '';
return true;
}
const lines = chunkResult.value.split(this.separator);
// Note the behavior: " ab ".split(' ') === ['', 'ab', '']
// Thus the carryover may be '' if the separator falls on a chunk
// boundary; this produces the correct result.
lines[0] = this.carryover + lines[0];
for (const line of lines.slice(0, -1)) {
this.outputQueue.push(line);
}
this.carryover = lines[lines.length - 1];
return true;
}
}
//# sourceMappingURL=string_iterator.js.map
/***/ }),
/* 273 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const blazeface = __webpack_require__(295);
const tfconv = __webpack_require__(208);
const tf = __webpack_require__(0);
const keypoints_1 = __webpack_require__(296);
const pipeline_1 = __webpack_require__(297);
const uv_coords_1 = __webpack_require__(299);
const FACEMESH_GRAPHMODEL_PATH = 'https://tfhub.dev/mediapipe/tfjs-model/facemesh/1/default/1';
const MESH_MODEL_INPUT_WIDTH = 192;
const MESH_MODEL_INPUT_HEIGHT = 192;
async function load({ maxContinuousChecks = 5, detectionConfidence = 0.9, maxFaces = 10, iouThreshold = 0.3, scoreThreshold = 0.75 } = {}) {
const [blazeFace, blazeMeshModel] = await Promise.all([
loadDetectorModel(maxFaces, iouThreshold, scoreThreshold), loadMeshModel()
]);
const faceMesh = new FaceMesh(blazeFace, blazeMeshModel, maxContinuousChecks, detectionConfidence, maxFaces);
return faceMesh;
}
exports.load = load;
async function loadDetectorModel(maxFaces, iouThreshold, scoreThreshold) {
return blazeface.load({ maxFaces, iouThreshold, scoreThreshold });
}
async function loadMeshModel() {
return tfconv.loadGraphModel(FACEMESH_GRAPHMODEL_PATH, { fromTFHub: true });
}
function getInputTensorDimensions(input) {
return input instanceof tf.Tensor ? [input.shape[0], input.shape[1]] :
[input.height, input.width];
}
function flipFaceHorizontal(face, imageWidth) {
if (face.mesh instanceof tf.Tensor) {
const [topLeft, bottomRight, mesh, scaledMesh] = tf.tidy(() => {
const subtractBasis = tf.tensor1d([imageWidth - 1, 0, 0]);
const multiplyBasis = tf.tensor1d([1, -1, 1]);
return tf.tidy(() => {
return [
tf.concat([
tf.sub(imageWidth - 1, face.boundingBox.topLeft.slice(0, 1)),
face.boundingBox.topLeft.slice(1, 1)
]),
tf.concat([
tf.sub(imageWidth - 1, face.boundingBox.bottomRight.slice(0, 1)),
face.boundingBox.bottomRight.slice(1, 1)
]),
tf.sub(subtractBasis, face.mesh).mul(multiplyBasis),
tf.sub(subtractBasis, face.scaledMesh).mul(multiplyBasis)
];
});
});
return Object.assign({}, face, { boundingBox: { topLeft, bottomRight }, mesh, scaledMesh });
}
return Object.assign({}, face, {
boundingBox: {
topLeft: [
imageWidth - 1 - face.boundingBox.topLeft[0],
face.boundingBox.topLeft[1]
],
bottomRight: [
imageWidth - 1 - face.boundingBox.bottomRight[0],
face.boundingBox.bottomRight[1]
]
},
mesh: (face.mesh).map(coord => {
const flippedCoord = coord.slice(0);
flippedCoord[0] = imageWidth - 1 - coord[0];
return flippedCoord;
}),
scaledMesh: face.scaledMesh.map(coord => {
const flippedCoord = coord.slice(0);
flippedCoord[0] = imageWidth - 1 - coord[0];
return flippedCoord;
})
});
}
class FaceMesh {
constructor(blazeFace, blazeMeshModel, maxContinuousChecks, detectionConfidence, maxFaces) {
this.pipeline = new pipeline_1.Pipeline(blazeFace, blazeMeshModel, MESH_MODEL_INPUT_WIDTH, MESH_MODEL_INPUT_HEIGHT, maxContinuousChecks, maxFaces);
this.detectionConfidence = detectionConfidence;
}
static getAnnotations() {
return keypoints_1.MESH_ANNOTATIONS;
}
static getUVCoords() {
return uv_coords_1.UV_COORDS;
}
async estimateFaces(input, returnTensors = false, flipHorizontal = false) {
const [, width] = getInputTensorDimensions(input);
const image = tf.tidy(() => {
if (!(input instanceof tf.Tensor)) {
input = tf.browser.fromPixels(input);
}
return input.toFloat().expandDims(0);
});
const savedWebglPackDepthwiseConvFlag = tf.env().get('WEBGL_PACK_DEPTHWISECONV');
tf.env().set('WEBGL_PACK_DEPTHWISECONV', true);
const predictions = await this.pipeline.predict(image);
tf.env().set('WEBGL_PACK_DEPTHWISECONV', savedWebglPackDepthwiseConvFlag);
image.dispose();
if (predictions != null && predictions.length > 0) {
return Promise.all(predictions.map(async (prediction, i) => {
const { coords, scaledCoords, box, flag } = prediction;
let tensorsToRead = [flag];
if (!returnTensors) {
tensorsToRead = tensorsToRead.concat([coords, scaledCoords, box.startPoint, box.endPoint]);
}
const tensorValues = await Promise.all(tensorsToRead.map(async (d) => d.array()));
const flagValue = tensorValues[0];
flag.dispose();
if (flagValue < this.detectionConfidence) {
this.pipeline.clearRegionOfInterest(i);
}
if (returnTensors) {
const annotatedPrediction = {
faceInViewConfidence: flagValue,
mesh: coords,
scaledMesh: scaledCoords,
boundingBox: {
topLeft: box.startPoint.squeeze(),
bottomRight: box.endPoint.squeeze()
}
};
if (flipHorizontal) {
return flipFaceHorizontal(annotatedPrediction, width);
}
return annotatedPrediction;
}
const [coordsArr, coordsArrScaled, topLeft, bottomRight] = tensorValues.slice(1);
scaledCoords.dispose();
coords.dispose();
let annotatedPrediction = {
faceInViewConfidence: flagValue,
boundingBox: { topLeft, bottomRight },
mesh: coordsArr,
scaledMesh: coordsArrScaled
};
if (flipHorizontal) {
annotatedPrediction =
flipFaceHorizontal(annotatedPrediction, width);
}
const annotations = {};
for (const key in keypoints_1.MESH_ANNOTATIONS) {
annotations[key] = keypoints_1.MESH_ANNOTATIONS[key].map(index => annotatedPrediction.scaledMesh[index]);
}
annotatedPrediction['annotations'] = annotations;
return annotatedPrediction;
}));
}
return [];
}
}
exports.FaceMesh = FaceMesh;
//# sourceMappingURL=index.js.map
/***/ }),
/* 274 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global, process) {/**
* @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.
* =============================================================================
*/
Object.defineProperty(exports, '__esModule', { value: true });
var tfjsCore = __webpack_require__(0);
var tfjsLayers = __webpack_require__(300);
var tfjsConverter = __webpack_require__(208);
var tfjsData = __webpack_require__(303);
var tfjsBackendCpu = __webpack_require__(302);
var tfjsBackendWebgl = __webpack_require__(301);
const Abs = 'Abs';
const Acos = 'Acos';
const Acosh = 'Acosh';
const Add = 'Add';
const AddN = 'AddN';
const All = 'All';
const Any = 'Any';
const ArgMax = 'ArgMax';
const ArgMin = 'ArgMin';
const Asin = 'Asin';
const Asinh = 'Asinh';
const Atan = 'Atan';
const Atanh = 'Atanh';
const Atan2 = 'Atan2';
const AvgPool = 'AvgPool';
const AvgPoolGrad = 'AvgPoolGrad';
const AvgPool3D = 'AvgPool3D';
const AvgPool3DGrad = 'AvgPool3DGrad';
const BatchMatMul = 'BatchMatMul';
const BatchToSpaceND = 'BatchToSpaceND';
const Bincount = 'Bincount';
const BroadcastTo = 'BroadcastTo';
const Cast = 'Cast';
const Ceil = 'Ceil';
const ClipByValue = 'ClipByValue';
const Complex = 'Complex';
const ComplexAbs = 'ComplexAbs';
const Concat = 'Concat';
const Conv2D = 'Conv2D';
const Conv2DBackpropFilter = 'Conv2DBackpropFilter';
const Conv2DBackpropInput = 'Conv2DBackpropInput';
const Conv3D = 'Conv3D';
const Conv3DBackpropFilterV2 = 'Conv3DBackpropFilterV2';
const Conv3DBackpropInputV2 = 'Conv3DBackpropInputV2';
const Cos = 'Cos';
const Cosh = 'Cosh';
const Cumsum = 'Cumsum';
const CropAndResize = 'CropAndResize';
const DenseBincount = 'DenseBincount';
const DepthToSpace = 'DepthToSpace';
const DepthwiseConv2dNative = 'DepthwiseConv2dNative';
const DepthwiseConv2dNativeBackpropFilter = 'DepthwiseConv2dNativeBackpropFilter';
const DepthwiseConv2dNativeBackpropInput = 'DepthwiseConv2dNativeBackpropInput';
const Diag = 'Diag';
const Dilation2D = 'Dilation2D';
const Dilation2DBackpropInput = 'Dilation2DBackpropInput';
const Dilation2DBackpropFilter = 'Dilation2DBackpropFilter';
const RealDiv = 'RealDiv';
const Einsum = 'Einsum';
const Elu = 'Elu';
const EluGrad = 'EluGrad';
const Erf = 'Erf';
const Equal = 'Equal';
const Exp = 'Exp';
const ExpandDims = 'ExpandDims';
const Expm1 = 'Expm1';
const FFT = 'FFT';
const Fill = 'Fill';
const FlipLeftRight = 'FlipLeftRight';
const Floor = 'Floor';
const FloorDiv = 'FloorDiv';
const FusedBatchNorm = 'FusedBatchNorm';
const GatherV2 = 'GatherV2';
const GatherNd = 'GatherNd';
const Greater = 'Greater';
const GreaterEqual = 'GreaterEqual';
const Identity = 'Identity';
const IFFT = 'IFFT';
const Imag = 'Imag';
const IsFinite = 'IsFinite';
const IsInf = 'IsInf';
const IsNan = 'IsNan';
const LeakyRelu = 'LeakyRelu';
const Less = 'Less';
const LessEqual = 'LessEqual';
const LinSpace = 'LinSpace';
const Log = 'Log';
const Log1p = 'Log1p';
const LogicalAnd = 'LogicalAnd';
const LogicalNot = 'LogicalNot';
const LogicalOr = 'LogicalOr';
const LogSoftmax = 'LogSoftmax';
const LRN = 'LRN';
const LRNGrad = 'LRNGrad';
const Max = 'Max';
const Maximum = 'Maximum';
const MaxPool = 'MaxPool';
const MaxPoolGrad = 'MaxPoolGrad';
const MaxPool3D = 'MaxPool3D';
const MaxPool3DGrad = 'MaxPool3DGrad';
const MaxPoolWithArgmax = 'MaxPoolWithArgmax';
const Mean = 'Mean';
const Min = 'Min';
const Minimum = 'Minimum';
const MirrorPad = 'MirrorPad';
const Mod = 'Mod';
const Multinomial = 'Multinomial';
const Multiply = 'Multiply';
const Neg = 'Neg';
const NotEqual = 'NotEqual';
const NonMaxSuppressionV3 = 'NonMaxSuppressionV3';
const NonMaxSuppressionV4 = 'NonMaxSuppressionV4';
const NonMaxSuppressionV5 = 'NonMaxSuppressionV5';
const OnesLike = 'OnesLike';
const OneHot = 'OneHot';
const Pack = 'Pack';
const PadV2 = 'PadV2';
const Pool = 'Pool';
const Pow = 'Pow';
const Prelu = 'Prelu';
const Prod = 'Prod';
const Range = 'Range';
const Real = 'Real';
const Reciprocal = 'Reciprocal';
const Relu = 'Relu';
const Reshape = 'Reshape';
const ResizeNearestNeighbor = 'ResizeNearestNeighbor';
const ResizeNearestNeighborGrad = 'ResizeNearestNeighborGrad';
const ResizeBilinear = 'ResizeBilinear';
const ResizeBilinearGrad = 'ResizeBilinearGrad';
const Relu6 = 'Relu6';
const Reverse = 'Reverse';
const Round = 'Round';
const Rsqrt = 'Rsqrt';
const ScatterNd = 'ScatterNd';
const Select = 'Select';
const Selu = 'Selu';
const Slice = 'Slice';
const Sin = 'Sin';
const Sinh = 'Sinh';
const Sign = 'Sign';
const Sigmoid = 'Sigmoid';
const Softplus = 'Softplus';
const Sqrt = 'Sqrt';
const Sum = 'Sum';
const SpaceToBatchND = 'SpaceToBatchND';
const SplitV = 'SplitV';
const Softmax = 'Softmax';
const SparseReshape = 'SparseReshape';
const SparseToDense = 'SparseToDense';
const SquaredDifference = 'SquaredDifference';
const Square = 'Square';
const StridedSlice = 'StridedSlice';
const Sub = 'Sub';
const Tan = 'Tan';
const Tanh = 'Tanh';
const Tile = 'Tile';
const TopK = 'TopK';
const Transform = 'Transform';
const Transpose = 'Transpose';
const Unique = 'Unique';
const Unpack = 'Unpack';
const UnsortedSegmentSum = 'UnsortedSegmentSum';
const ZerosLike = 'ZerosLike';
/**
* TensorFlow.js-only kernels
*/
const Step = 'Step';
const FromPixels = 'FromPixels';
const RotateWithOffset = 'RotateWithOffset';
const _FusedMatMul = '_FusedMatMul';
const FusedConv2D = 'FusedConv2D';
const FusedDepthwiseConv2D = 'FusedDepthwiseConv2D';
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const EPSILON_FLOAT32 = 1e-7;
const EPSILON_FLOAT16 = 1e-4;
/** Convenient class for storing tensor-related data. */
class DataStorage {
constructor(backend, dataMover) {
this.backend = backend;
this.dataMover = dataMover;
this.data = new WeakMap();
this.dataIdsCount = 0;
}
get(dataId) {
if (!this.data.has(dataId)) {
this.dataMover.moveData(this.backend, dataId);
}
return this.data.get(dataId);
}
set(dataId, value) {
this.dataIdsCount++;
this.data.set(dataId, value);
}
has(dataId) {
return this.data.has(dataId);
}
delete(dataId) {
this.dataIdsCount--;
return this.data.delete(dataId);
}
numDataIds() {
return this.dataIdsCount;
}
}
/**
* The interface that defines the kernels that should be implemented when
* adding a new backend. New backends don't need to implement every one of the
* methods, this can be done gradually (throw an error for unimplemented
* methods).
*/
class KernelBackend {
refCount(dataId) {
return notYetImplemented('refCount');
}
incRef(dataId) {
return notYetImplemented('incRef');
}
timerAvailable() {
return true;
}
time(f) {
return notYetImplemented('time');
}
read(dataId) {
return notYetImplemented('read');
}
readSync(dataId) {
return notYetImplemented('readSync');
}
numDataIds() {
return notYetImplemented('numDataIds');
}
disposeData(dataId, force) {
return notYetImplemented('disposeData');
}
write(values, shape, dtype) {
return notYetImplemented('write');
}
move(dataId, values, shape, dtype, refCount) {
return notYetImplemented('move');
}
memory() {
return notYetImplemented('memory');
}
/** Returns the highest precision for floats in bits (e.g. 16 or 32) */
floatPrecision() {
return notYetImplemented('floatPrecision');
}
/** Returns the smallest representable number. */
epsilon() {
return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;
}
dispose() {
return notYetImplemented('dispose');
}
}
function notYetImplemented(kernelName) {
throw new Error(`'${kernelName}' not yet implemented or not found in the registry. ` +
`This kernel may not be supported by the tfjs backend you have chosen`);
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Shuffles the array in-place using Fisher-Yates algorithm.
*
* ```js
* const a = [1, 2, 3, 4, 5];
* tf.util.shuffle(a);
* console.log(a);
* ```
*
* @param array The array to shuffle in-place.
*
* @doc {heading: 'Util', namespace: 'util'}
*/
// tslint:disable-next-line:no-any
function shuffle(array) {
let counter = array.length;
let temp = 0;
let index = 0;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
index = (Math.random() * counter) | 0;
// Decrease counter by 1
counter--;
// And swap the last element with it
temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
}
/**
* Shuffles two arrays in-place the same way using Fisher-Yates algorithm.
*
* ```js
* const a = [1,2,3,4,5];
* const b = [11,22,33,44,55];
* tf.util.shuffleCombo(a, b);
* console.log(a, b);
* ```
*
* @param array The first array to shuffle in-place.
* @param array2 The second array to shuffle in-place with the same permutation
* as the first array.
*
* @doc {heading: 'Util', namespace: 'util'}
*/
function shuffleCombo(
// tslint:disable-next-line:no-any
array,
// tslint:disable-next-line:no-any
array2) {
if (array.length !== array2.length) {
throw new Error(`Array sizes must match to be shuffled together ` +
`First array length was ${array.length}` +
`Second array length was ${array2.length}`);
}
let counter = array.length;
let temp, temp2;
let index = 0;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
index = (Math.random() * counter) | 0;
// Decrease counter by 1
counter--;
// And swap the last element of each array with it
temp = array[counter];
temp2 = array2[counter];
array[counter] = array[index];
array2[counter] = array2[index];
array[index] = temp;
array2[index] = temp2;
}
}
/** Clamps a value to a specified range. */
function clamp(min, x, max) {
return Math.max(min, Math.min(x, max));
}
function nearestLargerEven(val) {
return val % 2 === 0 ? val : val + 1;
}
function sum(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
/**
* Returns a sample from a uniform [a, b) distribution.
*
* @param a The minimum support (inclusive).
* @param b The maximum support (exclusive).
* @return A pseudorandom number on the half-open interval [a,b).
*/
function randUniform(a, b) {
const r = Math.random();
return (b * r) + (1 - r) * a;
}
/** Returns the squared Euclidean distance between two vectors. */
function distSquared(a, b) {
let result = 0;
for (let i = 0; i < a.length; i++) {
const diff = Number(a[i]) - Number(b[i]);
result += diff * diff;
}
return result;
}
/**
* Asserts that the expression is true. Otherwise throws an error with the
* provided message.
*
* ```js
* const x = 2;
* tf.util.assert(x === 2, 'x is not 2');
* ```
*
* @param expr The expression to assert (as a boolean).
* @param msg A function that returns the message to report when throwing an
* error. We use a function for performance reasons.
*
* @doc {heading: 'Util', namespace: 'util'}
*/
function assert(expr, msg) {
if (!expr) {
throw new Error(typeof msg === 'string' ? msg : msg());
}
}
function assertShapesMatch(shapeA, shapeB, errorMessagePrefix = '') {
assert(arraysEqual(shapeA, shapeB), () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);
}
function assertNonNull(a) {
assert(a != null, () => `The input to the tensor constructor must be a non-null value.`);
}
// NOTE: We explicitly type out what T extends instead of any so that
// util.flatten on a nested array of number doesn't try to infer T as a
// number[][], causing us to explicitly type util.flatten().
/**
* Flattens an arbitrarily nested array.
*
* ```js
* const a = [[1, 2], [3, 4], [5, [6, [7]]]];
* const flat = tf.util.flatten(a);
* console.log(flat);
* ```
*
* @param arr The nested array to flatten.
* @param result The destination array which holds the elements.
* @param skipTypedArray If true, avoids flattening the typed arrays. Defaults
* to false.
*
* @doc {heading: 'Util', namespace: 'util'}
*/
function flatten(arr, result = [], skipTypedArray = false) {
if (result == null) {
result = [];
}
if (Array.isArray(arr) || isTypedArray(arr) && !skipTypedArray) {
for (let i = 0; i < arr.length; ++i) {
flatten(arr[i], result, skipTypedArray);
}
}
else {
result.push(arr);
}
return result;
}
/**
* Returns the size (number of elements) of the tensor given its shape.
*
* ```js
* const shape = [3, 4, 2];
* const size = tf.util.sizeFromShape(shape);
* console.log(size);
* ```
*
* @doc {heading: 'Util', namespace: 'util'}
*/
function sizeFromShape(shape) {
if (shape.length === 0) {
// Scalar.
return 1;
}
let size = shape[0];
for (let i = 1; i < shape.length; i++) {
size *= shape[i];
}
return size;
}
function isScalarShape(shape) {
return shape.length === 0;
}
function arraysEqual(n1, n2) {
if (n1 === n2) {
return true;
}
if (n1 == null || n2 == null) {
return false;
}
if (n1.length !== n2.length) {
return false;
}
for (let i = 0; i < n1.length; i++) {
if (n1[i] !== n2[i]) {
return false;
}
}
return true;
}
function isInt(a) {
return a % 1 === 0;
}
function tanh(x) {
// tslint:disable-next-line:no-any
if (Math.tanh != null) {
// tslint:disable-next-line:no-any
return Math.tanh(x);
}
if (x === Infinity) {
return 1;
}
else if (x === -Infinity) {
return -1;
}
else {
const e2x = Math.exp(2 * x);
return (e2x - 1) / (e2x + 1);
}
}
function sizeToSquarishShape(size) {
const width = Math.ceil(Math.sqrt(size));
return [width, Math.ceil(size / width)];
}
/**
* Creates a new array with randomized indicies to a given quantity.
*
* ```js
* const randomTen = tf.util.createShuffledIndices(10);
* console.log(randomTen);
* ```
*
* @param number Quantity of how many shuffled indicies to create.
*
* @doc {heading: 'Util', namespace: 'util'}
*/
function createShuffledIndices(n) {
const shuffledIndices = new Uint32Array(n);
for (let i = 0; i < n; ++i) {
shuffledIndices[i] = i;
}
shuffle(shuffledIndices);
return shuffledIndices;
}
function rightPad(a, size) {
if (size <= a.length) {
return a;
}
return a + ' '.repeat(size - a.length);
}
function repeatedTry(checkFn, delayFn = (counter) => 0, maxCounter) {
return new Promise((resolve, reject) => {
let tryCount = 0;
const tryFn = () => {
if (checkFn()) {
resolve();
return;
}
tryCount++;
const nextBackoff = delayFn(tryCount);
if (maxCounter != null && tryCount >= maxCounter) {
reject();
return;
}
setTimeout(tryFn, nextBackoff);
};
tryFn();
});
}
/**
* Given the full size of the array and a shape that may contain -1 as the
* implicit dimension, returns the inferred shape where -1 is replaced.
* E.g. For shape=[2, -1, 3] and size=24, it will return [2, 4, 3].
*
* @param shape The shape, which may contain -1 in some dimension.
* @param size The full size (number of elements) of the array.
* @return The inferred shape where -1 is replaced with the inferred size.
*/
function inferFromImplicitShape(shape, size) {
let shapeProd = 1;
let implicitIdx = -1;
for (let i = 0; i < shape.length; ++i) {
if (shape[i] >= 0) {
shapeProd *= shape[i];
}
else if (shape[i] === -1) {
if (implicitIdx !== -1) {
throw Error(`Shapes can only have 1 implicit size. ` +
`Found -1 at dim ${implicitIdx} and dim ${i}`);
}
implicitIdx = i;
}
else if (shape[i] < 0) {
throw Error(`Shapes can not be < 0. Found ${shape[i]} at dim ${i}`);
}
}
if (implicitIdx === -1) {
if (size > 0 && size !== shapeProd) {
throw Error(`Size(${size}) must match the product of shape ${shape}`);
}
return shape;
}
if (shapeProd === 0) {
throw Error(`Cannot infer the missing size in [${shape}] when ` +
`there are 0 elements`);
}
if (size % shapeProd !== 0) {
throw Error(`The implicit shape can't be a fractional number. ` +
`Got ${size} / ${shapeProd}`);
}
const newShape = shape.slice();
newShape[implicitIdx] = size / shapeProd;
return newShape;
}
function parseAxisParam(axis, shape) {
const rank = shape.length;
// Normalize input
axis = axis == null ? shape.map((s, i) => i) : [].concat(axis);
// Check for valid range
assert(axis.every(ax => ax >= -rank && ax < rank), () => `All values in axis param must be in range [-${rank}, ${rank}) but ` +
`got axis ${axis}`);
// Check for only integers
assert(axis.every(ax => isInt(ax)), () => `All values in axis param must be integers but ` +
`got axis ${axis}`);
// Handle negative axis.
return axis.map(a => a < 0 ? rank + a : a);
}
/** Reduces the shape by removing all dimensions of shape 1. */
function squeezeShape(shape, axis) {
const newShape = [];
const keptDims = [];
const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;
const axes = (axis == null || isEmptyArray) ?
null :
parseAxisParam(axis, shape).sort();
let j = 0;
for (let i = 0; i < shape.length; ++i) {
if (axes != null) {
if (axes[j] === i && shape[i] !== 1) {
throw new Error(`Can't squeeze axis ${i} since its dim '${shape[i]}' is not 1`);
}
if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {
newShape.push(shape[i]);
keptDims.push(i);
}
if (axes[j] <= i) {
j++;
}
}
if (shape[i] !== 1) {
newShape.push(shape[i]);
keptDims.push(i);
}
}
return { newShape, keptDims };
}
function getTypedArrayFromDType(dtype, size) {
let values = null;
if (dtype == null || dtype === 'float32') {
values = new Float32Array(size);
}
else if (dtype === 'int32') {
values = new Int32Array(size);
}
else if (dtype === 'bool') {
values = new Uint8Array(size);
}
else {
throw new Error(`Unknown data type ${dtype}`);
}
return values;
}
function getArrayFromDType(dtype, size) {
let values = null;
if (dtype == null || dtype === 'float32') {
values = new Float32Array(size);
}
else if (dtype === 'int32') {
values = new Int32Array(size);
}
else if (dtype === 'bool') {
values = new Uint8Array(size);
}
else if (dtype === 'string') {
values = new Array(size);
}
else {
throw new Error(`Unknown data type ${dtype}`);
}
return values;
}
function checkConversionForErrors(vals, dtype) {
for (let i = 0; i < vals.length; i++) {
const num = vals[i];
if (isNaN(num) || !isFinite(num)) {
throw Error(`A tensor of type ${dtype} being uploaded contains ${num}.`);
}
}
}
/** Returns true if the dtype is valid. */
function isValidDtype(dtype) {
return dtype === 'bool' || dtype === 'complex64' || dtype === 'float32' ||
dtype === 'int32' || dtype === 'string';
}
/**
* Returns true if the new type can't encode the old type without loss of
* precision.
*/
function hasEncodingLoss(oldType, newType) {
if (newType === 'complex64') {
return false;
}
if (newType === 'float32' && oldType !== 'complex64') {
return false;
}
if (newType === 'int32' && oldType !== 'float32' && oldType !== 'complex64') {
return false;
}
if (newType === 'bool' && oldType === 'bool') {
return false;
}
return true;
}
function isTypedArray(a) {
return a instanceof Float32Array || a instanceof Int32Array ||
a instanceof Uint8Array;
}
function bytesPerElement(dtype) {
if (dtype === 'float32' || dtype === 'int32') {
return 4;
}
else if (dtype === 'complex64') {
return 8;
}
else if (dtype === 'bool') {
return 1;
}
else {
throw new Error(`Unknown dtype ${dtype}`);
}
}
/**
* Returns the approximate number of bytes allocated in the string array - 2
* bytes per character. Computing the exact bytes for a native string in JS is
* not possible since it depends on the encoding of the html page that serves
* the website.
*/
function bytesFromStringArray(arr) {
if (arr == null) {
return 0;
}
let bytes = 0;
arr.forEach(x => bytes += x.length);
return bytes;
}
/** Returns true if the value is a string. */
function isString(value) {
return typeof value === 'string' || value instanceof String;
}
function isBoolean(value) {
return typeof value === 'boolean';
}
function isNumber(value) {
return typeof value === 'number';
}
function inferDtype(values) {
if (Array.isArray(values)) {
return inferDtype(values[0]);
}
if (values instanceof Float32Array) {
return 'float32';
}
else if (values instanceof Int32Array || values instanceof Uint8Array) {
return 'int32';
}
else if (isNumber(values)) {
return 'float32';
}
else if (isString(values)) {
return 'string';
}
else if (isBoolean(values)) {
return 'bool';
}
return 'float32';
}
function isFunction(f) {
return !!(f && f.constructor && f.call && f.apply);
}
function nearestDivisor(size, start) {
for (let i = start; i < size; ++i) {
if (size % i === 0) {
return i;
}
}
return size;
}
function computeStrides(shape) {
const rank = shape.length;
if (rank < 2) {
return [];
}
// Last dimension has implicit stride of 1, thus having D-1 (instead of D)
// strides.
const strides = new Array(rank - 1);
strides[rank - 2] = shape[rank - 1];
for (let i = rank - 3; i >= 0; --i) {
strides[i] = strides[i + 1] * shape[i + 1];
}
return strides;
}
function createNestedArray(offset, shape, a, isComplex = false) {
const ret = new Array();
if (shape.length === 1) {
const d = shape[0] * (isComplex ? 2 : 1);
for (let i = 0; i < d; i++) {
ret[i] = a[offset + i];
}
}
else {
const d = shape[0];
const rest = shape.slice(1);
const len = rest.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);
for (let i = 0; i < d; i++) {
ret[i] = createNestedArray(offset + i * len, rest, a, isComplex);
}
}
return ret;
}
// Provide a nested array of TypedArray in given shape.
function toNestedArray(shape, a, isComplex = false) {
if (shape.length === 0) {
// Scalar type should return a single number.
return a[0];
}
const size = shape.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);
if (size === 0) {
// A tensor with shape zero should be turned into empty list.
return [];
}
if (size !== a.length) {
throw new Error(`[${shape}] does not match the input size ${a.length}${isComplex ? ' for a complex tensor' : ''}.`);
}
return createNestedArray(0, shape, a, isComplex);
}
function makeOnesTypedArray(size, dtype) {
const array = makeZerosTypedArray(size, dtype);
for (let i = 0; i < array.length; i++) {
array[i] = 1;
}
return array;
}
function makeZerosTypedArray(size, dtype) {
if (dtype == null || dtype === 'float32' || dtype === 'complex64') {
return new Float32Array(size);
}
else if (dtype === 'int32') {
return new Int32Array(size);
}
else if (dtype === 'bool') {
return new Uint8Array(size);
}
else {
throw new Error(`Unknown data type ${dtype}`);
}
}
/**
* Make nested `TypedArray` filled with zeros.
* @param shape The shape information for the nested array.
* @param dtype dtype of the array element.
*/
function makeZerosNestedTypedArray(shape, dtype) {
const size = shape.reduce((prev, curr) => prev * curr, 1);
if (dtype == null || dtype === 'float32') {
return toNestedArray(shape, new Float32Array(size));
}
else if (dtype === 'int32') {
return toNestedArray(shape, new Int32Array(size));
}
else if (dtype === 'bool') {
return toNestedArray(shape, new Uint8Array(size));
}
else {
throw new Error(`Unknown data type ${dtype}`);
}
}
function assertNonNegativeIntegerDimensions(shape) {
shape.forEach(dimSize => {
assert(Number.isInteger(dimSize) && dimSize >= 0, () => `Tensor must have a shape comprised of positive integers but got ` +
`shape [${shape}].`);
});
}
/**
* Computes flat index for a given location (multidimentionsal index) in a
* Tensor/multidimensional array.
*
* @param locs Location in the tensor.
* @param rank Rank of the tensor.
* @param strides Tensor strides.
*/
function locToIndex(locs, rank, strides) {
if (rank === 0) {
return 0;
}
else if (rank === 1) {
return locs[0];
}
let index = locs[locs.length - 1];
for (let i = 0; i < locs.length - 1; ++i) {
index += strides[i] * locs[i];
}
return index;
}
/**
* Computes the location (multidimensional index) in a tensor/multidimentional
* array for a given flat index.
*
* @param index Index in flat array.
* @param rank Rank of tensor.
* @param strides Strides of tensor.
*/
function indexToLoc(index, rank, strides) {
if (rank === 0) {
return [];
}
else if (rank === 1) {
return [index];
}
const locs = new Array(rank);
for (let i = 0; i < locs.length - 1; ++i) {
locs[i] = Math.floor(index / strides[i]);
index -= locs[i] * strides[i];
}
locs[locs.length - 1] = index;
return locs;
}
/**
* This method asserts whether an object is a Promise instance.
* @param object
*/
// tslint:disable-next-line: no-any
function isPromise(object) {
// We chose to not use 'obj instanceOf Promise' for two reasons:
// 1. It only reliably works for es6 Promise, not other Promise
// implementations.
// 2. It doesn't work with framework that uses zone.js. zone.js monkey patch
// the async calls, so it is possible the obj (patched) is comparing to a
// pre-patched Promise.
return object && object.then && typeof object.then === 'function';
}
/**
* @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.
* =============================================================================
*/
// Expects flags from URL in the format ?tfjsflags=FLAG1:1,FLAG2:true.
const TENSORFLOWJS_FLAGS_PREFIX = 'tfjsflags';
/**
* The environment contains evaluated flags as well as the registered platform.
* This is always used as a global singleton and can be retrieved with
* `tf.env()`.
*
* @doc {heading: 'Environment'}
*/
class Environment {
// tslint:disable-next-line: no-any
constructor(global) {
this.global = global;
this.flags = {};
this.flagRegistry = {};
this.urlFlags = {};
// Jasmine spies on this in 'environment_test.ts'
this.getQueryParams = getQueryParams;
this.populateURLFlags();
}
setPlatform(platformName, platform) {
if (this.platform != null) {
console.warn(`Platform ${this.platformName} has already been set. ` +
`Overwriting the platform with ${platform}.`);
}
this.platformName = platformName;
this.platform = platform;
}
registerFlag(flagName, evaluationFn, setHook) {
this.flagRegistry[flagName] = { evaluationFn, setHook };
// Override the flag value from the URL. This has to happen here because the
// environment is initialized before flags get registered.
if (this.urlFlags[flagName] != null) {
const flagValue = this.urlFlags[flagName];
console.warn(`Setting feature override from URL ${flagName}: ${flagValue}.`);
this.set(flagName, flagValue);
}
}
async getAsync(flagName) {
if (flagName in this.flags) {
return this.flags[flagName];
}
this.flags[flagName] = await this.evaluateFlag(flagName);
return this.flags[flagName];
}
get(flagName) {
if (flagName in this.flags) {
return this.flags[flagName];
}
const flagValue = this.evaluateFlag(flagName);
if (isPromise(flagValue)) {
throw new Error(`Flag ${flagName} cannot be synchronously evaluated. ` +
`Please use getAsync() instead.`);
}
this.flags[flagName] = flagValue;
return this.flags[flagName];
}
getNumber(flagName) {
return this.get(flagName);
}
getBool(flagName) {
return this.get(flagName);
}
getFlags() {
return this.flags;
}
// For backwards compatibility.
get features() {
return this.flags;
}
set(flagName, value) {
if (this.flagRegistry[flagName] == null) {
throw new Error(`Cannot set flag ${flagName} as it has not been registered.`);
}
this.flags[flagName] = value;
if (this.flagRegistry[flagName].setHook != null) {
this.flagRegistry[flagName].setHook(value);
}
}
evaluateFlag(flagName) {
if (this.flagRegistry[flagName] == null) {
throw new Error(`Cannot evaluate flag '${flagName}': no evaluation function found.`);
}
return this.flagRegistry[flagName].evaluationFn();
}
setFlags(flags) {
this.flags = Object.assign({}, flags);
}
reset() {
this.flags = {};
this.urlFlags = {};
this.populateURLFlags();
}
populateURLFlags() {
if (typeof this.global === 'undefined' ||
typeof this.global.location === 'undefined' ||
typeof this.global.location.search === 'undefined') {
return;
}
const urlParams = this.getQueryParams(this.global.location.search);
if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {
const keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(',');
keyValues.forEach(keyValue => {
const [key, value] = keyValue.split(':');
this.urlFlags[key] = parseValue(key, value);
});
}
}
}
function getQueryParams(queryString) {
const params = {};
queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (s, ...t) => {
decodeParam(params, t[0], t[1]);
return t.join('=');
});
return params;
}
function decodeParam(params, name, value) {
params[decodeURIComponent(name)] = decodeURIComponent(value || '');
}
function parseValue(flagName, value) {
value = value.toLowerCase();
if (value === 'true' || value === 'false') {
return value === 'true';
}
else if (`${+value}` === value) {
return +value;
}
throw new Error(`Could not parse value flag value ${value} for flag ${flagName}.`);
}
/**
* Returns the current environment (a global singleton).
*
* The environment object contains the evaluated feature values as well as the
* active platform.
*
* @doc {heading: 'Environment'}
*/
function env() {
return ENV;
}
let ENV = null;
function setEnvironmentGlobal(environment) {
ENV = environment;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Note that the identifier globalNameSpace is scoped to this module, but will
// always resolve to the same global object regardless of how the module is
// resolved.
// tslint:disable-next-line:no-any
let globalNameSpace;
// tslint:disable-next-line:no-any
function getGlobalNamespace() {
if (globalNameSpace == null) {
// tslint:disable-next-line:no-any
let ns;
if (typeof (window) !== 'undefined') {
ns = window;
}
else if (typeof (global) !== 'undefined') {
ns = global;
}
else if (typeof (process) !== 'undefined') {
ns = process;
}
else if (typeof (self) !== 'undefined') {
ns = self;
}
else {
throw new Error('Could not find a global object');
}
globalNameSpace = ns;
}
return globalNameSpace;
}
// tslint:disable-next-line:no-any
function getGlobalMap() {
const ns = getGlobalNamespace();
if (ns._tfGlobals == null) {
ns._tfGlobals = new Map();
}
return ns._tfGlobals;
}
/**
* Returns a globally accessible 'singleton' object.
*
* @param key the name of the object
* @param init a function to initialize to initialize this object
* the first time it is fetched.
*/
function getGlobal(key, init) {
const globalMap = getGlobalMap();
if (globalMap.has(key)) {
return globalMap.get(key);
}
else {
const singleton = init();
globalMap.set(key, singleton);
return globalMap.get(key);
}
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const kernelRegistry = getGlobal('kernelRegistry', () => new Map());
const gradRegistry = getGlobal('gradRegistry', () => new Map());
/**
* Returns the kernel function (code) associated with the provided names.
*
* @param kernelName The official name of the kernel.
* @param backendName The official name of the backend.
*/
function getKernel(kernelName, backendName) {
const key = makeKey(kernelName, backendName);
return kernelRegistry.get(key);
}
/**
* Returns the registered gradient info associated with the provided kernel.
* @param kernelName The official TF kernel name.
*/
function getGradient(kernelName) {
return gradRegistry.get(kernelName);
}
function getKernelsForBackend(backendName) {
const it = kernelRegistry.entries();
const result = [];
while (true) {
const { done, value } = it.next();
if (done) {
break;
}
const [key, config] = value;
const [backend,] = key.split('_');
if (backend === backendName) {
result.push(config);
}
}
return result;
}
/**
* Registers the function (forward pass) for the kernel in a global registry.
*
* @param config A config object with the following properties:
* - `kernelName` The official name of the kernel.
* - `backendName` The official name of the backend.
* - `kernelFunc` The function to run during the forward pass of the kernel.
* - `setupFunc` Optional. Gets called once, after the backend initializes.
* - `disposeFunc` Optional. Gets called once, right before the backend is
* disposed.
*/
function registerKernel(config) {
const { kernelName, backendName } = config;
const key = makeKey(kernelName, backendName);
if (kernelRegistry.has(key)) {
console.warn(`The kernel '${kernelName}' for backend ` +
`'${backendName}' is already registered`);
}
kernelRegistry.set(key, config);
}
/**
* Registers a gradient function for a given kernel in the global registry,
* to be used during the back-propagation of that kernel.
*
* @param config An object with the following properties:
* - `kernelName` The name of the kernel that the gradient function is for.
* - `gradFunc` The function to run during back-propagation.
*/
function registerGradient(config) {
const { kernelName } = config;
if (gradRegistry.has(kernelName)) {
// TODO (yassogba) after 3.0 assess whether we need to keep this gated
// to debug mode.
if (env().getBool('DEBUG')) {
console.warn(`Overriding the gradient for '${kernelName}'`);
}
}
gradRegistry.set(kernelName, config);
}
/**
* Removes the kernel function from the registry.
*
* @param kernelName The official name of the kernel.
* @param backendName The official name of the backend.
*
*/
function unregisterKernel(kernelName, backendName) {
const key = makeKey(kernelName, backendName);
if (!kernelRegistry.has(key)) {
throw new Error(`The kernel '${kernelName}' for backend ` +
`'${backendName}' is not registered`);
}
kernelRegistry.delete(key);
}
/** Removes the registered gradient from the global registry. */
function unregisterGradient(kernelName) {
if (!gradRegistry.has(kernelName)) {
throw new Error(`The gradient '${kernelName}' for backend is not registered`);
}
gradRegistry.delete(kernelName);
}
/**
* Finds kernels that have already been registered to a backend and re-registers
* them for a new backend. Useful for registering custom backends.
* @param registeredBackendName Already registered backend.
* @param newBackendName New backend.
*/
function copyRegisteredKernels(registeredBackendName, newBackendName) {
const kernels = getKernelsForBackend(registeredBackendName);
kernels.forEach(kernelConfig => {
const newKernelConfig = Object.assign({}, kernelConfig, { backendName: newBackendName });
registerKernel(newKernelConfig);
});
}
function makeKey(kernelName, backendName) {
return `${backendName}_${kernelName}`;
}
/**
* @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.
* =============================================================================
*/
/**
* Create typed array for scalar value. Used for storing in `DataStorage`.
*/
function createScalarValue(value, dtype) {
if (dtype === 'string') {
return encodeString(value);
}
return toTypedArray([value], dtype);
}
function noConversionNeeded(a, dtype) {
return (a instanceof Float32Array && dtype === 'float32') ||
(a instanceof Int32Array && dtype === 'int32') ||
(a instanceof Uint8Array && dtype === 'bool');
}
function toTypedArray(a, dtype) {
if (dtype === 'string') {
throw new Error('Cannot convert a string[] to a TypedArray');
}
if (Array.isArray(a)) {
a = flatten(a);
}
if (env().getBool('DEBUG')) {
checkConversionForErrors(a, dtype);
}
if (noConversionNeeded(a, dtype)) {
return a;
}
if (dtype == null || dtype === 'float32' || dtype === 'complex64') {
return new Float32Array(a);
}
else if (dtype === 'int32') {
return new Int32Array(a);
}
else if (dtype === 'bool') {
const bool = new Uint8Array(a.length);
for (let i = 0; i < bool.length; ++i) {
if (Math.round(a[i]) !== 0) {
bool[i] = 1;
}
}
return bool;
}
else {
throw new Error(`Unknown data type ${dtype}`);
}
}
/**
* Returns the current high-resolution time in milliseconds relative to an
* arbitrary time in the past. It works across different platforms (node.js,
* browsers).
*
* ```js
* console.log(tf.util.now());
* ```
*
* @doc {heading: 'Util', namespace: 'util'}
*/
function now() {
return env().platform.now();
}
/**
* Returns a platform-specific implementation of
* [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
*
* If `fetch` is defined on the global object (`window`, `process`, etc.),
* `tf.util.fetch` returns that function.
*
* If not, `tf.util.fetch` returns a platform-specific solution.
*
* ```js
* const resource = await tf.util.fetch('https://unpkg.com/@tensorflow/tfjs');
* // handle response
* ```
*
* @doc {heading: 'Util'}
*/
function fetch(path, requestInits) {
return env().platform.fetch(path, requestInits);
}
/**
* Encodes the provided string into bytes using the provided encoding scheme.
*
* @param s The string to encode.
* @param encoding The encoding scheme. Defaults to utf-8.
*
* @doc {heading: 'Util'}
*/
function encodeString(s, encoding = 'utf-8') {
encoding = encoding || 'utf-8';
return env().platform.encode(s, encoding);
}
/**
* Decodes the provided bytes into a string using the provided encoding scheme.
* @param bytes The bytes to decode.
*
* @param encoding The encoding scheme. Defaults to utf-8.
*
* @doc {heading: 'Util'}
*/
function decodeString(bytes, encoding = 'utf-8') {
encoding = encoding || 'utf-8';
return env().platform.decode(bytes, encoding);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
class Profiler {
constructor(backendTimer, logger) {
this.backendTimer = backendTimer;
this.logger = logger;
if (logger == null) {
this.logger = new Logger();
}
}
profileKernel(kernelName, inputs, f) {
let outputs;
const holdResultWrapperFn = () => {
outputs = f();
};
let timer;
const start = now();
if (this.backendTimer.timerAvailable()) {
timer = this.backendTimer.time(holdResultWrapperFn);
}
else {
holdResultWrapperFn();
for (const output of outputs) {
output.dataSync();
}
timer = Promise.resolve({ kernelMs: now() - start });
}
if (env().getBool('CHECK_COMPUTATION_FOR_ERRORS')) {
for (let i = 0; i < outputs.length; i++) {
const output = outputs[i];
// Dangling promise here because we don't want to propagate up
// asynchronicity.
output.data().then(tensorVals => {
checkComputationForErrors(tensorVals, output.dtype, kernelName);
});
}
}
const kernelProfile = {
kernelName,
outputs,
inputs,
timeMs: timer.then(timing => timing.kernelMs),
extraInfo: timer.then(timing => timing.getExtraProfileInfo != null ?
timing.getExtraProfileInfo() :
'')
};
return kernelProfile;
}
logKernelProfile(kernelProfile) {
const { kernelName, outputs, timeMs, inputs, extraInfo } = kernelProfile;
outputs.forEach(result => {
Promise.all([result.data(), timeMs, extraInfo]).then(valueContainer => {
this.logger.logKernelProfile(kernelName, result, valueContainer[0], valueContainer[1], inputs, valueContainer[2]);
});
});
}
}
function checkComputationForErrors(vals, dtype, kernelName) {
if (dtype !== 'float32') {
// Only floating point computations will generate NaN values
return false;
}
for (let i = 0; i < vals.length; i++) {
const num = vals[i];
if (isNaN(num) || !isFinite(num)) {
// Throwing custom exception so behavior is testable.
console.warn(`Found ${num} in the result of '${kernelName}'`);
return true;
}
}
return false;
}
class Logger {
logKernelProfile(name, result, vals, timeMs, inputs, extraInfo) {
const time = typeof timeMs === 'number' ? rightPad(`${timeMs}ms`, 9) :
timeMs['error'];
const paddedName = rightPad(name, 25);
const rank = result.rank;
const size = result.size;
const shape = rightPad(result.shape.toString(), 14);
let inputShapesDescription = '';
for (const name in inputs) {
const input = inputs[name];
if (input != null) {
// The input might be a non-tensor (e.g HTMLImageElement), in which case
// we claim the output shape as input shape.
const inputShape = input.shape || result.shape;
const inputRank = inputShape.length;
inputShapesDescription +=
`${name}: ${inputRank}D ${inputRank > 0 ? inputShape : ''} `;
}
}
console.log(`%c${paddedName}\t%c${time}\t%c${rank}D ${shape}\t%c${size}\t%c${inputShapesDescription}\t%c${extraInfo}`, 'font-weight:bold', 'color:red', 'color:blue', 'color: orange', 'color: green', 'color: steelblue');
}
}
/**
* @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.
* =============================================================================
*/
/**
* Computes a list of TapeNodes that connect x to y, filtering everything else
* out and preserving the order of the original tape elements.
*
* @param tape The tape elements to filter.
* @param xs The input Tensors.
* @param y The output Tensor.
*/
function getFilteredNodesXToY(tape, xs, y) {
// Forward pass to compute all the nodes and Tensors that are transitively a
// function of x.
const tensorsFromX = {};
const nodesFromX = {};
for (let i = 0; i < xs.length; i++) {
tensorsFromX[xs[i].id] = true;
}
for (let i = 0; i < tape.length; i++) {
const node = tape[i];
const nodeInputs = node.inputs;
for (const inputName in nodeInputs) {
const input = nodeInputs[inputName];
let anyInputFromX = false;
for (let j = 0; j < xs.length; j++) {
if (tensorsFromX[input.id]) {
node.outputs.forEach(output => tensorsFromX[output.id] = true);
anyInputFromX = true;
nodesFromX[node.id] = true;
break;
}
}
if (anyInputFromX) {
break;
}
}
}
// Backward pass to find all of the nodes and Tensors that lead to y.
const tensorsLeadToY = {};
tensorsLeadToY[y.id] = true;
const nodesToY = {};
for (let i = tape.length - 1; i >= 0; i--) {
const node = tape[i];
const nodeInputs = node.inputs;
// If any of the outputs lead to y, mark all of the inputs as leading to y.
for (let j = 0; j < node.outputs.length; j++) {
if (tensorsLeadToY[node.outputs[j].id]) {
for (const inputName in nodeInputs) {
tensorsLeadToY[nodeInputs[inputName].id] = true;
nodesToY[node.id] = true;
}
break;
}
}
}
// Return the paths that come from x and lead to y.
const filteredTape = [];
for (let i = 0; i < tape.length; i++) {
const node = tape[i];
if (nodesFromX[node.id] && nodesToY[node.id]) {
// Prune the inputs from the node that aren't a function of x.
const prunedInputs = {};
for (const inputName in node.inputs) {
const nodeInput = node.inputs[inputName];
if (tensorsFromX[nodeInput.id]) {
prunedInputs[inputName] = nodeInput;
}
}
// Copy the node and overwrite inputsAndArgs to the pruned version.
const prunedNode = Object.assign({}, node);
prunedNode.inputs = prunedInputs;
prunedNode.outputs = node.outputs;
filteredTape.push(prunedNode);
}
}
return filteredTape;
}
/**
* Backpropagate gradients through the filtered TapeNodes.
*
* @param tensorAccumulatedGradientMap A map of Tensor to its gradient. This map
* is mutated by this method.
* @param filteredTape The filtered TapeNodes to backprop through.
*/
function backpropagateGradients(tensorAccumulatedGradientMap, filteredTape, tidy, add) {
// Walk the tape backward and keep a map of Tensor to its gradient.
for (let i = filteredTape.length - 1; i >= 0; i--) {
const node = filteredTape[i];
const dys = [];
node.outputs.forEach(o => {
const gradTensor = tensorAccumulatedGradientMap[o.id];
if (gradTensor != null) {
dys.push(gradTensor);
}
else {
// This particular output is not in the back-propagation subgraph, so it
// does not affect the final output, thus we put null for its dy.
dys.push(null);
}
});
if (node.gradient == null) {
throw new Error(`Cannot compute gradient: gradient function not found ` +
`for ${node.kernelName}.`);
}
// Backprop dy through this node and accumulate gradients over the inputs.
const inputGradients = node.gradient(dys);
for (const inputName in node.inputs) {
if (!(inputName in inputGradients)) {
throw new Error(`Cannot backprop through input ${inputName}. ` +
`Available gradients found: ${Object.keys(inputGradients)}.`);
}
// Call the gradient function.
const dx = tidy(() => inputGradients[inputName]());
if (dx.dtype !== 'float32') {
throw new Error(`Error in gradient for op ${node.kernelName}. The gradient of input ` +
`${inputName} must have 'float32' dtype, but has '${dx.dtype}'`);
}
const x = node.inputs[inputName];
if (!arraysEqual(dx.shape, x.shape)) {
throw new Error(`Error in gradient for op ${node.kernelName}. The gradient of input ` +
`'${inputName}' has shape '${dx.shape}', which does not match ` +
`the shape of the input '${x.shape}'`);
}
if (tensorAccumulatedGradientMap[x.id] == null) {
tensorAccumulatedGradientMap[x.id] = dx;
}
else {
const curGradient = tensorAccumulatedGradientMap[x.id];
tensorAccumulatedGradientMap[x.id] = add(curGradient, dx);
curGradient.dispose();
}
}
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Maximum number of values before we decide to show ellipsis.
const FORMAT_LIMIT_NUM_VALS = 20;
// Number of first and last values to show when displaying a, b,...,y, z.
const FORMAT_NUM_FIRST_LAST_VALS = 3;
// Number of significant digits to show.
const FORMAT_NUM_SIG_DIGITS = 7;
function tensorToString(vals, shape, dtype, verbose) {
const strides = computeStrides(shape);
const padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides);
const rank = shape.length;
const valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol);
const lines = ['Tensor'];
if (verbose) {
lines.push(` dtype: ${dtype}`);
lines.push(` rank: ${rank}`);
lines.push(` shape: [${shape}]`);
lines.push(` values:`);
}
lines.push(valsLines.map(l => ' ' + l).join('\n'));
return lines.join('\n');
}
function computeMaxSizePerColumn(vals, shape, dtype, strides) {
const n = sizeFromShape(shape);
const numCols = strides[strides.length - 1];
const padPerCol = new Array(numCols).fill(0);
const rank = shape.length;
const valuesOrTuples = dtype === 'complex64' ? createComplexTuples(vals) : vals;
if (rank > 1) {
for (let row = 0; row < n / numCols; row++) {
const offset = row * numCols;
for (let j = 0; j < numCols; j++) {
padPerCol[j] = Math.max(padPerCol[j], valToString(valuesOrTuples[offset + j], 0, dtype).length);
}
}
}
return padPerCol;
}
function valToString(val, pad, dtype) {
let valStr;
if (Array.isArray(val)) {
valStr = `${parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS))} + ` +
`${parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS))}j`;
}
else if (isString(val)) {
valStr = `'${val}'`;
}
else if (dtype === 'bool') {
valStr = boolNumToString(val);
}
else {
valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString();
}
return rightPad(valStr, pad);
}
function boolNumToString(v) {
return v === 0 ? 'false' : 'true';
}
function subTensorToString(vals, shape, dtype, strides, padPerCol, isLast = true) {
const storagePerElement = dtype === 'complex64' ? 2 : 1;
const size = shape[0];
const rank = shape.length;
if (rank === 0) {
if (dtype === 'complex64') {
const complexTuple = createComplexTuples(vals);
return [valToString(complexTuple[0], 0, dtype)];
}
if (dtype === 'bool') {
return [boolNumToString(vals[0])];
}
return [vals[0].toString()];
}
if (rank === 1) {
if (size > FORMAT_LIMIT_NUM_VALS) {
const firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement;
let firstVals = Array.from(vals.slice(0, firstValsSize));
let lastVals = Array.from(vals.slice((size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement, size * storagePerElement));
if (dtype === 'complex64') {
firstVals = createComplexTuples(firstVals);
lastVals = createComplexTuples(lastVals);
}
return [
'[' +
firstVals.map((x, i) => valToString(x, padPerCol[i], dtype))
.join(', ') +
', ..., ' +
lastVals
.map((x, i) => valToString(x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i], dtype))
.join(', ') +
']'
];
}
const displayVals = dtype === 'complex64' ? createComplexTuples(vals) :
Array.from(vals);
return [
'[' +
displayVals.map((x, i) => valToString(x, padPerCol[i], dtype))
.join(', ') +
']'
];
}
// The array is rank 2 or more.
const subshape = shape.slice(1);
const substrides = strides.slice(1);
const stride = strides[0] * storagePerElement;
const lines = [];
if (size > FORMAT_LIMIT_NUM_VALS) {
for (let i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {
const start = i * stride;
const end = start + stride;
lines.push(...subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, false /* isLast */));
}
lines.push('...');
for (let i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {
const start = i * stride;
const end = start + stride;
lines.push(...subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, i === size - 1 /* isLast */));
}
}
else {
for (let i = 0; i < size; i++) {
const start = i * stride;
const end = start + stride;
lines.push(...subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, i === size - 1 /* isLast */));
}
}
const sep = rank === 2 ? ',' : '';
lines[0] = '[' + lines[0] + sep;
for (let i = 1; i < lines.length - 1; i++) {
lines[i] = ' ' + lines[i] + sep;
}
let newLineSep = ',\n';
for (let i = 2; i < rank; i++) {
newLineSep += '\n';
}
lines[lines.length - 1] =
' ' + lines[lines.length - 1] + ']' + (isLast ? '' : newLineSep);
return lines;
}
function createComplexTuples(vals) {
const complexTuples = [];
for (let i = 0; i < vals.length; i += 2) {
complexTuples.push([vals[i], vals[i + 1]]);
}
return complexTuples;
}
/**
* @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.
* =============================================================================
*/
/**
* A mutable object, similar to `tf.Tensor`, that allows users to set values
* at locations before converting to an immutable `tf.Tensor`.
*
* See `tf.buffer` for creating a tensor buffer.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
class TensorBuffer {
constructor(shape, dtype, values) {
this.dtype = dtype;
this.shape = shape.slice();
this.size = sizeFromShape(shape);
if (values != null) {
const n = values.length;
assert(n === this.size, () => `Length of values '${n}' does not match the size ` +
`inferred by the shape '${this.size}'.`);
}
if (dtype === 'complex64') {
throw new Error(`complex64 dtype TensorBuffers are not supported. Please create ` +
`a TensorBuffer for the real and imaginary parts separately and ` +
`call tf.complex(real, imag).`);
}
this.values = values || getArrayFromDType(dtype, this.size);
this.strides = computeStrides(shape);
}
/**
* Sets a value in the buffer at a given location.
*
* @param value The value to set.
* @param locs The location indices.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
set(value, ...locs) {
if (locs.length === 0) {
locs = [0];
}
assert(locs.length === this.rank, () => `The number of provided coordinates (${locs.length}) must ` +
`match the rank (${this.rank})`);
const index = this.locToIndex(locs);
this.values[index] = value;
}
/**
* Returns the value in the buffer at the provided location.
*
* @param locs The location indices.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
get(...locs) {
if (locs.length === 0) {
locs = [0];
}
let i = 0;
for (const loc of locs) {
if (loc < 0 || loc >= this.shape[i]) {
const msg = `Requested out of range element at ${locs}. ` +
` Buffer shape=${this.shape}`;
throw new Error(msg);
}
i++;
}
let index = locs[locs.length - 1];
for (let i = 0; i < locs.length - 1; ++i) {
index += this.strides[i] * locs[i];
}
return this.values[index];
}
locToIndex(locs) {
if (this.rank === 0) {
return 0;
}
else if (this.rank === 1) {
return locs[0];
}
let index = locs[locs.length - 1];
for (let i = 0; i < locs.length - 1; ++i) {
index += this.strides[i] * locs[i];
}
return index;
}
indexToLoc(index) {
if (this.rank === 0) {
return [];
}
else if (this.rank === 1) {
return [index];
}
const locs = new Array(this.shape.length);
for (let i = 0; i < locs.length - 1; ++i) {
locs[i] = Math.floor(index / this.strides[i]);
index -= locs[i] * this.strides[i];
}
locs[locs.length - 1] = index;
return locs;
}
get rank() {
return this.shape.length;
}
/**
* Creates an immutable `tf.Tensor` object from the buffer.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
toTensor() {
return trackerFn().makeTensor(this.values, this.shape, this.dtype);
}
}
// For tracking tensor creation and disposal.
let trackerFn = null;
// Used by chaining methods to call into ops.
let opHandler = null;
// Used to warn about deprecated methods.
let deprecationWarningFn = null;
// This here so that we can use this method on dev branches and keep the
// functionality at master.
// tslint:disable-next-line:no-unused-expression
[deprecationWarningFn];
/**
* An external consumer can register itself as the tensor tracker. This way
* the Tensor class can notify the tracker for every tensor created and
* disposed.
*/
function setTensorTracker(fn) {
trackerFn = fn;
}
/**
* An external consumer can register itself as the op handler. This way the
* Tensor class can have chaining methods that call into ops via the op
* handler.
*/
function setOpHandler(handler) {
opHandler = handler;
}
/**
* Sets the deprecation warning function to be used by this file. This way the
* Tensor class can be a leaf but still use the environment.
*/
function setDeprecationWarningFn(fn) {
deprecationWarningFn = fn;
}
/**
* A `tf.Tensor` object represents an immutable, multidimensional array of
* numbers that has a shape and a data type.
*
* For performance reasons, functions that create tensors do not necessarily
* perform a copy of the data passed to them (e.g. if the data is passed as a
* `Float32Array`), and changes to the data will change the tensor. This is not
* a feature and is not supported. To avoid this behavior, use the tensor before
* changing the input data or create a copy with `copy = tf.add(yourTensor, 0)`.
*
* See `tf.tensor` for details on how to create a `tf.Tensor`.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
class Tensor {
constructor(shape, dtype, dataId, id) {
/** Whether this tensor has been globally kept. */
this.kept = false;
this.isDisposedInternal = false;
this.shape = shape.slice();
this.dtype = dtype || 'float32';
this.size = sizeFromShape(shape);
this.strides = computeStrides(shape);
this.dataId = dataId;
this.id = id;
this.rankType = (this.rank < 5 ? this.rank.toString() : 'higher');
}
get rank() {
return this.shape.length;
}
/**
* Returns a promise of `tf.TensorBuffer` that holds the underlying data.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
async buffer() {
const vals = await this.data();
return opHandler.buffer(this.shape, this.dtype, vals);
}
/**
* Returns a `tf.TensorBuffer` that holds the underlying data.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
bufferSync() {
return opHandler.buffer(this.shape, this.dtype, this.dataSync());
}
/**
* Returns the tensor data as a nested array. The transfer of data is done
* asynchronously.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
async array() {
const vals = await this.data();
return toNestedArray(this.shape, vals, this.dtype === 'complex64');
}
/**
* Returns the tensor data as a nested array. The transfer of data is done
* synchronously.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
arraySync() {
return toNestedArray(this.shape, this.dataSync(), this.dtype === 'complex64');
}
/**
* Asynchronously downloads the values from the `tf.Tensor`. Returns a
* promise of `TypedArray` that resolves when the computation has finished.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
async data() {
this.throwIfDisposed();
const data = trackerFn().read(this.dataId);
if (this.dtype === 'string') {
const bytes = await data;
try {
return bytes.map(b => decodeString(b));
}
catch (_a) {
throw new Error('Failed to decode the string bytes into utf-8. ' +
'To get the original bytes, call tensor.bytes().');
}
}
return data;
}
/**
* Synchronously downloads the values from the `tf.Tensor`. This blocks the
* UI thread until the values are ready, which can cause performance issues.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
dataSync() {
this.throwIfDisposed();
const data = trackerFn().readSync(this.dataId);
if (this.dtype === 'string') {
try {
return data.map(b => decodeString(b));
}
catch (_a) {
throw new Error('Failed to decode the string bytes into utf-8. ' +
'To get the original bytes, call tensor.bytes().');
}
}
return data;
}
/** Returns the underlying bytes of the tensor's data. */
async bytes() {
this.throwIfDisposed();
const data = await trackerFn().read(this.dataId);
if (this.dtype === 'string') {
return data;
}
else {
return new Uint8Array(data.buffer);
}
}
/**
* Disposes `tf.Tensor` from memory.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
dispose() {
if (this.isDisposed) {
return;
}
trackerFn().disposeTensor(this);
this.isDisposedInternal = true;
}
get isDisposed() {
return this.isDisposedInternal;
}
throwIfDisposed() {
if (this.isDisposed) {
throw new Error(`Tensor is disposed.`);
}
}
/**
* Prints the `tf.Tensor`. See `tf.print` for details.
*
* @param verbose Whether to print verbose information about the tensor,
* including dtype and size.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
print(verbose = false) {
return opHandler.print(this, verbose);
}
/**
* Returns a copy of the tensor. See `tf.clone` for details.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
clone() {
this.throwIfDisposed();
return opHandler.clone(this);
}
/**
* Returns a human-readable description of the tensor. Useful for logging.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
toString(verbose = false) {
const vals = this.dataSync();
return tensorToString(vals, this.shape, this.dtype, verbose);
}
cast(dtype) {
this.throwIfDisposed();
return opHandler.cast(this, dtype);
}
variable(trainable = true, name, dtype) {
this.throwIfDisposed();
return trackerFn().makeVariable(this, trainable, name, dtype);
}
}
Object.defineProperty(Tensor, Symbol.hasInstance, {
value: (instance) => {
// Implementation note: we should use properties of the object that will be
// defined before the constructor body has finished executing (methods).
// This is because when this code is transpiled by babel, babel will call
// classCallCheck before the constructor body is run.
// See https://github.com/tensorflow/tfjs/issues/3384 for backstory.
return !!instance && instance.data != null && instance.dataSync != null &&
instance.throwIfDisposed != null;
}
});
function getGlobalTensorClass() {
// Use getGlobal so that we can augment the Tensor class across package
// boundaries becase the node resolution alg may result in different modules
// being returned for this file depending on the path they are loaded from.
return getGlobal('Tensor', () => {
return Tensor;
});
}
// Global side effect. Cache global reference to Tensor class
getGlobalTensorClass();
/**
* A mutable `tf.Tensor`, useful for persisting state, e.g. for training.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
class Variable extends Tensor {
constructor(initialValue, trainable, name, tensorId) {
super(initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId);
this.trainable = trainable;
this.name = name;
}
/**
* Assign a new `tf.Tensor` to this variable. The new `tf.Tensor` must have
* the same shape and dtype as the old `tf.Tensor`.
*
* @param newValue New tensor to be assigned to this variable.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
assign(newValue) {
if (newValue.dtype !== this.dtype) {
throw new Error(`dtype of the new value (${newValue.dtype}) and ` +
`previous value (${this.dtype}) must match`);
}
if (!arraysEqual(newValue.shape, this.shape)) {
throw new Error(`shape of the new value (${newValue.shape}) and ` +
`previous value (${this.shape}) must match`);
}
trackerFn().disposeTensor(this);
this.dataId = newValue.dataId;
trackerFn().incRef(this, null /* backend */);
}
dispose() {
trackerFn().disposeVariable(this);
this.isDisposedInternal = true;
}
}
Object.defineProperty(Variable, Symbol.hasInstance, {
value: (instance) => {
return instance instanceof Tensor && instance.assign != null &&
instance.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 Rank;
(function (Rank) {
Rank["R0"] = "R0";
Rank["R1"] = "R1";
Rank["R2"] = "R2";
Rank["R3"] = "R3";
Rank["R4"] = "R4";
Rank["R5"] = "R5";
Rank["R6"] = "R6";
})(Rank || (Rank = {}));
// Looks for upcasting types. Used, for example, in operations with mixed dtype
// inputs.
var UpcastInt32AndMap;
(function (UpcastInt32AndMap) {
UpcastInt32AndMap["float32"] = "float32";
UpcastInt32AndMap["int32"] = "int32";
UpcastInt32AndMap["bool"] = "int32";
UpcastInt32AndMap["complex64"] = "complex64";
})(UpcastInt32AndMap || (UpcastInt32AndMap = {}));
var UpcastBoolAndMap;
(function (UpcastBoolAndMap) {
UpcastBoolAndMap["float32"] = "float32";
UpcastBoolAndMap["int32"] = "int32";
UpcastBoolAndMap["bool"] = "bool";
UpcastBoolAndMap["complex64"] = "complex64";
})(UpcastBoolAndMap || (UpcastBoolAndMap = {}));
var UpcastFloat32AndMap;
(function (UpcastFloat32AndMap) {
UpcastFloat32AndMap["float32"] = "float32";
UpcastFloat32AndMap["int32"] = "float32";
UpcastFloat32AndMap["bool"] = "float32";
UpcastFloat32AndMap["complex64"] = "complex64";
})(UpcastFloat32AndMap || (UpcastFloat32AndMap = {}));
var UpcastComplex64AndMap;
(function (UpcastComplex64AndMap) {
UpcastComplex64AndMap["float32"] = "complex64";
UpcastComplex64AndMap["int32"] = "complex64";
UpcastComplex64AndMap["bool"] = "complex64";
UpcastComplex64AndMap["complex64"] = "complex64";
})(UpcastComplex64AndMap || (UpcastComplex64AndMap = {}));
const upcastTypeMap = {
'float32': UpcastFloat32AndMap,
'int32': UpcastInt32AndMap,
'bool': UpcastBoolAndMap,
'complex64': UpcastComplex64AndMap
};
function upcastType(typeA, typeB) {
if (typeA === 'string' || typeB === 'string') {
if (typeA === 'string' && typeB === 'string') {
return 'string';
}
throw new Error(`Can not upcast ${typeA} with ${typeB}`);
}
return upcastTypeMap[typeA][typeB];
}
/** Returns the output type after summation. */
function sumOutType(type) {
return upcastType(type, 'int32');
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function makeTypesMatch(a, b) {
if (a.dtype === b.dtype) {
return [a, b];
}
const dtype = upcastType(a.dtype, b.dtype);
return [a.cast(dtype), b.cast(dtype)];
}
function assertTypesMatch(a, b) {
assert(a.dtype === b.dtype, () => `The dtypes of the first(${a.dtype}) and` +
` second(${b.dtype}) input must match`);
}
function isTensorInList(tensor, tensorList) {
return tensorList.some(x => x.id === tensor.id);
}
/**
* Extracts any `Tensor`s found within the provided object.
*
* @param container an object that may be a `Tensor` or may directly contain
* `Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. In general it
* is safe to pass any object here, except that `Promise`s are not
* supported.
* @returns An array of `Tensors` found within the passed object. If the
* argument is simply a `Tensor', a list containing that `Tensor` is
* returned. If the object is not a `Tensor` or does not
* contain `Tensors`, an empty list is returned.
*/
function getTensorsInContainer(result) {
const list = [];
const seen = new Set();
walkTensorContainer(result, list, seen);
return list;
}
function walkTensorContainer(container, list, seen) {
if (container == null) {
return;
}
if (container instanceof Tensor) {
list.push(container);
return;
}
if (!isIterable(container)) {
return;
}
// Iteration over keys works also for arrays.
const iterable = container;
for (const k in iterable) {
const val = iterable[k];
if (!seen.has(val)) {
seen.add(val);
walkTensorContainer(val, list, seen);
}
}
}
// tslint:disable-next-line:no-any
function isIterable(obj) {
return Array.isArray(obj) || typeof obj === 'object';
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function isRegisteredKernelInvocation(kernelInvocation) {
return kernelInvocation.kernelName != null;
}
class EngineState {
constructor() {
// Public since optimizers will use it.
this.registeredVariables = {};
this.nextTapeNodeId = 0;
this.numBytes = 0;
this.numTensors = 0;
this.numStringTensors = 0;
this.numDataBuffers = 0;
// Number of nested tf.grad() statements when computing higher-order
// gradients. E.g. `1` for first-order gradients and `2` for second-order
// gradients. Used to track if the tape should be removed after a backprop.
this.gradientDepth = 0;
// Number of nested kernel calls. When kernel depth is greater than 1, we turn
// off the tape.
this.kernelDepth = 0;
this.scopeStack = [];
/**
* Keeps track of the number of data moves during a kernel execution. We
* maintain a stack since kernels can call other kernels, recursively.
*/
this.numDataMovesStack = [];
this.nextScopeId = 0;
this.tensorInfo = new WeakMap();
this.profiling = false;
this.activeProfile = {
newBytes: 0,
newTensors: 0,
peakBytes: 0,
kernels: [],
result: null,
get kernelNames() {
return Array.from(new Set(this.kernels.map(k => k.name)));
}
};
}
dispose() {
for (const variableName in this.registeredVariables) {
this.registeredVariables[variableName].dispose();
}
}
}
class Engine {
constructor(ENV) {
this.ENV = ENV;
this.registry = {};
this.registryFactory = {};
this.pendingBackendInitId = 0;
this.state = new EngineState();
}
async ready() {
if (this.pendingBackendInit != null) {
return this.pendingBackendInit.then(() => { });
}
if (this.backendInstance != null) {
return;
}
const sortedBackends = this.getSortedBackends();
for (let i = 0; i < sortedBackends.length; i++) {
const backendName = sortedBackends[i];
const success = await this.initializeBackend(backendName).success;
if (success) {
await this.setBackend(backendName);
return;
}
}
throw new Error(`Could not initialize any backends, all backend initializations ` +
`failed.`);
}
get backend() {
if (this.pendingBackendInit != null) {
throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make ` +
`sure to await tf.ready() or await tf.setBackend() before calling ` +
`other methods`);
}
if (this.backendInstance == null) {
const { name, asyncInit } = this.initializeBackendsAndReturnBest();
if (asyncInit) {
throw new Error(`The highest priority backend '${name}' has not yet been ` +
`initialized. Make sure to await tf.ready() or ` +
`await tf.setBackend() before calling other methods`);
}
this.setBackend(name);
}
return this.backendInstance;
}
backendNames() {
return Object.keys(this.registryFactory);
}
findBackend(backendName) {
if (!(backendName in this.registry)) {
// If the backend hasn't been initialized but we have a registry entry for
// it, initialize it and return it.
if (backendName in this.registryFactory) {
const { asyncInit } = this.initializeBackend(backendName);
if (asyncInit) {
// Backend is not ready yet.
return null;
}
}
else {
return null;
}
}
return this.registry[backendName];
}
findBackendFactory(backendName) {
if (!(backendName in this.registryFactory)) {
return null;
}
return this.registryFactory[backendName].factory;
}
registerBackend(backendName, factory, priority = 1) {
if (backendName in this.registryFactory) {
console.warn(`${backendName} backend was already registered. ` +
`Reusing existing backend factory.`);
return false;
}
this.registryFactory[backendName] = { factory, priority };
return true;
}
async setBackend(backendName) {
if (this.registryFactory[backendName] == null) {
throw new Error(`Backend name '${backendName}' not found in registry`);
}
this.backendName = backendName;
if (this.registry[backendName] == null) {
this.backendInstance = null;
const { success, asyncInit } = this.initializeBackend(backendName);
const result = asyncInit ? await success : success;
if (!result) {
return false;
}
}
this.backendInstance = this.registry[backendName];
this.setupRegisteredKernels();
// Reset the profiler.
this.profiler = new Profiler(this.backendInstance);
return true;
}
setupRegisteredKernels() {
const kernels = getKernelsForBackend(this.backendName);
kernels.forEach(kernel => {
if (kernel.setupFunc != null) {
kernel.setupFunc(this.backendInstance);
}
});
}
disposeRegisteredKernels(backendName) {
const kernels = getKernelsForBackend(backendName);
kernels.forEach(kernel => {
if (kernel.disposeFunc != null) {
kernel.disposeFunc(this.registry[backendName]);
}
});
}
/**
* Initializes a backend by looking up the backend name in the factory
* registry and calling the factory method. Returns a boolean representing
* whether the initialization of the backend suceeded. Throws an error if
* there is no backend in the factory registry.
*/
initializeBackend(backendName) {
const registryFactoryEntry = this.registryFactory[backendName];
if (registryFactoryEntry == null) {
throw new Error(`Cannot initialize backend ${backendName}, no registration found.`);
}
try {
const backend = registryFactoryEntry.factory();
/* Test if the factory returns a promise.
Done in a more liberal way than
previous 'Promise.resolve(backend)===backend'
as we needed to account for custom Promise
implementations (e.g. Angular) */
if (backend && !(backend instanceof KernelBackend) &&
typeof backend.then === 'function') {
const promiseId = ++this.pendingBackendInitId;
const success = backend
.then(backendInstance => {
// Outdated promise. Another backend was set in the meantime.
if (promiseId < this.pendingBackendInitId) {
return false;
}
this.registry[backendName] = backendInstance;
this.pendingBackendInit = null;
return true;
})
.catch(err => {
// Outdated promise. Another backend was set in the meantime.
if (promiseId < this.pendingBackendInitId) {
return false;
}
this.pendingBackendInit = null;
console.warn(`Initialization of backend ${backendName} failed`);
console.warn(err.stack || err.message);
return false;
});
this.pendingBackendInit = success;
return { success, asyncInit: true };
}
else {
this.registry[backendName] = backend;
return { success: true, asyncInit: false };
}
}
catch (err) {
console.warn(`Initialization of backend ${backendName} failed`);
console.warn(err.stack || err.message);
return { success: false, asyncInit: false };
}
}
removeBackend(backendName) {
if (!(backendName in this.registryFactory)) {
throw new Error(`${backendName} backend not found in registry`);
}
if (this.backendName === backendName && this.pendingBackendInit != null) {
// There is a pending promise of the backend we want to remove. Make it
// obsolete.
this.pendingBackendInitId++;
}
if (backendName in this.registry) {
this.disposeRegisteredKernels(backendName);
this.registry[backendName].dispose();
delete this.registry[backendName];
}
delete this.registryFactory[backendName];
// Unset the backend if it is active.
if (this.backendName === backendName) {
this.pendingBackendInit = null;
this.backendName = null;
this.backendInstance = null;
}
}
getSortedBackends() {
if (Object.keys(this.registryFactory).length === 0) {
throw new Error('No backend found in registry.');
}
return Object.keys(this.registryFactory).sort((a, b) => {
// Highest priority comes first.
return this.registryFactory[b].priority -
this.registryFactory[a].priority;
});
}
initializeBackendsAndReturnBest() {
const sortedBackends = this.getSortedBackends();
for (let i = 0; i < sortedBackends.length; i++) {
const backendName = sortedBackends[i];
const { success, asyncInit } = this.initializeBackend(backendName);
if (asyncInit || success) {
return { name: backendName, asyncInit };
}
}
throw new Error(`Could not initialize any backends, all backend initializations ` +
`failed.`);
}
moveData(backend, dataId) {
const info = this.state.tensorInfo.get(dataId);
const srcBackend = info.backend;
const values = this.readSync(dataId);
const refCount = srcBackend.refCount(dataId);
// Delete the tensor from the old backend and move it to the new
// backend.
srcBackend.disposeData(dataId, true);
info.backend = backend;
backend.move(dataId, values, info.shape, info.dtype, refCount);
if (this.shouldCheckForMemLeaks()) {
// Track the number of moves during a kernel execution to correctly
// detect memory leaks.
this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;
}
}
tidy(nameOrFn, fn) {
let name = null;
if (fn == null) {
// Called with only 1 argument.
if (typeof nameOrFn !== 'function') {
throw new Error('Please provide a function to tidy()');
}
fn = nameOrFn;
}
else {
// Called with 2 arguments.
if (typeof nameOrFn !== 'string' && !(nameOrFn instanceof String)) {
throw new Error('When calling with two arguments, the first argument ' +
'to tidy() must be a string');
}
if (typeof fn !== 'function') {
throw new Error('When calling with two arguments, the 2nd argument ' +
'to tidy() must be a function');
}
name = nameOrFn;
// TODO(nsthorat,smilkov): Do operation logging and performance
// profiling.
}
let result;
return this.scopedRun(() => this.startScope(name), () => this.endScope(result), () => {
result = fn();
if (result instanceof Promise) {
console.error('Cannot return a Promise inside of tidy.');
}
return result;
});
}
scopedRun(start, end, f) {
start();
try {
const res = f();
end();
return res;
}
catch (ex) {
end();
throw ex;
}
}
nextTensorId() {
return Engine.nextTensorId++;
}
nextVariableId() {
return Engine.nextVariableId++;
}
/**
* This method is called instead of the public-facing tensor.clone() when
* saving a tensor for backwards pass. It makes sure to add the clone
* operation to the tape regardless of being called inside a kernel
* execution.
*/
clone(x) {
const y = ENGINE.runKernel(Identity, { x });
const inputs = { x };
const grad = (dy) => ({
x: () => {
const dtype = 'float32';
const gradInputs = { x: dy };
const attrs = { dtype };
return ENGINE.runKernel(Cast, gradInputs,
// tslint:disable-next-line: no-unnecessary-type-assertion
attrs);
}
});
const saved = [];
this.addTapeNode(this.state.activeScope.name, inputs, [y], grad, saved, {});
return y;
}
/**
* Execute a kernel with the given name and return the output tensor.
*
* @param kernelName The name of the kernel to execute.
* @param inputs A map of input names to tensors.
* @param attrs A map of attribute names to their values. An attribute is a
* primitive (non-tensor) input to the kernel.
* @param inputsToSave A list of tensors, inputs to save for the backprop
* computation.
* @param outputsToSave A list of booleans, specifying which output to save
* for the backprop computation. These are booleans since the output
* tensors are not visible to the user.
*/
runKernel(kernelName, inputs, attrs) {
const hasKernel = getKernel(kernelName, this.backendName) != null;
if (!hasKernel) {
throw new Error(`Kernel '${kernelName}' not registered for backend '${this.backendName}'`);
}
return this.runKernelFunc({ kernelName, inputs, attrs });
}
shouldCheckForMemLeaks() {
return this.ENV.getBool('IS_TEST');
}
checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos) {
const numDataIdsAfter = this.backend.numDataIds();
// Count the number of data ids associated with the result of the kernel.
let numOutputDataIds = 0;
outInfos.forEach(info => {
// Complex numbers allocate 3 data ids, one for 'real', one for
// 'imaginary', and one for the container that holds the former two.
numOutputDataIds += (info.dtype === 'complex64' ? 3 : 1);
});
// Account for the number of moves during kernel execution. A "data move"
// can happen in the middle of a kernel execution, placing a new (key,value)
// pair in the data storage. Since data moves have net zero effect (we
// always remove the data from the old backend), we have to cancel them out
// when detecting memory leaks.
const numMoves = this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1];
const dataIdsLeaked = numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves;
if (dataIdsLeaked > 0) {
throw new Error(`Backend '${this.backendName}' has an internal memory leak ` +
`(${dataIdsLeaked} data ids) after running '${kernelName}'`);
}
}
/**
* Internal helper method to execute a kernel Func
*
* Use `runKernel` to execute kernels from outside of engine.
*/
runKernelFunc(kernelParams) {
let outputs;
let saved = [];
const isTapeOn = this.isTapeOn();
const startingBytecount = this.state.numBytes;
const startingNumTensors = this.state.numTensors;
if (this.shouldCheckForMemLeaks()) {
this.state.numDataMovesStack.push(0);
}
let kernelFunc;
if (this.backendName == null) {
// backend has not been initialized yet (backend initialization is lazy
// can be deferred until an op/ kernel is run).
// The below getter has side effects that will try to initialize the
// backend and set properties like this.backendName
// tslint:disable-next-line: no-unused-expression
this.backend;
}
let out;
const kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ?
kernelParams.kernelName :
this.state.activeScope != null ? this.state.activeScope.name : '';
// Create the kernelFunc from either a registered kernel OR passed in
// forward/backward functions (used by custom grad). In this context a
// kernelFunc wraps a kernel implementation with some bookkeeping.
if (isRegisteredKernelInvocation(kernelParams)) {
const { kernelName, inputs, attrs } = kernelParams;
if (this.backendName == null) {
// backend has not been initialized yet (backend initialization is lazy
// can be deferred until an op/ kernel is run).
// The below getter has side effects that will try to initialize the
// backend and set properties like this.backendName
// tslint:disable-next-line: no-unused-expression
this.backend;
}
const kernel = getKernel(kernelName, this.backendName);
assert(kernel != null, () => `Cannot find registered kernel '${kernelName}' for backend '${this.backendName}'`);
kernelFunc = () => {
const numDataIdsBefore = this.backend.numDataIds();
out = kernel.kernelFunc({ inputs, attrs, backend: this.backend });
const outInfos = Array.isArray(out) ? out : [out];
if (this.shouldCheckForMemLeaks()) {
this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos);
}
const outTensors = outInfos.map((outInfo) => {
// todo (yassogba) remove this option (Tensor) when node backend
// methods have been modularized and they all return tensorInfo.
// TensorInfos do not have a rank attribute.
if (outInfo.rank != null) {
return outInfo;
}
const { dataId, shape, dtype } = outInfo;
return this.makeTensorFromDataId(dataId, shape, dtype);
});
// Save any required inputs and outputs.
// Do not save unless we are recording to the tape. Otherwise it would
// cause a mem leak since there would be no backprop for these tensors
// (which would otherwise dispose them).
if (isTapeOn) {
const tensorsToSave = this.getTensorsForGradient(kernelName, inputs, outTensors);
saved = this.saveTensorsForBackwardMode(tensorsToSave);
}
return outTensors;
};
}
else {
const { forwardFunc } = kernelParams;
// Running a customGrad op.
const saveFunc = (tensors) => {
// Do not save unless we are recording to the tape. Otherwise it would
// cause a mem leak since we would never run backprop, which disposes
// the kept tensors.
if (!isTapeOn) {
return;
}
saved = tensors.map(tensor => this.keep(this.clone(tensor)));
};
kernelFunc = () => {
const numDataIdsBefore = this.backend.numDataIds();
out = this.tidy(() => forwardFunc(this.backend, saveFunc));
const outs = (Array.isArray(out) ? out : [out]);
if (this.shouldCheckForMemLeaks()) {
// Scope name is used to print a more helpful error message if needed.
this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs);
}
return outs;
};
}
//
// Run the kernelFunc. Optionally profiling it.
//
const { inputs, attrs } = kernelParams;
const backwardsFunc = isRegisteredKernelInvocation(kernelParams) ?
null :
kernelParams.backwardsFunc;
let kernelProfile;
this.scopedRun(
// Stop recording to a tape when running a kernel.
() => this.state.kernelDepth++, () => this.state.kernelDepth--, () => {
if (!this.ENV.getBool('DEBUG') && !this.state.profiling) {
outputs = kernelFunc();
}
else {
kernelProfile = this.profiler.profileKernel(kernelOrScopeName, inputs, () => kernelFunc());
if (this.ENV.getBool('DEBUG')) {
this.profiler.logKernelProfile(kernelProfile);
}
outputs = kernelProfile.outputs;
}
});
if (isTapeOn) {
this.addTapeNode(kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs);
}
if (this.state.profiling) {
this.state.activeProfile.kernels.push({
name: kernelOrScopeName,
bytesAdded: this.state.numBytes - startingBytecount,
totalBytesSnapshot: this.state.numBytes,
tensorsAdded: this.state.numTensors - startingNumTensors,
totalTensorsSnapshot: this.state.numTensors,
inputShapes: Object.keys(inputs).map(key => inputs[key] != null ? inputs[key].shape : null),
outputShapes: outputs.map(item => item.shape),
kernelTimeMs: kernelProfile.timeMs,
extraInfo: kernelProfile.extraInfo
});
}
return (Array.isArray(out) ? outputs : outputs[0]);
}
/**
* Saves tensors used in forward mode for use in backward mode.
*
* @param tensors the list of tensors to save.
*/
saveTensorsForBackwardMode(tensors) {
const saved = tensors.map(tensor => this.keep(this.clone(tensor)));
return saved;
}
/**
* Returns a list of tensors to save for a given gradient calculation.
*
* @param kernelName name of kernel to look up gradient for.
* @param inputs a map of input tensors.
* @param outputs an array of output tensors from forward mode of kernel.
*/
getTensorsForGradient(kernelName, inputs, outputs) {
const gradConfig = getGradient(kernelName);
if (gradConfig != null) {
const inputsToSave = gradConfig.inputsToSave || [];
const outputsToSave = gradConfig.outputsToSave || [];
// If saveAllInputs is true, all inputs will be saved. Otherwise, inputs
// specified in inputsToSave will be saved.
let inputTensorsToSave;
if (gradConfig.saveAllInputs) {
assert(Array.isArray(inputs), () => 'saveAllInputs is true, expected inputs to be an array.');
inputTensorsToSave = Object.keys(inputs).map((key) => inputs[key]);
}
else {
inputTensorsToSave = inputsToSave.map((inputName) => inputs[inputName]);
}
const outputTensorsToSave = outputs.filter((_, i) => outputsToSave[i]);
return inputTensorsToSave.concat(outputTensorsToSave);
}
// We return an empty list rather than throw an error because the kernel we
// are looking up may not actually be relevant to backproping through the
// overall function
//
// See 'does not error if irrelevant (pruned) ops are missing grads' test
// in gradients_test.ts for an example.
return [];
}
/**
* Internal method used by public APIs for tensor creation. Makes a new
* tensor with the provided shape, dtype and values. It always
* creates a new data id and writes the values to the underlying backend.
*/
makeTensor(values, shape, dtype, backend) {
if (values == null) {
throw new Error('Values passed to engine.makeTensor() are null');
}
dtype = dtype || 'float32';
backend = backend || this.backend;
let backendVals = values;
if (dtype === 'string' && isString(values[0])) {
backendVals = values.map(d => encodeString(d));
}
const dataId = backend.write(backendVals, shape, dtype);
const t = new Tensor(shape, dtype, dataId, this.nextTensorId());
this.trackTensor(t, backend);
// Count bytes for string tensors.
if (dtype === 'string') {
const info = this.state.tensorInfo.get(dataId);
const newBytes = bytesFromStringArray(backendVals);
this.state.numBytes += newBytes - info.bytes;
info.bytes = newBytes;
}
return t;
}
/**
* Internal method used by backends. Makes a new tensor
* that is a wrapper around an existing data id. It doesn't create
* a new data id, only increments the ref count used in memory tracking.
*/
makeTensorFromDataId(dataId, shape, dtype, backend) {
dtype = dtype || 'float32';
const t = new Tensor(shape, dtype, dataId, this.nextTensorId());
this.trackTensor(t, backend);
return t;
}
makeVariable(initialValue, trainable = true, name, dtype) {
name = name || this.nextVariableId().toString();
if (dtype != null && dtype !== initialValue.dtype) {
initialValue = initialValue.cast(dtype);
}
const v = new Variable(initialValue, trainable, name, this.nextTensorId());
if (this.state.registeredVariables[v.name] != null) {
throw new Error(`Variable with name ${v.name} was already registered`);
}
this.state.registeredVariables[v.name] = v;
this.incRef(v, this.backend);
return v;
}
trackTensor(a, backend) {
this.state.numTensors++;
if (a.dtype === 'string') {
this.state.numStringTensors++;
}
// Bytes for complex numbers are counted by their components. Bytes for
// string tensors are counted when writing values.
let bytes = 0;
if (a.dtype !== 'complex64' && a.dtype !== 'string') {
bytes = a.size * bytesPerElement(a.dtype);
}
this.state.numBytes += bytes;
if (!this.state.tensorInfo.has(a.dataId)) {
this.state.numDataBuffers++;
this.state.tensorInfo.set(a.dataId, {
backend: backend || this.backend,
dtype: a.dtype,
shape: a.shape,
bytes
});
}
if (!(a instanceof Variable)) {
this.track(a);
}
}
// Track the tensor by dataId and increase the refCount for the dataId in the
// backend.
// TODO(pyu10055): This is currently used by makeVariable method, to increase
// refCount on the backend for the dataId. It can potentially be replaced with
// Identity op indead of calling backend directly.
incRef(a, backend) {
this.trackTensor(a, backend);
this.backend.incRef(a.dataId);
}
removeDataId(dataId, backend) {
if (this.state.tensorInfo.has(dataId) &&
this.state.tensorInfo.get(dataId).backend === backend) {
this.state.tensorInfo.delete(dataId);
this.state.numDataBuffers--;
}
}
disposeTensor(a) {
if (!this.state.tensorInfo.has(a.dataId)) {
return;
}
const info = this.state.tensorInfo.get(a.dataId);
this.state.numTensors--;
if (a.dtype === 'string') {
this.state.numStringTensors--;
this.state.numBytes -= info.bytes;
}
// Don't count bytes for complex numbers as they are counted by their
// components.
if (a.dtype !== 'complex64' && a.dtype !== 'string') {
const bytes = a.size * bytesPerElement(a.dtype);
this.state.numBytes -= bytes;
}
// Remove the reference to dataId if backend dispose the data successfully
if (info.backend.disposeData(a.dataId)) {
this.removeDataId(a.dataId, info.backend);
}
// TODO(nsthorat): Construct an error and save the stack trace for
// debugging when in debug mode. Creating a stack trace is too expensive
// to do unconditionally.
}
disposeVariables() {
for (const varName in this.state.registeredVariables) {
const v = this.state.registeredVariables[varName];
this.disposeVariable(v);
}
}
disposeVariable(v) {
this.disposeTensor(v);
if (this.state.registeredVariables[v.name] != null) {
delete this.state.registeredVariables[v.name];
}
}
memory() {
const info = this.backend.memory();
info.numTensors = this.state.numTensors;
info.numDataBuffers = this.state.numDataBuffers;
info.numBytes = this.state.numBytes;
if (this.state.numStringTensors > 0) {
info.unreliable = true;
if (info.reasons == null) {
info.reasons = [];
}
info.reasons.push('Memory usage by string tensors is approximate ' +
'(2 bytes per character)');
}
return info;
}
async profile(query) {
this.state.profiling = true;
const startBytes = this.state.numBytes;
const startNumTensors = this.state.numTensors;
this.state.activeProfile.kernels = [];
this.state.activeProfile.result = await query();
this.state.profiling = false;
this.state.activeProfile.peakBytes = Math.max(...this.state.activeProfile.kernels.map(d => d.totalBytesSnapshot));
this.state.activeProfile.newBytes = this.state.numBytes - startBytes;
this.state.activeProfile.newTensors =
this.state.numTensors - startNumTensors;
for (const kernel of this.state.activeProfile.kernels) {
kernel.kernelTimeMs = await kernel.kernelTimeMs;
kernel.extraInfo = await kernel.extraInfo;
}
return this.state.activeProfile;
}
isTapeOn() {
return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;
}
addTapeNode(kernelName, inputs, outputs, gradientsFunc, saved, attrs) {
const tapeNode = { id: this.state.nextTapeNodeId++, kernelName, inputs, outputs, saved };
const gradConfig = getGradient(kernelName);
if (gradConfig != null) {
gradientsFunc = gradConfig.gradFunc;
}
if (gradientsFunc != null) {
tapeNode.gradient = (dys) => {
// TODO(smilkov): To optimize back-prop, pass dys that are not used in
// the backprop graph to the user as null instead of zeros
dys = dys.map((dy, i) => {
if (dy == null) {
const output = outputs[i];
const vals = makeZerosTypedArray(output.size, output.dtype);
return this.makeTensor(vals, output.shape, output.dtype);
}
return dy;
});
// Grad functions of ops with single outputs expect a dy, while ops
// with multiple outputs expect dys (array of dy).
return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs);
};
}
this.state.activeTape.push(tapeNode);
}
keep(result) {
result.kept = true;
return result;
}
startTape() {
if (this.state.gradientDepth === 0) {
this.state.activeTape = [];
}
this.state.gradientDepth++;
}
endTape() {
this.state.gradientDepth--;
}
/**
* Start a scope. Use this with endScope() to achieve the same functionality
* as scope() without the need for a function closure.
*/
startScope(name) {
const scopeInfo = {
track: [],
name: 'unnamed scope',
id: this.state.nextScopeId++
};
if (name) {
scopeInfo.name = name;
}
this.state.scopeStack.push(scopeInfo);
this.state.activeScope = scopeInfo;
}
/**
* End a scope. Use this with startScope() to achieve the same functionality
* as scope() without the need for a function closure.
*/
endScope(result) {
const tensorsToTrackInParent = getTensorsInContainer(result);
const tensorsToTrackInParentSet = new Set(tensorsToTrackInParent.map(t => t.id));
// Dispose the arrays tracked in this scope.
for (let i = 0; i < this.state.activeScope.track.length; i++) {
const tensor = this.state.activeScope.track[i];
if (!tensor.kept && !tensorsToTrackInParentSet.has(tensor.id)) {
tensor.dispose();
}
}
const oldScope = this.state.scopeStack.pop();
this.state.activeScope = this.state.scopeStack.length === 0 ?
null :
this.state.scopeStack[this.state.scopeStack.length - 1];
// Track the current result in the parent scope.
tensorsToTrackInParent.forEach(tensor => {
// Only track the tensor if was allocated in the inner scope and is not
// globally kept.
if (!tensor.kept && tensor.scopeId === oldScope.id) {
this.track(tensor);
}
});
}
/**
* Returns gradients of `f` with respect to each of the `xs`. The gradients
* returned are of the same length as `xs`, but some might be null if `f`
* was not a function of that `x`. It also takes optional dy to multiply the
* gradient, which defaults to `1`.
*/
gradients(f, xs, dy, allowNoGradients = false) {
assert(xs.length > 0, () => 'gradients() received an empty list of xs.');
if (dy != null && dy.dtype !== 'float32') {
throw new Error(`dy must have 'float32' dtype, but has '${dy.dtype}'`);
}
const y = this.scopedRun(() => this.startTape(), () => this.endTape(), () => this.tidy('forward', f));
assert(y instanceof Tensor, () => 'The result y returned by f() must be a tensor.');
// Filter out the nodes that don't connect x => y.
const filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y);
if (!allowNoGradients && filteredTape.length === 0 && xs.length > 0) {
throw new Error('Cannot compute gradient of y=f(x) with respect to x. Make sure ' +
'that the f you passed encloses all operations that lead from x ' +
'to y.');
}
return this.tidy('backward', () => {
const accumulatedGradientMap = {};
accumulatedGradientMap[y.id] = (dy == null) ? ones(y.shape) : dy;
// Backprop gradients through the filtered nodes.
backpropagateGradients(accumulatedGradientMap, filteredTape,
// Pass the tidy function to avoid circular dep with `tape.ts`.
f => this.tidy(f),
// Pass an add function to avoide a circular dep with `tape.ts`.
add);
const grads = xs.map(x => accumulatedGradientMap[x.id]);
if (this.state.gradientDepth === 0) {
// This means that we are not computing higher-order gradients
// and can clean up the tape.
this.state.activeTape.forEach(node => {
for (const tensor of node.saved) {
tensor.dispose();
}
});
this.state.activeTape = null;
}
return { value: y, grads };
});
}
customGrad(f) {
assert(isFunction(f), () => 'The f passed in customGrad(f) must be a function.');
return (...inputs) => {
assert(inputs.every(t => t instanceof Tensor), () => 'The args passed in customGrad(f)(x1, x2,...) must all be ' +
'tensors');
let res;
const inputMap = {};
inputs.forEach((input, i) => {
inputMap[i] = input;
});
const forwardFunc = (_, save) => {
res = f(...[...inputs, save]);
assert(res.value instanceof Tensor, () => 'The function f passed in customGrad(f) must return an ' +
'object where `obj.value` is a tensor');
assert(isFunction(res.gradFunc), () => 'The function f passed in customGrad(f) must return an ' +
'object where `obj.gradFunc` is a function.');
return res.value;
};
const backwardsFunc = (dy, saved) => {
const gradRes = res.gradFunc(dy, saved);
const grads = Array.isArray(gradRes) ? gradRes : [gradRes];
assert(grads.length === inputs.length, () => 'The function f passed in customGrad(f) must return an ' +
'object where `obj.gradFunc` is a function that returns ' +
'the same number of tensors as inputs passed to f(...).');
assert(grads.every(t => t instanceof Tensor), () => 'The function f passed in customGrad(f) must return an ' +
'object where `obj.gradFunc` is a function that returns ' +
'a list of only tensors.');
const gradMap = {};
grads.forEach((grad, i) => {
gradMap[i] = () => grad;
});
return gradMap;
};
return this.runKernelFunc({
forwardFunc,
backwardsFunc,
inputs: inputMap,
});
};
}
readSync(dataId) {
// Route the read to the correct backend.
const info = this.state.tensorInfo.get(dataId);
return info.backend.readSync(dataId);
}
read(dataId) {
// Route the read to the correct backend.
const info = this.state.tensorInfo.get(dataId);
return info.backend.read(dataId);
}
async time(query) {
const start = now();
const timingInfo = await this.backend.time(query);
timingInfo.wallMs = now() - start;
return timingInfo;
}
/**
* Tracks a Tensor in the current scope to be automatically cleaned up
* when the current scope ends, and returns the value.
*
* @param result The Tensor to track in the current scope.
*/
track(result) {
if (this.state.activeScope != null) {
result.scopeId = this.state.activeScope.id;
this.state.activeScope.track.push(result);
}
return result;
}
get registeredVariables() {
return this.state.registeredVariables;
}
/**
* Resets the engine state. Removes all backends but does not remove
* registered backend factories.
*/
reset() {
// Make any pending promise obsolete.
this.pendingBackendInitId++;
this.state.dispose();
this.ENV.reset();
this.state = new EngineState();
for (const backendName in this.registry) {
this.disposeRegisteredKernels(backendName);
this.registry[backendName].dispose();
delete this.registry[backendName];
}
this.backendName = null;
this.backendInstance = null;
this.pendingBackendInit = null;
}
}
Engine.nextTensorId = 0;
Engine.nextVariableId = 0;
function ones(shape) {
const values = makeOnesTypedArray(sizeFromShape(shape), 'float32');
return ENGINE.makeTensor(values, shape, 'float32');
}
function getOrMakeEngine() {
const ns = getGlobalNamespace();
if (ns._tfengine == null) {
const environment = new Environment(ns);
ns._tfengine = new Engine(environment);
}
setEnvironmentGlobal(ns._tfengine.ENV);
// Tell the current tensor interface that the global engine is responsible
// for tracking.
setTensorTracker(() => ns._tfengine);
return ns._tfengine;
}
const ENGINE = getOrMakeEngine();
/**
* A implementation of the add op for use within engine and tape.
*
* This allows us to avoid a circular dependency between add.ts and engine.
* It is exported to be available in tape tests.
*/
function add(a, b) {
// We duplicate Add here to avoid a circular dependency with add.ts.
const inputs = { a, b };
return ENGINE.runKernel(Add, inputs);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function inferShape(val, dtype) {
let firstElem = val;
if (isTypedArray(val)) {
return dtype === 'string' ? [] : [val.length];
}
if (!Array.isArray(val)) {
return []; // Scalar.
}
const shape = [];
while (Array.isArray(firstElem) ||
isTypedArray(firstElem) && dtype !== 'string') {
shape.push(firstElem.length);
firstElem = firstElem[0];
}
if (Array.isArray(val) &&
env().getBool('TENSORLIKE_CHECK_SHAPE_CONSISTENCY')) {
deepAssertShapeConsistency(val, shape, []);
}
return shape;
}
function deepAssertShapeConsistency(val, shape, indices) {
indices = indices || [];
if (!(Array.isArray(val)) && !isTypedArray(val)) {
assert(shape.length === 0, () => `Element arr[${indices.join('][')}] is a primitive, ` +
`but should be an array/TypedArray of ${shape[0]} elements`);
return;
}
assert(shape.length > 0, () => `Element arr[${indices.join('][')}] should be a primitive, ` +
`but is an array of ${val.length} elements`);
assert(val.length === shape[0], () => `Element arr[${indices.join('][')}] should have ${shape[0]} ` +
`elements, but has ${val.length} elements`);
const subShape = shape.slice(1);
for (let i = 0; i < val.length; ++i) {
deepAssertShapeConsistency(val[i], subShape, indices.concat(i));
}
}
function assertDtype(expectedDtype, actualDType, argName, functionName) {
if (expectedDtype === 'string_or_numeric') {
return;
}
if (expectedDtype == null) {
throw new Error(`Expected dtype cannot be null.`);
}
if (expectedDtype !== 'numeric' && expectedDtype !== actualDType ||
expectedDtype === 'numeric' && actualDType === 'string') {
throw new Error(`Argument '${argName}' passed to '${functionName}' must ` +
`be ${expectedDtype} tensor, but got ${actualDType} tensor`);
}
}
function convertToTensor(x, argName, functionName, parseAsDtype = 'numeric') {
if (x instanceof Tensor) {
assertDtype(parseAsDtype, x.dtype, argName, functionName);
return x;
}
let inferredDtype = inferDtype(x);
// If the user expects a bool/int/float, use that info to update the
// inferredDtype when it is not a string.
if (inferredDtype !== 'string' &&
['bool', 'int32', 'float32'].indexOf(parseAsDtype) >= 0) {
inferredDtype = parseAsDtype;
}
assertDtype(parseAsDtype, inferredDtype, argName, functionName);
if ((x == null) ||
(!isTypedArray(x) && !Array.isArray(x) && typeof x !== 'number' &&
typeof x !== 'boolean' && typeof x !== 'string')) {
const type = x == null ? 'null' : x.constructor.name;
throw new Error(`Argument '${argName}' passed to '${functionName}' must be a ` +
`Tensor or TensorLike, but got '${type}'`);
}
const inferredShape = inferShape(x, inferredDtype);
if (!isTypedArray(x) && !Array.isArray(x)) {
x = [x];
}
const skipTypedArray = true;
const values = inferredDtype !== 'string' ?
toTypedArray(x, inferredDtype) :
flatten(x, [], skipTypedArray);
return ENGINE.makeTensor(values, inferredShape, inferredDtype);
}
function convertToTensorArray(arg, argName, functionName, parseAsDtype = 'numeric') {
if (!Array.isArray(arg)) {
throw new Error(`Argument ${argName} passed to ${functionName} must be a ` +
'`Tensor[]` or `TensorLike[]`');
}
const tensors = arg;
return tensors.map((t, i) => convertToTensor(t, `${argName}[${i}]`, functionName, parseAsDtype));
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const OP_SCOPE_SUFFIX = '__op';
/**
* Used for wrapping functions that perform math operations on
* Tensors. The function will be wrapped in a named scope that cleans all
* memory usage after the function is done.
*/
function op(f) {
const keys = Object.keys(f);
if (keys.length !== 1) {
throw new Error(`Please provide an object with a single key ` +
`(operation name) mapping to a function. Got an object with ` +
`${keys.length} keys.`);
}
let opName = keys[0];
const fn = f[opName];
// Strip the underscore from the end of the function name.
if (opName.endsWith('_')) {
opName = opName.substring(0, opName.length - 1);
}
// add an __op suffix to distinguish ops from kernels in tf.profile
opName = opName + OP_SCOPE_SUFFIX;
// tslint:disable-next-line:no-any
const f2 = (...args) => {
ENGINE.startScope(opName);
try {
const result = fn(...args);
if (isPromise(result)) {
console.error('Cannot return a Promise inside of tidy.');
}
ENGINE.endScope(result);
return result;
}
catch (ex) {
ENGINE.endScope(null);
throw ex;
}
};
Object.defineProperty(f2, 'name', { value: opName, configurable: true });
// tslint:disable-next-line:no-any
return f2;
}
/**
* @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.
* =============================================================================
*/
/**
* Casts a `tf.Tensor` to a new dtype.
*
* ```js
* const x = tf.tensor1d([1.5, 2.5, 3]);
* tf.cast(x, 'int32').print();
* ```
* @param x The input tensor to be casted.
* @param dtype The dtype to cast the input tensor to.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function cast_(x, dtype) {
const $x = convertToTensor(x, 'x', 'cast');
// Sanity checks.
if (!isValidDtype(dtype)) {
throw new Error(`Failed to cast to unknown dtype ${dtype}`);
}
if (dtype === 'string' && $x.dtype !== 'string' ||
dtype !== 'string' && $x.dtype === 'string') {
throw new Error('Only strings can be casted to strings');
}
const inputs = { x: $x };
const attrs = { dtype };
return ENGINE.runKernel(Cast, inputs, attrs);
}
const cast = op({ cast_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Multiplies two `tf.Tensor`s element-wise, A * B. Supports broadcasting.
*
* We also expose `tf.mulStrict` which has the same signature as this op and
* asserts that `a` and `b` are the same shape (does not broadcast).
*
* ```js
* const a = tf.tensor1d([1, 2, 3, 4]);
* const b = tf.tensor1d([2, 3, 4, 5]);
*
* a.mul(b).print(); // or tf.mul(a, b)
* ```
*
* ```js
* // Broadcast mul a with b.
* const a = tf.tensor1d([1, 2, 3, 4]);
* const b = tf.scalar(5);
*
* a.mul(b).print(); // or tf.mul(a, b)
* ```
* @param a The first tensor to multiply.
* @param b The second tensor to multiply. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function mul_(a, b) {
let $a = convertToTensor(a, 'a', 'mul');
let $b = convertToTensor(b, 'b', 'mul');
[$a, $b] = makeTypesMatch($a, $b);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Multiply, inputs);
}
const mul = op({ mul_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes step of the input `tf.Tensor` element-wise: `x > 0 ? 1 : alpha * x`
*
* ```js
* const x = tf.tensor1d([0, 2, -1, -3]);
*
* x.step(.5).print(); // or tf.step(x, .5)
* ```
* @param x The input tensor.
* @param alpha The gradient when input is negative.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function step_(x, alpha = 0.0) {
const $x = convertToTensor(x, 'x', 'step');
const inputs = { x: $x };
const attrs = { alpha };
return ENGINE.runKernel(Step, inputs, attrs);
}
const step = op({ step_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const absGradConfig = {
kernelName: Abs,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(dy, step(cast(x, '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.
* =============================================================================
*/
/**
* Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.
* The result is rounded with floor function.
*
*
* ```js
* const a = tf.tensor1d([1, 4, 9, 16]);
* const b = tf.tensor1d([1, 2, 3, 4]);
*
* a.floorDiv(b).print(); // or tf.div(a, b)
* ```
*
* ```js
* // Broadcast div a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(2);
*
* a.floorDiv(b).print(); // or tf.floorDiv(a, b)
* ```
*
* @param a The first tensor as the numerator.
* @param b The second tensor as the denominator. Must have the same dtype as
* `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function floorDiv_(a, b) {
let $a = convertToTensor(a, 'a', 'floorDiv');
let $b = convertToTensor(b, 'b', 'floorDiv');
[$a, $b] = makeTypesMatch($a, $b);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(FloorDiv, inputs);
}
const floorDiv = op({ floorDiv_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 4, 9, 16]);
* const b = tf.tensor1d([1, 2, 3, 4]);
*
* a.div(b).print(); // or tf.div(a, b)
* ```
*
* ```js
* // Broadcast div a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(2);
*
* a.div(b).print(); // or tf.div(a, b)
* ```
*
* @param a The first tensor as the numerator.
* @param b The second tensor as the denominator. Must have the same dtype as
* `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function div_(a, b) {
let $a = convertToTensor(a, 'a', 'div');
let $b = convertToTensor(b, 'b', 'div');
[$a, $b] = makeTypesMatch($a, $b);
if ($a.dtype === 'int32' && $b.dtype === 'int32') {
return floorDiv($a, $b);
}
const inputs = { a: $a, b: $b };
const attrs = {};
// tslint:disable-next-line: no-unnecessary-type-assertion
return ENGINE.runKernel(RealDiv, inputs, attrs);
}
const div = op({ div_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes `-1 * x` element-wise.
*
* ```js
* const x = tf.tensor2d([1, 2, -2, 0], [2, 2]);
*
* x.neg().print(); // or tf.neg(x)
* ```
*
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function neg_(x) {
const $x = convertToTensor(x, 'x', 'neg');
const inputs = { x: $x };
return ENGINE.runKernel(Neg, inputs);
}
const neg = op({ neg_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** This is shared code across all tensor creation methods. */
function makeTensor(values, shape, inferredShape, dtype) {
if (dtype == null) {
dtype = inferDtype(values);
}
if (dtype === 'complex64') {
throw new Error(`Cannot construct a complex64 tensor directly. ` +
`Please use tf.complex(real, imag).`);
}
if (!isTypedArray(values) && !Array.isArray(values) &&
typeof values !== 'number' && typeof values !== 'boolean' &&
typeof values !== 'string') {
throw new Error('values passed to tensor(values) must be a number/boolean/string or ' +
'an array of numbers/booleans/strings, or a TypedArray');
}
if (shape != null) {
assertNonNegativeIntegerDimensions(shape);
const providedSize = sizeFromShape(shape);
const inferredSize = sizeFromShape(inferredShape);
assert(providedSize === inferredSize, () => `Based on the provided shape, [${shape}], the tensor should have ` +
`${providedSize} values but has ${inferredSize}`);
for (let i = 0; i < inferredShape.length; ++i) {
const inferred = inferredShape[i];
const flatDimsDontMatch = i === inferredShape.length - 1 ?
inferred !== sizeFromShape(shape.slice(i)) :
true;
assert(inferredShape[i] === shape[i] || !flatDimsDontMatch, () => `Error creating a new Tensor. Inferred shape ` +
`(${inferredShape}) does not match the provided ` +
`shape (${shape}). `);
}
}
if (!isTypedArray(values) && !Array.isArray(values)) {
values = [values];
}
shape = shape || inferredShape;
values = dtype !== 'string' ?
toTypedArray(values, dtype) :
flatten(values, [], true);
return ENGINE.makeTensor(values, shape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates rank-0 `tf.Tensor` (scalar) with the provided value and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.scalar` as it makes the code more readable.
*
* ```js
* tf.scalar(3.14).print();
* ```
*
* @param value The value of the scalar.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function scalar(value, dtype) {
if (((isTypedArray(value) && dtype !== 'string') || Array.isArray(value)) &&
dtype !== 'complex64') {
throw new Error('Error creating a new Scalar: value must be a primitive ' +
'(number|boolean|string)');
}
if (dtype === 'string' && isTypedArray(value) &&
!(value instanceof Uint8Array)) {
throw new Error('When making a scalar from encoded string, ' +
'the value must be `Uint8Array`.');
}
const shape = [];
const inferredShape = [];
return makeTensor(value, shape, inferredShape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes square root of the input `tf.Tensor` element-wise: `y = sqrt(x)`
*
* ```js
* const x = tf.tensor1d([1, 2, 4, -1]);
*
* x.sqrt().print(); // or tf.sqrt(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function sqrt_(x) {
const $x = convertToTensor(x, 'x', 'sqrt');
const inputs = { x: $x };
return ENGINE.runKernel(Sqrt, inputs);
}
const sqrt = op({ sqrt_ });
/**
* @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.
* =============================================================================
*/
/**
* Computes square of `x` element-wise: `x ^ 2`
*
* ```js
* const x = tf.tensor1d([1, 2, Math.sqrt(2), -1]);
*
* x.square().print(); // or tf.square(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function square_(x) {
const $x = convertToTensor(x, 'x', 'square');
const attrs = {};
return ENGINE.runKernel('Square', { x: $x }, attrs);
}
const square = op({ square_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Subtracts two `tf.Tensor`s element-wise, A - B. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([10, 20, 30, 40]);
* const b = tf.tensor1d([1, 2, 3, 4]);
*
* a.sub(b).print(); // or tf.sub(a, b)
* ```
*
* ```js
* // Broadcast subtract a with b.
* const a = tf.tensor1d([10, 20, 30, 40]);
* const b = tf.scalar(5);
*
* a.sub(b).print(); // or tf.sub(a, b)
* ```
* @param a The first `tf.Tensor` to subtract from.
* @param b The second `tf.Tensor` to be subtracted. Must have the same dtype as
* `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function sub_(a, b) {
let $a = convertToTensor(a, 'a', 'sub');
let $b = convertToTensor(b, 'b', 'sub');
[$a, $b] = makeTypesMatch($a, $b);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Sub, inputs);
}
const sub = op({ sub_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const acosGradConfig = {
kernelName: Acos,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return {
x: () => {
const a = square(cast(x, 'float32'));
const b = sqrt(sub(scalar(1), a));
return neg(div(dy, 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.
* =============================================================================
*/
const acoshGradConfig = {
kernelName: Acosh,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return {
x: () => {
const a = sqrt(sub(square(cast(x, 'float32')), 1));
return div(dy, 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.
* =============================================================================
*/
/**
* Returns the dimensions in the input shape that are broadcasted to
* produce the provided output shape.
*
* The returned dimensions are 0-indexed and sorted. An example:
* inShape = [4, 1, 3]
* outShape = [5, 4, 3, 3]
* result = [1]. Dimension 1 (2nd dimension of input) gets broadcasted 1 => 3.
*/
function getBroadcastDims(inShape, outShape) {
const inRank = inShape.length;
const dims = [];
for (let i = 0; i < inRank; i++) {
const dim = inRank - 1 - i;
const a = inShape[dim] || 1;
const b = outShape[outShape.length - 1 - i] || 1;
if (b > 1 && a === 1) {
dims.unshift(dim);
}
}
return dims;
}
/**
* Returns the axes in the output space that should be reduced to produce
* the input space.
*/
function getReductionAxes(inShape, outShape) {
const result = [];
for (let i = 0; i < outShape.length; i++) {
const inDim = inShape[inShape.length - i - 1];
const outAxis = outShape.length - i - 1;
const outDim = outShape[outAxis];
if (inDim == null || (inDim === 1 && outDim > 1)) {
result.unshift(outAxis);
}
}
return result;
}
function assertAndGetBroadcastShape(shapeA, shapeB) {
const result = [];
const l = Math.max(shapeA.length, shapeB.length);
for (let i = 0; i < l; i++) {
let a = shapeA[shapeA.length - i - 1];
if (a == null) {
a = 1;
}
let b = shapeB[shapeB.length - i - 1];
if (b == null) {
b = 1;
}
if (a === 1) {
result.unshift(b);
}
else if (b === 1) {
result.unshift(a);
}
else if (a !== b) {
const errMsg = `Operands could not be broadcast together with shapes ` +
`${shapeA} and ${shapeB}.`;
throw Error(errMsg);
}
else {
result.unshift(a);
}
}
return result;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Reshapes a `tf.Tensor` to a given shape.
*
* Given an input tensor, returns a new tensor with the same values as the
* input tensor with shape `shape`.
*
* If one component of shape is the special value -1, the size of that
* dimension is computed so that the total size remains constant. In
* particular, a shape of [-1] flattens into 1-D. At most one component of
* shape can be -1.
*
* If shape is 1-D or higher, then the operation returns a tensor with shape
* shape filled with the values of tensor. In this case, the number of
* elements implied by shape must be the same as the number of elements in
* tensor.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* x.reshape([2, 2]).print();
* ```
*
* @param x The input tensor to be reshaped.
* @param shape An array of integers defining the output tensor shape.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function reshape_(x, shape) {
const $x = convertToTensor(x, 'x', 'reshape', 'string_or_numeric');
const inputs = { x: $x };
const attrs = { shape };
return ENGINE.runKernel(Reshape, inputs, attrs);
}
const reshape = op({ reshape_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the sum of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If axes has no entries, all dimensions are reduced, and a
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.sum().print(); // or tf.sum(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.sum(axis).print(); // or tf.sum(x, axis)
* ```
*
* @param x The input tensor to compute the sum over. If the dtype is `bool`
* it will be converted to `int32` and the output dtype will be `int32`.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function sum_(x, axis = null, keepDims = false) {
let $x = convertToTensor(x, 'x', 'sum');
if ($x.dtype === 'bool') {
$x = cast($x, 'int32');
}
const inputs = { x: $x };
const attrs = { axis, keepDims };
return ENGINE.runKernel(Sum, inputs, attrs);
}
const sum$1 = op({ sum_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const addGradConfig = {
kernelName: Add,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
let res = dy;
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, a.shape);
};
const derB = () => {
let res = dy;
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, b.shape);
};
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const addNGradConfig = {
kernelName: AddN,
saveAllInputs: true,
gradFunc: (dy, saved) => {
const ders = {};
saved.forEach((_, i) => {
ders[i] = () => dy.clone();
});
return ders;
}
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with all elements set to 0 with the same shape as the
* given tensor.
*
* ```js
* const x = tf.tensor([1, 2]);
* tf.zerosLike(x).print();
* ```
*
* @param x The tensor of required shape.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function zerosLike_(x) {
const $x = convertToTensor(x, 'x', 'zerosLike');
const inputs = { x: $x };
return ENGINE.runKernel(ZerosLike, inputs);
}
const zerosLike = op({ zerosLike_ });
/**
* @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 argMaxGradConfig = {
kernelName: ArgMax,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => zerosLike(x) };
}
};
/**
* @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 argMinGradConfig = {
kernelName: ArgMin,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => zerosLike(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 asinGradConfig = {
kernelName: Asin,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => div(dy, sqrt(sub(scalar(1), square(cast(x, '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.
* =============================================================================
*/
/**
* Adds two `tf.Tensor`s element-wise, A + B. Supports broadcasting.
*
*
* ```js
* const a = tf.tensor1d([1, 2, 3, 4]);
* const b = tf.tensor1d([10, 20, 30, 40]);
*
* a.add(b).print(); // or tf.add(a, b)
* ```
*
* ```js
* // Broadcast add a with b.
* const a = tf.scalar(5);
* const b = tf.tensor1d([10, 20, 30, 40]);
*
* a.add(b).print(); // or tf.add(a, b)
* ```
* @param a The first `tf.Tensor` to add.
* @param b The second `tf.Tensor` to add. Must have the same type as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function add_(a, b) {
let $a = convertToTensor(a, 'a', 'add');
let $b = convertToTensor(b, 'b', 'add');
[$a, $b] = makeTypesMatch($a, $b);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Add, inputs);
}
const add$1 = op({ add_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const asinhGradConfig = {
kernelName: Asinh,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return {
x: () => {
const a = sqrt(add$1(scalar(1), square(cast(x, 'float32'))));
return div(dy, 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 atan2GradConfig = {
kernelName: Atan2,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
const d = add$1(square(a), square(b));
let res = mul(dy, div(b, d));
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, a.shape);
};
const derB = () => {
const d = add$1(square(a), square(b));
let res = neg(mul(dy, div(a, d)));
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, b.shape);
};
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const atanGradConfig = {
kernelName: Atan,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => div(dy, add$1(square(cast(x, '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 atanhGradConfig = {
kernelName: Atanh,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => div(dy, sub(scalar(1), square(cast(x, '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.
* =============================================================================
*/
/**
* Computes the backprop of a 3d avg pool.
*
* @param dy The dy error, of rank 5 of shape
* [batchSize, depth, height, width, channels].
* assumed.
* @param input The original input image, of rank 5 or rank4 of shape
* [batchSize, depth, height, width, channels].
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function avgPool3dGrad_(dy, input, filterSize, strides, pad, dimRoundingMode) {
const $dy = convertToTensor(dy, 'dy', 'avgPool3dGrad');
const $input = convertToTensor(input, 'input', 'avgPool3dGrad');
let dy5D = $dy;
let input5D = $input;
let reshapedTo5D = false;
if ($input.rank === 4) {
reshapedTo5D = true;
dy5D = reshape($dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2], $dy.shape[3]]);
input5D = reshape($input, [
1, $input.shape[0], $input.shape[1], $input.shape[2], $input.shape[3]
]);
}
assert(dy5D.rank === 5, () => `Error in avgPool3dGrad: dy must be rank 5 but got rank ` +
`${dy5D.rank}.`);
assert(input5D.rank === 5, () => `Error in avgPool3dGrad: input must be rank 5 but got rank ` +
`${input5D.rank}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in avgPool3dGrad: pad must be an integer when ` +
`using, dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { dy: dy5D, input: input5D };
const attrs = { filterSize, strides, pad, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(AvgPool3DGrad, inputs, attrs);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const avgPool3dGrad = op({ avgPool3dGrad_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const avgPool3DGradConfig = {
kernelName: AvgPool3D,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { filterSize, strides, pad, dimRoundingMode } = attrs;
return {
x: () => avgPool3dGrad(dy, x, filterSize, strides, pad, dimRoundingMode)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the backprop of an 2D avg pool.
*
* @param dy The dy error, of rank 4 or rank 3 of shape
* [batchSize, height, width, channels]. If rank 3, batch of 1 is
* assumed.
* @param input The input image, of rank 4 or rank 3 of shape
* [batchSize, height, width, channels]. If rank 3, batch of 1 is
* assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
*/
function avgPoolGrad_(dy, input, filterSize, strides, pad) {
const $dy = convertToTensor(dy, 'dy', 'avgPoolGrad');
const $input = convertToTensor(input, 'input', 'avgPoolGrad');
assert($input.rank === $dy.rank, () => `Rank of input (${$input.rank}) does not match rank of dy (${$dy.rank})`);
let input4D = $input;
let dy4D = $dy;
let reshapedTo4D = false;
if ($input.rank === 3) {
reshapedTo4D = true;
input4D =
reshape($input, [1, $input.shape[0], $input.shape[1], $input.shape[2]]);
dy4D = reshape($dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2]]);
}
assert(dy4D.rank === 4, () => `Error in avgPoolGrad: dy must be rank 4 but got rank ` +
`${dy4D.rank}.`);
assert(input4D.rank === 4, () => `Error in avgPoolGrad: input must be rank 4 but got rank ` +
`${input4D.rank}.`);
const inputs = { dy: dy4D, input: input4D };
const attrs = { filterSize, strides, pad };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(AvgPoolGrad, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const avgPoolGrad = op({ avgPoolGrad_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const avgPoolGradConfig = {
kernelName: AvgPool,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { filterSize, strides, pad } = attrs;
return { x: () => avgPoolGrad(dy, x, filterSize, strides, pad) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the dot product of two matrices, A * B. These must be matrices.
*
* ```js
* const a = tf.tensor2d([1, 2], [1, 2]);
* const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* a.matMul(b).print(); // or tf.matMul(a, b)
* ```
* @param a First matrix in dot product operation.
* @param b Second matrix in dot product operation.
* @param transposeA If true, `a` is transposed before multiplication.
* @param transposeB If true, `b` is transposed before multiplication.
*
* @doc {heading: 'Operations', subheading: 'Matrices'}
*/
function matMul_(a, b, transposeA = false, transposeB = false) {
let $a = convertToTensor(a, 'a', 'matMul');
let $b = convertToTensor(b, 'b', 'matMul');
[$a, $b] = makeTypesMatch($a, $b);
const inputs = { a: $a, b: $b };
const attrs = { transposeA, transposeB };
return ENGINE.runKernel(BatchMatMul, inputs, attrs);
}
const matMul = op({ matMul_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const batchMatMulGradConfig = {
kernelName: BatchMatMul,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved, attrs) => {
const [a, b] = saved;
const { transposeA, transposeB } = attrs;
if (!transposeA && !transposeB) {
return {
a: () => matMul(dy, b, false, true),
b: () => matMul(a, dy, true, false)
};
}
else if (!transposeA && transposeB) {
return {
a: () => matMul(dy, b, false, false),
b: () => matMul(dy, a, true, false)
};
}
else if (transposeA && !transposeB) {
return {
a: () => matMul(b, dy, false, true),
b: () => matMul(a, dy, false, false)
};
}
else {
return {
a: () => matMul(b, dy, true, true),
b: () => matMul(dy, a, true, true)
};
}
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* This operation divides "spatial" dimensions `[1, ..., M]` of the input into
* a grid of blocks of shape `blockShape`, and interleaves these blocks with
* the "batch" dimension (0) such that in the output, the spatial
* dimensions `[1, ..., M]` correspond to the position within the grid,
* and the batch dimension combines both the position within a spatial block
* and the original batch position. Prior to division into blocks,
* the spatial dimensions of the input are optionally zero padded
* according to `paddings`. See below for a precise description.
*
* ```js
* const x = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
* const blockShape = [2, 2];
* const paddings = [[0, 0], [0, 0]];
*
* x.spaceToBatchND(blockShape, paddings).print();
* ```
*
* @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +
* remainingShape`, where spatialShape has `M` dimensions.
* @param blockShape A 1-D array. Must have shape `[M]`, all values must
* be >= 1.
* @param paddings A 2-D array. Must have shape `[M, 2]`, all values must be >=
* 0. `paddings[i] = [padStart, padEnd]` specifies the amount to zero-pad
* from input dimension `i + 1`, which corresponds to spatial dimension `i`. It
* is required that
* `(inputShape[i + 1] + padStart + padEnd) % blockShape[i] === 0`
*
* This operation is equivalent to the following steps:
*
* 1. Zero-pad the start and end of dimensions `[1, ..., M]` of the input
* according to `paddings` to produce `padded` of shape paddedShape.
*
* 2. Reshape `padded` to `reshapedPadded` of shape:
* `[batch] + [paddedShape[1] / blockShape[0], blockShape[0], ...,
* paddedShape[M] / blockShape[M-1], blockShape[M-1]] + remainingShape`
*
* 3. Permute dimensions of `reshapedPadded` to produce `permutedReshapedPadded`
* of shape: `blockShape + [batch] + [paddedShape[1] / blockShape[0], ...,
* paddedShape[M] / blockShape[M-1]] + remainingShape`
*
* 4. Reshape `permutedReshapedPadded` to flatten `blockShape` into the
* batch dimension, producing an output tensor of shape:
* `[batch * prod(blockShape)] + [paddedShape[1] / blockShape[0], ...,
* paddedShape[M] / blockShape[M-1]] + remainingShape`
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function spaceToBatchND_(x, blockShape, paddings) {
const $x = convertToTensor(x, 'x', 'spaceToBatchND');
assert($x.rank >= 1 + blockShape.length, () => `input rank ${$x.rank} should be > than [blockShape] ${blockShape.length}`);
assert(paddings.length === blockShape.length, () => `paddings.shape[0] ${paddings.length} must be equal to [blockShape] ${blockShape.length}`);
assert($x.shape.reduce((a, b, i) => {
if (i > 0 && i <= blockShape.length) {
return a &&
((b + paddings[i - 1][0] + paddings[i - 1][1]) %
blockShape[i - 1] ===
0);
}
return a;
}, true), () => `input spatial dimensions ${$x.shape.slice(1)} with paddings ${paddings.toString()} must be divisible by blockShapes ${blockShape.toString()}`);
const inputs = { x: $x };
const attrs = { blockShape, paddings };
return ENGINE.runKernel(SpaceToBatchND, inputs, attrs);
}
const spaceToBatchND = op({ spaceToBatchND_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const batchToSpaceNDGradConfig = {
kernelName: BatchToSpaceND,
gradFunc: (dy, saved, attrs) => {
const { blockShape, crops } = attrs;
return { x: () => spaceToBatchND(dy, blockShape, crops) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const broadcastToGradConfig = {
kernelName: BroadcastTo,
gradFunc: (dy, saved, attrs) => {
const broadCastToAttrs = attrs;
const inputShape = broadCastToAttrs.inputShape;
const outputShape = broadCastToAttrs.shape;
const reps = Array.from(outputShape);
for (let i = inputShape.length - 1; i >= 0; i--) {
if (inputShape[i] === outputShape[i]) {
reps[i] = 1;
}
else if (inputShape[i] !== 1) {
throw new Error(`broadcastTo(): [${inputShape}] cannot be broadcast to [${outputShape}].`);
}
}
const axes = [];
for (let i = 0; i < reps.length; i++) {
if (reps[i] > 1) {
axes.push(i);
}
}
return { x: () => sum$1(dy, axes, true /* 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 castGradConfig = {
kernelName: Cast,
gradFunc: (dy) => {
return { x: () => dy.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 ceilGradConfig = {
kernelName: Ceil,
gradFunc: (dy) => {
// TODO(manrajgrover): Return null for gradients when backprop supports it.
return { x: () => zerosLike(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.
* =============================================================================
*/
/**
* Returns the truth value of (a >= b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.greaterEqual(b).print();
* ```
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function greaterEqual_(a, b) {
let $a = convertToTensor(a, 'a', 'greaterEqual');
let $b = convertToTensor(b, 'b', 'greaterEqual');
[$a, $b] = makeTypesMatch($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(GreaterEqual, inputs);
}
const greaterEqual = op({ greaterEqual_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of (a <= b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.lessEqual(b).print();
* ```
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function lessEqual_(a, b) {
let $a = convertToTensor(a, 'a', 'lessEqual');
let $b = convertToTensor(b, 'b', 'lessEqual');
[$a, $b] = makeTypesMatch($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(LessEqual, inputs);
}
const lessEqual = op({ lessEqual_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of `a AND b` element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([false, false, true, true], 'bool');
* const b = tf.tensor1d([false, true, false, true], 'bool');
*
* a.logicalAnd(b).print();
* ```
*
* @param a The first input tensor. Must be of dtype bool.
* @param b The second input tensor. Must be of dtype bool.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function logicalAnd_(a, b) {
const $a = convertToTensor(a, 'a', 'logicalAnd', 'bool');
const $b = convertToTensor(b, 'b', 'logicalAnd', 'bool');
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(LogicalAnd, inputs);
}
const logicalAnd = op({ logicalAnd_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a new tensor with the same values and shape as the specified
* tensor.
*
* ```js
* const x = tf.tensor([1, 2]);
*
* x.clone().print();
* ```
*
* @param x The tensor to clone.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function clone_(x) {
const $x = convertToTensor(x, 'x', 'clone', 'string_or_numeric');
const inputs = { x: $x };
// Note this op is called tf.identity in python. Hence the kernel name used
// here.
return ENGINE.runKernel(Identity, inputs);
}
const clone = op({ 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.
* =============================================================================
*/
/**
* Broadcast an array to a compatible shape NumPy-style.
*
* The tensor's shape is compared to the broadcast shape from end to beginning.
* Ones are prepended to the tensor's shape until is has the same length as
* the broadcast shape. If input.shape[i]==shape[i], the (i+1)-th axis is
* already broadcast-compatible. If input.shape[i]==1 and shape[i]==N, then
* the input tensor is tiled N times along that axis (using tf.tile).
*
* @param input The tensor that is to be broadcasted.
* @param shape The input is to be broadcast to this shape.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function broadcastTo_(x, shape) {
let input = convertToTensor(x, 'broadcastTo', 'x');
const xShape = input.shape;
if (shape.some(d => !(d > 0) || d % 1 !== 0)) {
throw new Error(`broadcastTo(): Invalid broadcast shape [${shape}].`);
}
if (shape.length < input.rank) {
throw new Error(`broadcastTo(): shape.length=${shape.length} < input.rank=${input.rank}.`);
}
if (shape.length > input.rank) {
const newShape = input.shape.slice();
while (newShape.length < shape.length) {
newShape.unshift(1);
}
input = reshape(input, newShape);
}
const inputShape = input.shape;
const reps = Array.from(shape);
for (let i = shape.length - 1; i >= 0; i--) {
if (inputShape[i] === shape[i]) {
reps[i] = 1;
}
else if (input.shape[i] !== 1) {
throw new Error(`broadcastTo(): [${xShape}] cannot be broadcast to [${shape}].`);
}
}
const axes = reps.map((n, i) => n > 1 ? i : -1).filter(i => i >= 0);
if (axes.length === 0) {
return clone(input);
}
// TODO call broadcastTo kernel directly once backends implement broadcstTo
const inputs = { x: input };
const attrs = { reps };
return ENGINE.runKernel(Tile, inputs, attrs);
}
const broadcastTo = op({ broadcastTo_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the elements, either `a` or `b` depending on the `condition`.
*
* If the condition is true, select from `a`, otherwise select from `b`.
*
* ```js
* const cond = tf.tensor1d([false, false, true], 'bool');
* const a = tf.tensor1d([1 , 2, 3]);
* const b = tf.tensor1d([-1, -2, -3]);
*
* a.where(cond, b).print();
* ```
*
* @param condition The input condition. Must be of dtype bool.
* @param a If `condition` is rank 1, `a` may have a higher rank but
* its first dimension must match the size of `condition`.
* @param b A tensor with the same dtype as `a` and with shape that is
* compatible with `a`.
* @return A tensor with same dtype as `a` and `b`, and shape that is
* broadcastable from `a` and `b`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function where_(condition, a, b) {
const $a = convertToTensor(a, 'a', 'where');
const $b = convertToTensor(b, 'b', 'where');
const $condition = convertToTensor(condition, 'condition', 'where', 'bool');
// TODO: move this logic to forward function when the broadcastTo op is
// implemented in WASM.
// Find the broadcastable shape for $condition, $a, and $b.
const broadcastShape = assertAndGetBroadcastShape(assertAndGetBroadcastShape($condition.shape, $a.shape), $b.shape);
const $broadcastedCondition = broadcastTo($condition, broadcastShape);
const $broadcastedA = broadcastTo($a, broadcastShape);
const $broadcastedB = broadcastTo($b, broadcastShape);
const inputs = {
condition: $broadcastedCondition,
t: $broadcastedA,
e: $broadcastedB
};
return ENGINE.runKernel(Select, inputs);
}
const where = op({ where_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const clipByValueGradConfig = {
kernelName: ClipByValue,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { clipValueMin, clipValueMax } = attrs;
return {
x: () => where(logicalAnd(greaterEqual(x, clipValueMin), lessEqual(x, clipValueMax)), dy, zerosLike(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.
* =============================================================================
*/
const complexAbsGradConfig = {
kernelName: ComplexAbs,
inputsToSave: ['x'],
gradFunc: absGradConfig.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.
* =============================================================================
*/
/**
* Splits a `tf.Tensor` into sub tensors.
*
* If `numOrSizeSplits` is a number, splits `x` along dimension `axis`
* into `numOrSizeSplits` smaller tensors.
* Requires that `numOrSizeSplits` evenly divides `x.shape[axis]`.
*
* If `numOrSizeSplits` is a number array, splits `x` into
* `numOrSizeSplits.length` pieces. The shape of the `i`-th piece has the
* same size as `x` except along dimension `axis` where the size is
* `numOrSizeSplits[i]`.
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8], [2, 4]);
* const [a, b] = tf.split(x, 2, 1);
* a.print();
* b.print();
*
* const [c, d, e] = tf.split(x, [1, 2, 1], 1);
* c.print();
* d.print();
* e.print();
* ```
*
* @param x The input tensor to split.
* @param numOrSizeSplits Either an integer indicating the number of
* splits along the axis or an array of integers containing the sizes of
* each output tensor along the axis. If a number then it must evenly divide
* `x.shape[axis]`; otherwise the sum of sizes must match `x.shape[axis]`.
* Can contain one -1 indicating that dimension is to be inferred.
* @param axis The dimension along which to split. Defaults to 0 (the first
* dim).
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function split_(x, numOrSizeSplits, axis = 0) {
const $x = convertToTensor(x, 'x', 'split');
const inputs = { x: $x };
const attr = { numOrSizeSplits, axis };
return ENGINE.runKernel(SplitV, inputs, attr);
}
const split = op({ split_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const concatGradConfig = {
kernelName: Concat,
saveAllInputs: true,
gradFunc: (dy, saved, attrs) => {
const shapes = saved.map(t => t.shape);
const { axis } = attrs;
const $axis = parseAxisParam(axis, saved[0].shape)[0];
const sizeSplits = shapes.map(s => s[$axis]);
const derTensors = split(dy, sizeSplits, $axis);
return derTensors.map(t => () => 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.
* =============================================================================
*/
/**
* Computes the derivative of the filter of a 2D convolution.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* [batch, height, width, inChannels]. If rank 3, batch of 1 is assumed.
* @param dy The dy image, of rank 4 or rank 3, of shape
* [batch, height, width, outDepth]. If rank 3, batch of 1 is assumed.
* @param filterShape The shape of the filter, length 4,
* [filterHeight, filterWidth, inDepth, outDepth].
* @param strides The strides of the convolution: [strideHeight,
* strideWidth].
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function conv2DBackpropFilter_(x, dy, filterShape, strides, pad, dataFormat = 'NHWC', dimRoundingMode) {
let x4D = x;
if (x.rank === 3) {
x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
}
let dy4D = dy;
if (dy4D.rank === 3) {
dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
}
assert(x4D.rank === 4, () => `Error in conv2dDerFilter: input must be rank 4, but got shape ` +
`${x4D.shape}.`);
assert(dy4D.rank === 4, () => `Error in conv2dDerFilter: dy must be rank 4, but got shape ` +
`${dy4D.shape}.`);
assert(filterShape.length === 4, () => `Error in conv2dDerFilter: filterShape must be length 4, but got ` +
`${filterShape}.`);
const inDepth = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];
const outDepth = dataFormat === 'NHWC' ? dy4D.shape[3] : dy4D.shape[1];
assert(inDepth === filterShape[2], () => `Error in conv2dDerFilter: depth of input ${inDepth}) must ` +
`match input depth in filter (${filterShape[2]}.`);
assert(outDepth === filterShape[3], () => `Error in conv2dDerFilter: depth of dy (${outDepth}) must ` +
`match output depth for filter (${filterShape[3]}).`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in conv2dDerFilter: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x4D, dy: dy4D };
const attrs = { strides, pad, dataFormat, dimRoundingMode, filterShape };
// tslint:disable-next-line: no-unnecessary-type-assertion
return ENGINE.runKernel(Conv2DBackpropFilter, inputs, attrs);
}
const conv2DBackpropFilter = op({ conv2DBackpropFilter_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the derivative of the input of a 2D convolution.
*
* @param xShape The shape of the input: [batch, height, width, inDepth].
* If length of 3, batch of 1 is assumed.
* @param dy The derivative of the output, of rank 4 or rank 3 of shape
* `[batch, outHeight, outWidth, outDepth]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, inDepth, outDepth]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm used:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function conv2DBackpropInput_(xShape, dy, filter, strides, pad, dataFormat = 'NHWC', dimRoundingMode) {
assert(xShape.length === dy.rank, () => `Length of inShape ` +
`(${xShape.length}) and rank of dy (${dy.rank}) must match`);
let xShape4D = xShape;
let dy4D = dy;
let reshapedTo4D = false;
if (dy.rank === 3) {
reshapedTo4D = true;
dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
xShape4D = [1, xShape[0], xShape[1], xShape[2]];
}
assert(xShape4D.length === 4, () => `Error in conv2dDerInput: inShape must be length 4, but got length ` +
`${xShape4D.length}.`);
assert(dy4D.rank === 4, () => `Error in conv2dDerInput: dy must be rank 4, but got ` +
`rank ${dy4D.rank}`);
assert(filter.rank === 4, () => `Error in conv2dDerInput: filter must be rank 4, but got ` +
`rank ${filter.rank}`);
const inDepth = dataFormat === 'NHWC' ? xShape4D[3] : xShape4D[1];
const outDepth = dataFormat === 'NHWC' ? dy4D.shape[3] : dy4D.shape[1];
assert(inDepth === filter.shape[2], () => `Error in conv2dDerInput: depth of input (${inDepth}) must ` +
`match input depth for filter ${filter.shape[2]}.`);
assert(outDepth === filter.shape[3], () => `Error in conv2dDerInput: depth of output (${outDepth}) must ` +
`match output depth for filter ${filter.shape[3]}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in conv2dDerInput: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { dy: dy4D, filter };
const attrs = { strides, pad, dataFormat, dimRoundingMode, inputShape: xShape4D };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(Conv2DBackpropInput, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const conv2DBackpropInput = op({ conv2DBackpropInput_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
*
* @param inputShape Input tensor shape is of the following dimensions:
* `[batch, height, width, inChannels]`.
* @param filterShape The filter shape is of the following dimensions:
* `[filterHeight, filterWidth, depth]`.
* @param strides The strides of the sliding window for each dimension of the
* input tensor: `[strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dataFormat The data format of the input and output data.
* Defaults to 'NHWC'.
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`.
* Defaults to `[1, 1]`. If `dilations` is a single number, then
* `dilationHeight == dilationWidth`.
*/
function computeDilation2DInfo(inputShape, filterShape, strides, pad, dataFormat = 'NHWC', dilations) {
// `computerConv2DInfo` require filterShape to be in the dimension of:
// `[filterHeight, filterWidth, depth, outDepth]`, dilation2d doesn't have
// outDepth, it should have the same depth as the input.
// Input shape: [batch, height, width, inChannels]
const inputChannels = inputShape[3];
const $filterShape = [...filterShape, inputChannels];
const $dataFormat = convertConv2DDataFormat(dataFormat);
return computeConv2DInfo(inputShape, $filterShape, strides, dilations, pad, null /* roundingMode */, null /* depthWise */, $dataFormat);
}
function computePool2DInfo(inShape, filterSize, strides, dilations, pad, roundingMode, dataFormat = 'channelsLast') {
const [filterHeight, filterWidth] = parseTupleParam(filterSize);
let filterShape;
if (dataFormat === 'channelsLast') {
filterShape = [filterHeight, filterWidth, inShape[3], inShape[3]];
}
else if (dataFormat === 'channelsFirst') {
filterShape = [filterHeight, filterWidth, inShape[1], inShape[1]];
}
else {
throw new Error(`Unknown dataFormat ${dataFormat}`);
}
return computeConv2DInfo(inShape, filterShape, strides, dilations, pad, roundingMode, false, dataFormat);
}
/**
* Computes the information for a forward pass of a pooling3D operation.
*/
function computePool3DInfo(inShape, filterSize, strides, dilations, pad, roundingMode, dataFormat = 'NDHWC') {
const [filterDepth, filterHeight, filterWidth] = parse3TupleParam(filterSize);
let filterShape;
let $dataFormat;
if (dataFormat === 'NDHWC') {
$dataFormat = 'channelsLast';
filterShape =
[filterDepth, filterHeight, filterWidth, inShape[4], inShape[4]];
}
else if (dataFormat === 'NCDHW') {
$dataFormat = 'channelsFirst';
filterShape =
[filterDepth, filterHeight, filterWidth, inShape[1], inShape[1]];
}
else {
throw new Error(`Unknown dataFormat ${dataFormat}`);
}
return computeConv3DInfo(inShape, filterShape, strides, dilations, pad, false, $dataFormat, roundingMode);
}
/**
* Computes the information for a forward pass of a convolution/pooling
* operation.
*/
function computeConv2DInfo(inShape, filterShape, strides, dilations, pad, roundingMode, depthwise = false, dataFormat = 'channelsLast') {
let [batchSize, inHeight, inWidth, inChannels] = [-1, -1, -1, -1];
if (dataFormat === 'channelsLast') {
[batchSize, inHeight, inWidth, inChannels] = inShape;
}
else if (dataFormat === 'channelsFirst') {
[batchSize, inChannels, inHeight, inWidth] = inShape;
}
else {
throw new Error(`Unknown dataFormat ${dataFormat}`);
}
const [filterHeight, filterWidth, , filterChannels] = filterShape;
const [strideHeight, strideWidth] = parseTupleParam(strides);
const [dilationHeight, dilationWidth] = parseTupleParam(dilations);
const effectiveFilterHeight = getEffectiveFilterSize(filterHeight, dilationHeight);
const effectiveFilterWidth = getEffectiveFilterSize(filterWidth, dilationWidth);
const { padInfo, outHeight, outWidth } = getPadAndOutInfo(pad, inHeight, inWidth, strideHeight, strideWidth, effectiveFilterHeight, effectiveFilterWidth, roundingMode, dataFormat);
const outChannels = depthwise ? filterChannels * inChannels : filterChannels;
let outShape;
if (dataFormat === 'channelsFirst') {
outShape = [batchSize, outChannels, outHeight, outWidth];
}
else if (dataFormat === 'channelsLast') {
outShape = [batchSize, outHeight, outWidth, outChannels];
}
return {
batchSize,
dataFormat,
inHeight,
inWidth,
inChannels,
outHeight,
outWidth,
outChannels,
padInfo,
strideHeight,
strideWidth,
filterHeight,
filterWidth,
effectiveFilterHeight,
effectiveFilterWidth,
dilationHeight,
dilationWidth,
inShape,
outShape,
filterShape
};
}
/**
* Computes the information for a forward pass of a 3D convolution/pooling
* operation.
*/
function computeConv3DInfo(inShape, filterShape, strides, dilations, pad, depthwise = false, dataFormat = 'channelsLast', roundingMode) {
let [batchSize, inDepth, inHeight, inWidth, inChannels] = [-1, -1, -1, -1, -1];
if (dataFormat === 'channelsLast') {
[batchSize, inDepth, inHeight, inWidth, inChannels] = inShape;
}
else if (dataFormat === 'channelsFirst') {
[batchSize, inChannels, inDepth, inHeight, inWidth] = inShape;
}
else {
throw new Error(`Unknown dataFormat ${dataFormat}`);
}
const [filterDepth, filterHeight, filterWidth, , filterChannels] = filterShape;
const [strideDepth, strideHeight, strideWidth] = parse3TupleParam(strides);
const [dilationDepth, dilationHeight, dilationWidth] = parse3TupleParam(dilations);
const effectiveFilterDepth = getEffectiveFilterSize(filterDepth, dilationDepth);
const effectiveFilterHeight = getEffectiveFilterSize(filterHeight, dilationHeight);
const effectiveFilterWidth = getEffectiveFilterSize(filterWidth, dilationWidth);
const { padInfo, outDepth, outHeight, outWidth } = get3DPadAndOutInfo(pad, inDepth, inHeight, inWidth, strideDepth, strideHeight, strideWidth, effectiveFilterDepth, effectiveFilterHeight, effectiveFilterWidth, roundingMode);
const outChannels = depthwise ? filterChannels * inChannels : filterChannels;
let outShape;
if (dataFormat === 'channelsFirst') {
outShape = [batchSize, outChannels, outDepth, outHeight, outWidth];
}
else if (dataFormat === 'channelsLast') {
outShape = [batchSize, outDepth, outHeight, outWidth, outChannels];
}
return {
batchSize,
dataFormat,
inDepth,
inHeight,
inWidth,
inChannels,
outDepth,
outHeight,
outWidth,
outChannels,
padInfo,
strideDepth,
strideHeight,
strideWidth,
filterDepth,
filterHeight,
filterWidth,
effectiveFilterDepth,
effectiveFilterHeight,
effectiveFilterWidth,
dilationDepth,
dilationHeight,
dilationWidth,
inShape,
outShape,
filterShape
};
}
function computeOutputShape2D(inShape, fieldSize, stride, zeroPad, roundingMode) {
if (zeroPad == null) {
zeroPad = computeDefaultPad(inShape, fieldSize, stride);
}
const inputRows = inShape[0];
const inputCols = inShape[1];
const outputRows = round((inputRows - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
const outputCols = round((inputCols - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
return [outputRows, outputCols];
}
function computeOutputShape4D(inShape, fieldSize, outChannels, stride, zeroPad, roundingMode) {
if (zeroPad == null) {
zeroPad = computeDefaultPad(inShape, fieldSize, stride);
}
const inputDepth = inShape[0];
const inputRows = inShape[1];
const inputCols = inShape[2];
const outputDepths = round((inputDepth - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
const outputRows = round((inputRows - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
const outputCols = round((inputCols - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
return [outputDepths, outputRows, outputCols, outChannels];
}
function computeDefaultPad(inputShape, fieldSize, stride, dilation = 1) {
const effectiveFieldSize = getEffectiveFilterSize(fieldSize, dilation);
return Math.floor((inputShape[0] * (stride - 1) - stride + effectiveFieldSize) / 2);
}
function parseTupleParam(param) {
if (typeof param === 'number') {
return [param, param, param];
}
if (param.length === 2) {
return [param[0], param[1], 1];
}
return param;
}
function parse3TupleParam(param) {
return typeof param === 'number' ? [param, param, param] : param;
}
/* See https://www.tensorflow.org/api_docs/python/tf/nn/atrous_conv2d
* Atrous convolution is equivalent to standard convolution with upsampled
* filters with effective_filter_height =
* filter_height + (filter_height - 1) * (dilation - 1)
* and effective_filter_width =
* filter_width + (filter_width - 1) * (dilation - 1),
* produced by inserting dilation - 1 zeros along consecutive elements across
* the filters' spatial dimensions.
* When there is a dilation, this converts a filter dimension to the
* effective filter dimension, so it can be used in a standard convolution.
*/
function getEffectiveFilterSize(filterSize, dilation) {
if (dilation <= 1) {
return filterSize;
}
return filterSize + (filterSize - 1) * (dilation - 1);
}
function getPadAndOutInfo(pad, inHeight, inWidth, strideHeight, strideWidth, filterHeight, filterWidth, roundingMode, dataFormat) {
let padInfo;
let outHeight;
let outWidth;
if (typeof pad === 'number') {
const padType = (pad === 0) ? 'VALID' : 'NUMBER';
padInfo = { top: pad, bottom: pad, left: pad, right: pad, type: padType };
const outShape = computeOutputShape2D([inHeight, inWidth], filterHeight, strideHeight, pad, roundingMode);
outHeight = outShape[0];
outWidth = outShape[1];
}
else if (pad === 'same') {
outHeight = Math.ceil(inHeight / strideHeight);
outWidth = Math.ceil(inWidth / strideWidth);
const padAlongHeight = Math.max(0, (outHeight - 1) * strideHeight + filterHeight - inHeight);
const padAlongWidth = Math.max(0, (outWidth - 1) * strideWidth + filterWidth - inWidth);
const top = Math.floor(padAlongHeight / 2);
const bottom = padAlongHeight - top;
const left = Math.floor(padAlongWidth / 2);
const right = padAlongWidth - left;
padInfo = { top, bottom, left, right, type: 'SAME' };
}
else if (pad === 'valid') {
padInfo = { top: 0, bottom: 0, left: 0, right: 0, type: 'VALID' };
outHeight = Math.ceil((inHeight - filterHeight + 1) / strideHeight);
outWidth = Math.ceil((inWidth - filterWidth + 1) / strideWidth);
}
else if (typeof pad === 'object') {
const top = dataFormat === 'channelsLast' ? pad[1][0] : pad[2][0];
const bottom = dataFormat === 'channelsLast' ? pad[1][1] : pad[2][1];
const left = dataFormat === 'channelsLast' ? pad[2][0] : pad[3][0];
const right = dataFormat === 'channelsLast' ? pad[2][1] : pad[3][1];
const padType = (top === 0 && bottom === 0 && left === 0 && right === 0) ?
'VALID' :
'EXPLICIT';
padInfo = { top, bottom, left, right, type: padType };
outHeight = round((inHeight - filterHeight + top + bottom) / strideHeight + 1, roundingMode);
outWidth = round((inWidth - filterWidth + left + right) / strideWidth + 1, roundingMode);
}
else {
throw Error(`Unknown padding parameter: ${pad}`);
}
return { padInfo, outHeight, outWidth };
}
function get3DPadAndOutInfo(pad, inDepth, inHeight, inWidth, strideDepth, strideHeight, strideWidth, filterDepth, filterHeight, filterWidth, roundingMode) {
let padInfo;
let outDepth;
let outHeight;
let outWidth;
if (typeof pad === 'number') {
const padType = (pad === 0) ? 'VALID' : 'NUMBER';
padInfo = {
top: pad,
bottom: pad,
left: pad,
right: pad,
front: pad,
back: pad,
type: padType
};
const outShape = computeOutputShape4D([inDepth, inHeight, inWidth, 1], filterDepth, 1, strideDepth, pad, roundingMode);
outDepth = outShape[0];
outHeight = outShape[1];
outWidth = outShape[2];
}
else if (pad === 'same') {
outDepth = Math.ceil(inDepth / strideDepth);
outHeight = Math.ceil(inHeight / strideHeight);
outWidth = Math.ceil(inWidth / strideWidth);
const padAlongDepth = (outDepth - 1) * strideDepth + filterDepth - inDepth;
const padAlongHeight = (outHeight - 1) * strideHeight + filterHeight - inHeight;
const padAlongWidth = (outWidth - 1) * strideWidth + filterWidth - inWidth;
const front = Math.floor(padAlongDepth / 2);
const back = padAlongDepth - front;
const top = Math.floor(padAlongHeight / 2);
const bottom = padAlongHeight - top;
const left = Math.floor(padAlongWidth / 2);
const right = padAlongWidth - left;
padInfo = { top, bottom, left, right, front, back, type: 'SAME' };
}
else if (pad === 'valid') {
padInfo = {
top: 0,
bottom: 0,
left: 0,
right: 0,
front: 0,
back: 0,
type: 'VALID'
};
outDepth = Math.ceil((inDepth - filterDepth + 1) / strideDepth);
outHeight = Math.ceil((inHeight - filterHeight + 1) / strideHeight);
outWidth = Math.ceil((inWidth - filterWidth + 1) / strideWidth);
}
else {
throw Error(`Unknown padding parameter: ${pad}`);
}
return { padInfo, outDepth, outHeight, outWidth };
}
/**
* Rounds a value depending on the rounding mode
* @param value
* @param roundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function round(value, roundingMode) {
if (!roundingMode) {
return Math.trunc(value);
}
switch (roundingMode) {
case 'round':
// used for Caffe Conv
return Math.round(value);
case 'ceil':
// used for Caffe Pool
return Math.ceil(value);
case 'floor':
return Math.floor(value);
default:
throw new Error(`Unknown roundingMode ${roundingMode}`);
}
}
function tupleValuesAreOne(param) {
const [dimA, dimB, dimC] = parseTupleParam(param);
return dimA === 1 && dimB === 1 && dimC === 1;
}
function eitherStridesOrDilationsAreOne(strides, dilations) {
return tupleValuesAreOne(strides) || tupleValuesAreOne(dilations);
}
/**
* Convert Conv2D dataFormat from 'NHWC'|'NCHW' to
* 'channelsLast'|'channelsFirst'
* @param dataFormat in 'NHWC'|'NCHW' mode
* @return dataFormat in 'channelsLast'|'channelsFirst' mode
* @throws unknown dataFormat
*/
function convertConv2DDataFormat(dataFormat) {
if (dataFormat === 'NHWC') {
return 'channelsLast';
}
else if (dataFormat === 'NCHW') {
return 'channelsFirst';
}
else {
throw new Error(`Unknown dataFormat ${dataFormat}`);
}
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const conv2DGradConfig = {
kernelName: Conv2D,
inputsToSave: ['x', 'filter'],
gradFunc: (dy, saved, attrs) => {
const [x4D, $filter] = saved;
const { dilations, strides, pad, dataFormat } = attrs;
assert(tupleValuesAreOne(dilations), () => 'Error in gradient of conv2D: dilation rates greater than 1 ' +
`are not yet supported in gradients. Got dilations '${dilations}'`);
return {
x: () => conv2DBackpropInput(x4D.shape, dy, $filter, strides, pad, dataFormat),
filter: () => conv2DBackpropFilter(x4D, dy, $filter.shape, strides, pad, dataFormat)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes a 2D convolution over the input x.
*
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, inDepth, outDepth]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `dilations` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function conv2d_(x, filter, strides, pad, dataFormat = 'NHWC', dilations = [1, 1], dimRoundingMode) {
const $x = convertToTensor(x, 'x', 'conv2d');
const $filter = convertToTensor(filter, 'filter', 'conv2d');
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
assert(x4D.rank === 4, () => `Error in conv2d: input must be rank 4, but got rank ${x4D.rank}.`);
assert($filter.rank === 4, () => `Error in conv2d: filter must be rank 4, but got rank ` +
`${$filter.rank}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in conv2d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inDepth = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];
assert(inDepth === $filter.shape[2], () => `Error in conv2d: depth of input (${inDepth}) must match ` +
`input depth for filter ${$filter.shape[2]}.`);
assert(eitherStridesOrDilationsAreOne(strides, dilations), () => 'Error in conv2D: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
const inputs = { x: x4D, filter: $filter };
const attrs = { strides, pad, dataFormat, dilations, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(Conv2D, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const conv2d = op({ conv2d_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const conv2DBackpropInputGradConfig = {
kernelName: Conv2DBackpropInput,
inputsToSave: ['dy', 'filter'],
gradFunc: (ddx, saved, attrs) => {
const [dy, filter] = saved;
const { strides, pad, dataFormat, dimRoundingMode } = attrs;
return {
dy: () => conv2d(ddx, filter, strides, pad, dataFormat, 1 /* dilations */, dimRoundingMode),
filter: () => conv2DBackpropFilter(ddx, dy, filter.shape, strides, pad, dataFormat, dimRoundingMode)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the derivative of the filter of a 3D convolution.
*
* @param x The input tensor, of rank 5 or rank 4 of shape
* [batch, depth, height, width, inChannels]. If rank 4, batch of 1 is
* assumed.
* @param dy The dy image, of rank 5 or rank 4, of shape
* [batch, depth, height, width, outDepth]. If rank 4, batch of 1 is
* assumed.
* @param filterShape The shape of the filter, length 5,
* [filterDepth, filterHeight, filterWidth, inDepth, outDepth].
* @param strides The strides of the convolution: [strideDepth, strideHeight,
* strideWidth].
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
*/
function conv3DBackpropFilter_(x, dy, filterShape, strides, pad) {
let x5D = x;
if (x.rank === 4) {
x5D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2], x.shape[3]]);
}
let dy5D = dy;
if (dy5D.rank === 4) {
dy5D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);
}
assert(x5D.rank === 5, () => `Error in conv3dDerFilter: input must be rank 5, but got shape ` +
`${x5D.shape}.`);
assert(dy5D.rank === 5, () => `Error in conv3dDerFilter: dy must be rank 5, but got shape ` +
`${dy5D.shape}.`);
assert(filterShape.length === 5, () => `Error in conv3dDerFilter: filterShape must be length 5, but got ` +
`${filterShape}.`);
assert(x5D.shape[4] === filterShape[3], () => `Error in conv3dDerFilter: depth of input ${x5D.shape[4]}) must ` +
`match input depth in filter (${filterShape[3]}.`);
assert(dy5D.shape[4] === filterShape[4], () => `Error in conv3dDerFilter: depth of dy (${dy5D.shape[4]}) must ` +
`match output depth for filter (${filterShape[4]}).`);
const inputs = { x: x5D, dy: dy5D };
const attrs = { strides, pad, filterShape };
// tslint:disable-next-line: no-unnecessary-type-assertion
return ENGINE.runKernel(Conv3DBackpropFilterV2, inputs, attrs);
}
const conv3DBackpropFilter = op({ conv3DBackpropFilter_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the derivative of the input of a 3D convolution.
*
* @param xShape The shape of the input: [batch, depth, height, width,
* in_channels]. If length of 4, batch of 1 is assumed.
* @param dy The derivative of the output, of rank 5 or rank 4 of shape
* `[batch, outDepth, outHeight, outWidth, in_channels]`.
* If rank 4, batch of 1 is assumed.
* @param filter The filter, rank 5, of shape
* `[filterDepth, filterHeight, filterWidth, inDepth, outDepth]`.
* @param strides The strides of the convolution: `[strideDepth, strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm used:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
*/
function conv3DBackpropInput_(xShape, dy, filter, strides, pad) {
assert(xShape.length === dy.rank, () => `Length of inShape ` +
`(${xShape.length}) and rank of dy (${dy.rank}) must match`);
let xShape5D = xShape;
let dy5D = dy;
let reshapedTo5D = false;
if (dy.rank === 4) {
reshapedTo5D = true;
dy5D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);
xShape5D = [1, xShape[0], xShape[1], xShape[2], xShape[3]];
}
const inDepth = xShape5D[4];
const outDepth = dy5D.shape[4];
assert(xShape5D.length === 5, () => `Error in conv3dDerInput: inShape must be length 5, but got length ` +
`${xShape5D.length}.`);
assert(dy5D.rank === 5, () => `Error in conv3dDerInput: dy must be rank 5, but got ` +
`rank ${dy5D.rank}`);
assert(filter.rank === 5, () => `Error in conv3dDerInput: filter must be rank 5, but got ` +
`rank ${filter.rank}`);
assert(inDepth === filter.shape[3], () => `Error in conv3dDerInput: depth of input (${inDepth}) must ` +
`match input depth for filter ${filter.shape[3]}.`);
assert(outDepth === filter.shape[4], () => `Error in conv3dDerInput: depth of output (${outDepth}) must ` +
`match output depth for filter ${filter.shape[4]}.`);
const inputs = { dy: dy5D, filter };
const attrs = { pad, strides, inputShape: xShape5D };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(Conv3DBackpropInputV2, inputs, attrs);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const conv3DBackpropInput = op({ conv3DBackpropInput_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const conv3DGradConfig = {
kernelName: Conv3D,
inputsToSave: ['x', 'filter'],
gradFunc: (dy, saved, attrs) => {
const { dilations, strides, pad } = attrs;
assert(tupleValuesAreOne(dilations), () => 'Error in gradient of conv3D: dilation rates greater than 1 are ' +
`not yet supported in gradients. Got dilations '${dilations}'`);
const [x5D, $filter] = saved;
return {
x: () => conv3DBackpropInput(x5D.shape, dy, $filter, strides, pad),
filter: () => conv3DBackpropFilter(x5D, dy, $filter.shape, strides, pad)
};
}
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes sin of the input Tensor element-wise: `sin(x)`
*
* ```js
* const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);
*
* x.sin().print(); // or tf.sin(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function sin_(x) {
const $x = convertToTensor(x, 'x', 'sin');
const inputs = { x: $x };
return ENGINE.runKernel(Sin, inputs);
}
const sin = op({ sin_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const cosGradConfig = {
kernelName: Cos,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(neg(sin(cast(x, 'float32'))), dy) };
}
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes hyperbolic sin of the input `tf.Tensor` element-wise: `sinh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.sinh().print(); // or tf.sinh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function sinh_(x) {
const $x = convertToTensor(x, 'x', 'sinh');
const inputs = { x: $x };
return ENGINE.runKernel(Sinh, inputs);
}
const sinh = op({ sinh_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const coshGradConfig = {
kernelName: Cosh,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(sinh(cast(x, 'float32')), dy) };
}
};
/**
* @license
* Copyright 2017 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns true if the axis specifies the inner most dimensions of the
* array.
*/
function axesAreInnerMostDims(axes, rank) {
for (let i = 0; i < axes.length; ++i) {
if (axes[axes.length - i - 1] !== rank - 1 - i) {
return false;
}
}
return true;
}
function combineLocations(outputLoc, reduceLoc, axes) {
const rank = outputLoc.length + reduceLoc.length;
const loc = [];
let outIdx = 0;
let reduceIdx = 0;
for (let dim = 0; dim < rank; dim++) {
if (axes.indexOf(dim) === -1) {
loc.push(outputLoc[outIdx++]);
}
else {
loc.push(reduceLoc[reduceIdx++]);
}
}
return loc;
}
function computeOutAndReduceShapes(aShape, axes) {
const outShape = [];
const rank = aShape.length;
for (let dim = 0; dim < rank; dim++) {
if (axes.indexOf(dim) === -1) {
outShape.push(aShape[dim]);
}
}
const reduceShape = axes.map(dim => aShape[dim]);
return [outShape, reduceShape];
}
function expandShapeToKeepDim(shape, axes) {
const reduceSubShape = axes.map(x => 1);
return combineLocations(shape, reduceSubShape, axes);
}
function assertAxesAreInnerMostDims(msg, axes, rank) {
assert(axesAreInnerMostDims(axes, rank), () => `${msg} supports only inner-most axes for now. ` +
`Got axes ${axes} and rank-${rank} input.`);
}
/**
* Returns the axes permutation to be used with `tf.transpose`, if such
* permutation is necessary. Otherwise it returns null. This method is used by
* operations that operate only on inner-most axes.
*/
function getAxesPermutation(axes, rank) {
if (axesAreInnerMostDims(axes, rank)) {
return null;
}
const result = [];
for (let i = 0; i < rank; ++i) {
if (axes.indexOf(i) === -1) {
result.push(i);
}
}
axes.forEach(axis => result.push(axis));
return result;
}
/** Returns the axes permutation that undoes the original permutation. */
function getUndoAxesPermutation(axes) {
return axes.map((axis, i) => [i, axis])
.sort((a, b) => a[1] - b[1])
.map(x => x[0]);
}
function getInnerMostAxes(numAxes, rank) {
const res = [];
for (let i = rank - numAxes; i < rank; ++i) {
res.push(i);
}
return res;
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the cumulative sum of a `tf.Tensor` along `axis`.
*
* ```js
* const x = tf.tensor([1, 2, 3, 4]);
* x.cumsum().print();
* ```
* ```js
* const x = tf.tensor([[1, 2], [3, 4]]);
* x.cumsum().print();
* ```
*
* @param x The input tensor to be summed.
* @param axis The axis along which to sum. Optional. Defaults to 0.
* @param exclusive Whether to perform exclusive cumulative sum. Optional.
* Defaults to false. If set to true then the sum of each tensor entry
* does not include its own value, but only the values previous to it
* along the specified axis.
* @param reverse Whether to sum in the opposite direction. Optional.
* Defaults to false.
*
* @doc {heading: 'Operations', subheading: 'Scan'}
*/
function cumsum_(x, axis = 0, exclusive = false, reverse = false) {
const $x = convertToTensor(x, 'x', 'cumsum');
const inputs = { x: $x };
const attrs = { axis, exclusive, reverse };
return ENGINE.runKernel(Cumsum, inputs, attrs);
}
const cumsum = op({ cumsum_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Transposes the `tf.Tensor`. Permutes the dimensions according to `perm`.
*
* The returned `tf.Tensor`'s dimension `i` will correspond to the input
* dimension `perm[i]`. If `perm` is not given, it is set to `[n-1...0]`,
* where `n` is the rank of the input `tf.Tensor`. Hence by default, this
* operation performs a regular matrix transpose on 2-D input `tf.Tensor`s.
*
* ```js
* const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]);
*
* a.transpose().print(); // or tf.transpose(a)
* ```
*
* @param x The tensor to transpose.
* @param perm The permutation of the dimensions of a.
*
* @doc {heading: 'Operations', subheading: 'Matrices'}
*/
function transpose_(x, perm) {
const $x = convertToTensor(x, 'x', 'transpose');
if (perm == null) {
perm = $x.shape.map((s, i) => i).reverse();
}
assert($x.rank === perm.length, () => `Error in transpose: rank of input ${$x.rank} ` +
`must match length of perm ${perm}.`);
perm.forEach(axis => {
assert(axis >= 0 && axis < $x.rank, () => `All entries in 'perm' must be between 0 and ${$x.rank - 1}` +
` but got ${perm}`);
});
if ($x.rank <= 1) {
return $x.clone();
}
const inputs = { x: $x };
const attrs = { perm };
return ENGINE.runKernel(Transpose, inputs, attrs);
}
const transpose = op({ transpose_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const cumsumGradConfig = {
kernelName: Cumsum,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { axis, exclusive, reverse } = attrs;
return {
x: () => {
const permutation = getAxesPermutation([axis], x.rank);
let out = cumsum(dy, axis, exclusive, !reverse);
if (permutation != null) {
out = transpose(out, permutation);
}
return out;
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function depthwiseConv2dNativeBackpropFilter_(x, dy, filterShape, strides, pad, dilations = [1, 1], dimRoundingMode) {
let x4D = x;
if (x.rank === 3) {
x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
}
let dy4D = dy;
if (dy4D.rank === 3) {
dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
}
const inputs = { x: x4D, dy: dy4D };
const attrs = { strides, pad, dimRoundingMode, dilations, filterShape };
// tslint:disable-next-line: no-unnecessary-type-assertion
return ENGINE.runKernel(DepthwiseConv2dNativeBackpropFilter, inputs, attrs);
}
const depthwiseConv2dNativeBackpropFilter = op({ depthwiseConv2dNativeBackpropFilter_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function depthwiseConv2dNativeBackpropInput_(xShape, dy, filter, strides, pad, dilations = [1, 1], dimRoundingMode) {
let dy4D = dy;
let reshapedTo4D = false;
if (dy.rank === 3) {
reshapedTo4D = true;
dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
}
const inputs = { dy: dy4D, filter };
const attrs = { strides, pad, dimRoundingMode, dilations, inputShape: xShape };
const res =
// tslint:disable-next-line: no-unnecessary-type-assertion
ENGINE.runKernel(DepthwiseConv2dNativeBackpropInput, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const depthwiseConv2dNativeBackpropInput = op({ depthwiseConv2dNativeBackpropInput_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const depthwiseConv2dNativeGradConfig = {
kernelName: DepthwiseConv2dNative,
inputsToSave: ['x', 'filter'],
gradFunc: (dy, saved, attrs) => {
const { dilations, strides, pad, dimRoundingMode } = attrs;
const $dilations = dilations == null ? [1, 1] : dilations;
assert(tupleValuesAreOne($dilations), () => 'Error in gradient of depthwiseConv2dNative: dilation rates ' +
`greater than 1 are not yet supported. Got dilations ` +
`'${$dilations}'`);
const [x, filter] = saved;
assert(x.rank === 4, () => `Error in gradient of depthwiseConv2dNative: input must be ` +
`rank 4, but got rank ${x.rank}.`);
assert(filter.rank === 4, () => `Error in gradient of depthwiseConv2dNative: filter must be ` +
`rank 4, but got rank ${filter.rank}.`);
assert(x.shape[3] === filter.shape[2], () => `Error in gradient of depthwiseConv2d: number of input ` +
`channels (${x.shape[3]}) must match the inChannels dimension ` +
`in filter ${filter.shape[2]}.`);
assert(eitherStridesOrDilationsAreOne(strides, $dilations), () => 'Error in gradient of depthwiseConv2d: Either strides or ' +
`dilations must be 1. Got strides ${strides} and dilations ` +
`'${$dilations}'.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in depthwiseConv2d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
return {
x: () => depthwiseConv2dNativeBackpropInput(x.shape, dy, filter, strides, pad, dilations, dimRoundingMode),
filter: () => depthwiseConv2dNativeBackpropFilter(x, dy, filter.shape, strides, pad, dilations, dimRoundingMode),
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const dilation2dGradConfig = {
kernelName: Dilation2D,
inputsToSave: ['x', 'filter'],
gradFunc: (dy, saved, attrs) => {
const [x, filter] = saved;
const inputInputs = { x, filter, dy };
const filterInputs = { x, filter, dy };
return {
x: () => ENGINE.runKernel(Dilation2DBackpropInput, inputInputs, attrs),
filter: () => ENGINE.runKernel(Dilation2DBackpropFilter, filterInputs, attrs)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const eluGradConfig = {
kernelName: Elu,
outputsToSave: [true],
gradFunc: (dy, saved) => {
const [y] = saved;
const inputs = { dy, y };
return { x: () => ENGINE.runKernel(EluGrad, inputs) };
}
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes exponential of the input `tf.Tensor` element-wise. `e ^ x`
*
* ```js
* const x = tf.tensor1d([1, 2, -3]);
*
* x.exp().print(); // or tf.exp(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function exp_(x) {
const $x = convertToTensor(x, 'x', 'exp');
const inputs = { x: $x };
return ENGINE.runKernel(Exp, inputs);
}
const exp = op({ exp_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const erfGradConfig = {
kernelName: Erf,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
const a = mul(exp(neg(square(x))), 2 / Math.sqrt(Math.PI));
return { x: () => mul(dy, 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 expGradConfig = {
kernelName: Exp,
outputsToSave: [true],
gradFunc: (dy, saved) => {
const [y] = saved;
return { x: () => mul(dy, 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 expandDimsGradConfig = {
kernelName: ExpandDims,
inputsToSave: ['input'],
gradFunc: (dy, saved) => {
const [input] = saved;
return { input: () => reshape(dy, input.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 expm1GradConfig = {
kernelName: Expm1,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(dy, exp(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 floorGradConfig = {
kernelName: Floor,
gradFunc: (dy) => {
return { x: () => zerosLike(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.
* =============================================================================
*/
const floorDivGradConfig = {
kernelName: FloorDiv,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
const res = div(dy, cast(b, 'float32'));
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
return reshape(sum$1(res, reduceAxes), a.shape);
}
return res;
};
const derB = () => {
let res = mul(dy, cast(a, 'float32'));
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
res = reshape(sum$1(res, reduceAxes), b.shape);
}
const tmp = square(b);
return neg(div(res, cast(tmp, 'float32')));
};
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes reciprocal of square root of the input `tf.Tensor` element-wise:
* `y = 1 / sqrt(x)`
*
* ```js
* const x = tf.tensor1d([1, 2, 4, -1]);
*
* x.rsqrt().print(); // or tf.rsqrt(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function rsqrt_(x) {
const $x = convertToTensor(x, 'x', 'rsqrt');
const inputs = { x: $x };
return ENGINE.runKernel(Rsqrt, inputs);
}
const rsqrt = op({ rsqrt_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Construct a tensor by repeating it the number of times given by reps.
*
* This operation creates a new tensor by replicating `input` `reps`
* times. The output tensor's i'th dimension has `input.shape[i] *
* reps[i]` elements, and the values of `input` are replicated
* `reps[i]` times along the i'th dimension. For example, tiling
* `[a, b, c, d]` by `[2]` produces `[a, b, c, d, a, b, c, d]`.
*
* ```js
* const a = tf.tensor1d([1, 2]);
*
* a.tile([2]).print(); // or a.tile([2])
* ```
*
* ```js
* const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* a.tile([1, 2]).print(); // or a.tile([1, 2])
* ```
* @param x The tensor to tile.
* @param reps Determines the number of replications per dimension.
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function tile_(x, reps) {
const $x = convertToTensor(x, 'x', 'tile', 'string_or_numeric');
assert($x.rank === reps.length, () => `Error in transpose: rank of input ${$x.rank} ` +
`must match length of reps ${reps}.`);
const inputs = { x: $x };
const attrs = { reps };
return ENGINE.runKernel(Tile, inputs, attrs);
}
const tile = op({ tile_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const fusedBatchNormGradConfig = {
kernelName: FusedBatchNorm,
inputsToSave: ['x', 'mean', 'variance', 'scale'],
gradFunc: (dy, saved, attrs) => {
const { varianceEpsilon } = attrs;
const [x, mean, variance, scale] = saved;
const scaleValue = scale == null ? scalar(1) : scale;
const reductionAxes = getReductionAxes(mean.shape, x.shape);
const tileShape = [];
if (mean.rank === 1) {
for (let i = 0; i < x.shape.length - 1; ++i) {
tileShape.push(x.shape[i]);
}
tileShape.push(1);
}
const xMinusMean = sub(x, mean);
const dyTimesScaleValue = mul(dy, scaleValue);
const oneOverSqrtVariance = rsqrt(add$1(variance, scalar(varianceEpsilon)));
const minusHalfRCube = mul(mul(mul(oneOverSqrtVariance, oneOverSqrtVariance), oneOverSqrtVariance), scalar(-0.5));
const derX = () => {
if (mean.rank === 1) {
return reshape(mul(mul(dy, tile(reshape(oneOverSqrtVariance, [1, 1, 1, mean.shape[0]]), tileShape)), scaleValue), x.shape);
}
else {
return reshape(mul(mul(dy, oneOverSqrtVariance), scaleValue), x.shape);
}
};
const derMean = () => {
let meanDer = mul(mul(oneOverSqrtVariance, scalar(-1)), dyTimesScaleValue);
if (mean.rank === 1) {
meanDer = sum$1(meanDer, reductionAxes);
}
return reshape(meanDer, mean.shape);
};
const derVariance = () => {
let varianceDer = mul(mul(minusHalfRCube, xMinusMean), dyTimesScaleValue);
if (mean.rank === 1) {
varianceDer = sum$1(varianceDer, reductionAxes);
}
return reshape(varianceDer, mean.shape);
};
const derScale = () => {
const xMinusMean2TimesRsqrt = mul(xMinusMean, oneOverSqrtVariance);
let scaleDer = mul(dy, xMinusMean2TimesRsqrt);
if (mean.rank === 1) {
scaleDer = sum$1(scaleDer, reductionAxes);
}
return reshape(scaleDer, mean.shape);
};
const derOffset = () => {
let offsetDer = dy;
if (mean.rank === 1) {
offsetDer = sum$1(offsetDer, reductionAxes);
}
return reshape(offsetDer, mean.shape);
};
return {
x: derX,
mean: derMean,
variance: derVariance,
scale: derScale,
offset: derOffset
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the sum along segments of a `tf.Tensor`.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* const segmentIds = tf.tensor1d([1, 2, 0, 1], 'int32');
* const numSegments = 3;
*
* x.unsortedSegmentSum(segmentIds, numSegments).print()
* //or tf.unsortedSegmentSum(x, segmentIds, numSegments)
* ```
* @param x The `tf.Tensor` that will be summed along its segments.
* @param segmentIds A `tf.Tensor1D` whose rank is equal to the rank of `x`'s
* dimension along the `axis`. Maps each element of `x` to a segment.
* @param numSegments The number of distinct `segmentIds`.
*
* @doc {heading: 'Operations', subheading: 'Segment'}
*/
function unsortedSegmentSum_(x, segmentIds, numSegments) {
const $x = convertToTensor(x, 'x', 'unsortedSegmentSum');
const $segmentIds = convertToTensor(segmentIds, 'segmentIds', 'unsortedSegmentSum', 'int32');
assert(isInt(numSegments), () => 'numSegments must be of dtype int');
const inputs = { x: $x, segmentIds: $segmentIds };
const attrs = { numSegments };
return ENGINE.runKernel(UnsortedSegmentSum, inputs, attrs);
}
const unsortedSegmentSum = op({ unsortedSegmentSum_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const gatherGradConfig = {
kernelName: GatherV2,
inputsToSave: ['x', 'indices'],
gradFunc: (dy, saved, attrs) => {
const [x, indices] = saved;
const { axis } = attrs;
const parsedAxis = parseAxisParam(axis, x.shape)[0];
const derX = () => {
const paramsShape = x.shape;
const indicesSize = indices.size;
const outerShape = paramsShape.slice(0, parsedAxis);
const outerDims = outerShape.length;
const innerShape = paramsShape.slice(axis, paramsShape.length).slice(1);
const innerDims = innerShape.length;
const outerAxesIndices = arrayRange(0, outerDims);
const innerAxesIndices = arrayRange(outerDims + 1, outerDims + 1 + innerDims);
const valuesShape = arrayConcat([outerShape, [indicesSize], innerShape]);
const values = reshape(dy, valuesShape);
const reshapedIndices = reshape(indices, [indicesSize]);
const transposeDims = arrayConcat([[outerDims], outerAxesIndices, innerAxesIndices]);
const valuesTranspose = transpose(values, transposeDims);
let paramsGrad = unsortedSegmentSum(valuesTranspose, reshapedIndices, x.shape[parsedAxis]);
const invertTransposeDims = getUndoAxesPermutation(transposeDims);
paramsGrad = transpose(paramsGrad, invertTransposeDims);
return paramsGrad;
};
return { x: derX, indices: () => indices };
}
};
function arrayRange(start, stop) {
const result = [];
for (let i = start; i < stop; ++i) {
result.push(i);
}
return result;
}
function arrayConcat(arrays) {
const result = [];
for (let i = 0; i < arrays.length; ++i) {
for (let j = 0; j < arrays[i].length; ++j) {
result.push(arrays[i][j]);
}
}
return result;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const greaterEqualGradConfig = {
kernelName: GreaterEqual,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
return { a: () => zerosLike(a), b: () => zerosLike(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.
* =============================================================================
*/
const identityGradConfig = {
kernelName: Identity,
gradFunc: (dy) => {
return { x: () => cast(dy, '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 isFiniteGradConfig = {
kernelName: IsFinite,
gradFunc: (dy) => {
// TODO(nsthorat): Let gradients be null for cases where we want to stop
// backpropgation.
return { x: () => zerosLike(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.
* =============================================================================
*/
const isInfGradConfig = {
kernelName: IsInf,
gradFunc: (dy) => {
// TODO(nsthorat): Let gradients be null for cases where we want to stop
// backpropgation.
return { x: () => zerosLike(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.
* =============================================================================
*/
const isNanGradConfig = {
kernelName: IsNan,
gradFunc: (dy) => {
// TODO(nsthorat): Let gradients be null for cases where we want to stop
// backpropgation.
return { x: () => zerosLike(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.
* =============================================================================
*/
/**
* Returns the truth value of (a > b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.greater(b).print();
* ```
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function greater_(a, b) {
let $a = convertToTensor(a, 'a', 'greater');
let $b = convertToTensor(b, 'b', 'greater');
[$a, $b] = makeTypesMatch($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Greater, inputs);
}
const greater = op({ greater_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const leakyReluGradConfig = {
kernelName: LeakyRelu,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { alpha } = attrs;
const mask = greater(x, 0);
// Returns `gradients * (features > 0) + alpha * gradients * (features <=
// 0)`.
return { x: () => where(mask, dy, mul(dy, alpha)) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const log1pGradConfig = {
kernelName: Log1p,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => div(dy, add$1(x, 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 logGradConfig = {
kernelName: Log,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => div(dy, cast(x, '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 logSoftmaxGradConfig = {
kernelName: LogSoftmax,
inputsToSave: [],
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const [value] = saved;
const { axis } = attrs;
return {
logits: () => {
const keepDims = true;
const softmax = exp(value);
return sub(dy, mul(sum$1(dy, axis, keepDims), softmax));
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function localResponseNormalizationBackprop_(x, y, dy, depthRadius = 5, bias = 1, alpha = 1, beta = 0.5) {
const inputs = { x, y, dy };
const attrs = { depthRadius, bias, alpha, beta };
return ENGINE.runKernel(LRNGrad, inputs, attrs);
}
const localResponseNormalizationBackprop = op({ localResponseNormalizationBackprop_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const lrnGradConfig = {
kernelName: LRN,
inputsToSave: ['x'],
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const [x, y] = saved;
const { depthRadius, bias, alpha, beta } = attrs;
return {
x: () => localResponseNormalizationBackprop(x, y, dy, depthRadius, bias, alpha, beta)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of (a == b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.equal(b).print();
* ```
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function equal_(a, b) {
let $a = convertToTensor(a, 'a', 'equal');
let $b = convertToTensor(b, 'b', 'equal');
[$a, $b] = makeTypesMatch($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Equal, inputs);
}
const equal = op({ equal_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Gradient helper function for the min and max operations.
*/
function gradForMinAndMax(dy, y, xOrig, origAxes) {
if (y.rank < xOrig.rank) {
y = reshape(y, expandShapeToKeepDim(y.shape, origAxes));
}
if (dy.rank < xOrig.rank) {
dy = reshape(dy, expandShapeToKeepDim(dy.shape, origAxes));
}
return {
x: () => {
const dx = mul(dy, cast(equal(xOrig, y), dy.dtype));
return dx;
}
};
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const maxGradConfig = {
kernelName: Max,
inputsToSave: ['x'],
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const maxAttrs = attrs;
const { reductionIndices } = maxAttrs;
const x = saved[0];
const y = saved[1];
const origAxes = parseAxisParam(reductionIndices, x.shape);
const maxGrad = gradForMinAndMax(dy, y, x, origAxes);
return {
x: () => {
return maxGrad['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.
* =============================================================================
*/
/**
* Returns the truth value of (a < b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.less(b).print();
* ```
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function less_(a, b) {
let $a = convertToTensor(a, 'a', 'less');
let $b = convertToTensor(b, 'b', 'less');
[$a, $b] = makeTypesMatch($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Less, inputs);
}
const less = op({ less_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const maximumGradConfig = {
kernelName: Maximum,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const derA = () => mul(dy, cast(greaterEqual(a, b), 'float32'));
const derB = () => mul(dy, cast(less(a, b), 'float32'));
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the backprop of a 3d max pool.
*
* @param dy The dy error, of rank 5 of shape
* [batchSize, depth, height, width, channels].
* assumed.
* @param input The original input image, of rank 5 or rank 4 of shape
* [batchSize, depth, height, width, channels].
* @param output The original output image, of rank 5 of shape
* [batchSize, outDepth, outHeight, outWidth, channels].
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function maxPool3dGrad_(dy, input, output, filterSize, strides, pad, dimRoundingMode) {
const $dy = convertToTensor(dy, 'dy', 'maxPool3dGrad');
const $input = convertToTensor(input, 'input', 'maxPool3dGrad');
const $output = convertToTensor(output, 'output', 'maxPool3dGrad');
let dy5D = $dy;
let input5D = $input;
let output5D = $output;
let reshapedTo5D = false;
if ($input.rank === 4) {
reshapedTo5D = true;
dy5D = reshape($dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2], $dy.shape[3]]);
input5D = reshape($input, [
1, $input.shape[0], $input.shape[1], $input.shape[2], $input.shape[3]
]);
output5D = reshape($output, [
1, $output.shape[0], $output.shape[1], $output.shape[2], $output.shape[3]
]);
}
assert(dy5D.rank === 5, () => `Error in maxPool3dGrad: dy must be rank 5 but got rank ` +
`${dy5D.rank}.`);
assert(input5D.rank === 5, () => `Error in maxPool3dGrad: input must be rank 5 but got rank ` +
`${input5D.rank}.`);
assert(output5D.rank === 5, () => `Error in maxPool3dGrad: output must be rank 5 but got rank ` +
`${output5D.rank}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in maxPool3dGrad: pad must be an integer when ` +
`using, dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { dy: dy5D, input: input5D, output: output5D };
const attrs = { filterSize, strides, pad, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(MaxPool3DGrad, inputs, attrs);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const maxPool3dGrad = op({ maxPool3dGrad_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const maxPool3DGradConfig = {
kernelName: MaxPool3D,
inputsToSave: ['x'],
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const [x, y] = saved;
const { filterSize, strides, pad, dimRoundingMode } = attrs;
return {
x: () => maxPool3dGrad(dy, x, y, filterSize, strides, pad, dimRoundingMode)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the backprop of a 2D max pool.
*
* @param dy The dy error, of rank 4 or rank 3 of shape
* [batchSize, height, width, channels]. If rank 3, batch of 1 is
* assumed.
* @param input The original input image, of rank 4, of shape
* [batchSize, height, width, channels].
* @param output The original output image, of rank 4, of shape
* [batchSize, outHeight, outWidth, channels].
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function maxPoolGrad_(dy, input, output, filterSize, strides, pad, dimRoundingMode) {
const $dy = convertToTensor(dy, 'dy', 'maxPoolGrad');
const $input = convertToTensor(input, 'input', 'maxPoolGrad');
const $output = convertToTensor(output, 'output', 'maxPoolGrad');
assert($input.rank === $dy.rank, () => `Rank of input (${$input.rank}) does not match rank of dy ` +
`(${$dy.rank})`);
assert($dy.rank === 4, () => `Error in maxPoolGrad: dy must be rank 4 but got rank ` +
`${$dy.rank}.`);
assert($input.rank === 4, () => `Error in maxPoolGrad: input must be rank 4 but got rank ` +
`${$input.rank}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in maxPoolGrad: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { dy: $dy, input: $input, output: $output };
const attrs = { filterSize, strides, pad, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
return ENGINE.runKernel(MaxPoolGrad, inputs, attrs);
}
const maxPoolGrad = op({ maxPoolGrad_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const maxPoolGradConfig = {
kernelName: MaxPool,
inputsToSave: ['x'],
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const [x, y] = saved;
const { filterSize, strides, pad } = attrs;
return {
x: () => maxPoolGrad(dy, x, y, filterSize, strides, pad)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Converts two real numbers to a complex number.
*
* Given a tensor `real` representing the real part of a complex number, and a
* tensor `imag` representing the imaginary part of a complex number, this
* operation returns complex numbers elementwise of the form [r0, i0, r1, i1],
* where r represents the real part and i represents the imag part.
*
* The input tensors real and imag must have the same shape.
*
* ```js
* const real = tf.tensor1d([2.25, 3.25]);
* const imag = tf.tensor1d([4.75, 5.75]);
* const complex = tf.complex(real, imag);
*
* complex.print();
* ```
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function complex_(real, imag) {
const $real = convertToTensor(real, 'real', 'complex');
const $imag = convertToTensor(imag, 'imag', 'complex');
assertShapesMatch($real.shape, $imag.shape, `real and imag shapes, ${$real.shape} and ${$imag.shape}, ` +
`must match in call to tf.complex().`);
const inputs = { real: $real, imag: $imag };
return ENGINE.runKernel(Complex, inputs);
}
const complex = op({ complex_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with all elements set to 0.
*
* ```js
* tf.zeros([2, 2]).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param dtype The type of an element in the resulting tensor. Can
* be 'float32', 'int32' or 'bool'. Defaults to 'float'.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function zeros(shape, dtype = 'float32') {
if (dtype === 'complex64') {
const real = zeros(shape, 'float32');
const imag = zeros(shape, 'float32');
return complex(real, imag);
}
const values = makeZerosTypedArray(sizeFromShape(shape), dtype);
return ENGINE.makeTensor(values, shape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with all elements set to 1.
*
* ```js
* tf.ones([2, 2]).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param dtype The type of an element in the resulting tensor. Defaults to
* 'float'.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function ones$1(shape, dtype = 'float32') {
if (dtype === 'complex64') {
const real = ones$1(shape, 'float32');
const imag = zeros(shape, 'float32');
return complex(real, imag);
}
const values = makeOnesTypedArray(sizeFromShape(shape), dtype);
return ENGINE.makeTensor(values, shape, 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 meanGradConfig = {
kernelName: Mean,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { axis } = attrs;
const axes = parseAxisParam(axis, x.shape);
const shapes = computeOutAndReduceShapes(x.shape, axes);
const reduceShape = shapes[1];
const reduceSize = sizeFromShape(reduceShape);
const derX = () => {
const expandedDyShape = x.shape.slice();
axes.forEach(axis => {
expandedDyShape[axis] = 1;
});
const expandedDy = reshape(dy, expandedDyShape);
const res = div(mul(expandedDy, ones$1(x.shape, 'float32')), reduceSize);
return res;
};
return { x: derX };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const minGradConfig = {
kernelName: Min,
inputsToSave: ['x'],
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const minAttrs = attrs;
const { axis } = minAttrs;
const [x, y] = saved;
const origAxes = parseAxisParam(axis, x.shape);
const minGrad = gradForMinAndMax(dy, y, x, origAxes);
return {
x: () => {
return minGrad['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 minimumGradConfig = {
kernelName: Minimum,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const derA = () => mul(dy, cast(lessEqual(a, b), 'float32'));
const derB = () => mul(dy, cast(greater(a, b), 'float32'));
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Extracts a slice from a `tf.Tensor` starting at coordinates `begin`
* and is of size `size`.
*
* Also available are stricter rank-specific methods with the same signature
* as this method that assert that `x` is of the given rank:
* - `tf.slice1d`
* - `tf.slice2d`
* - `tf.slice3d`
* - `tf.slice4d`
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
*
* x.slice([1], [2]).print();
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* x.slice([1, 0], [1, 2]).print();
* ```
* @param x The input `tf.Tensor` to slice from.
* @param begin The coordinates to start the slice from. The length can be
* less than the rank of x - the rest of the axes will have implicit 0 as
* start. Can also be a single number, in which case it specifies the
* first axis.
* @param size The size of the slice. The length can be less than the rank of
* x - the rest of the axes will have implicit -1. A value of -1 requests
* the rest of the dimensions in the axis. Can also be a single number,
* in which case it specifies the size of the first axis.
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function slice_(x, begin, size) {
const $x = convertToTensor(x, 'x', 'slice', 'string_or_numeric');
if ($x.rank === 0) {
throw new Error('Slicing scalar is not possible');
}
const inputs = { x: $x };
const attrs = { begin, size };
return ENGINE.runKernel(Slice, inputs, attrs);
}
const slice = op({ slice_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const mirrorPadGradConfig = {
kernelName: MirrorPad,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
// Pad introduces values around the original tensor, so the gradient
// slices the original shape out of the gradient.
const x = saved[0];
const { paddings } = attrs;
const begin = paddings.map(p => p[0]);
return { x: () => slice(dy, begin, x.shape) };
}
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes floor of input `tf.Tensor` element-wise: `floor(x)`.
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3]);
*
* x.floor().print(); // or tf.floor(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function floor_(x) {
const $x = convertToTensor(x, 'x', 'floor');
const inputs = { x: $x };
return ENGINE.runKernel(Floor, inputs);
}
const floor = op({ floor_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const modGradConfig = {
kernelName: Mod,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
return reshape(sum$1(dy, reduceAxes), a.shape);
}
return dy;
};
const derB = () => {
const res = mul(dy, neg(floor(div(a, b))));
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
return reshape(sum$1(res, reduceAxes), b.shape);
}
return res;
};
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const multiplyGradConfig = {
kernelName: Multiply,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
const res = mul(dy, cast(b, 'float32'));
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
return reshape(sum$1(res, reduceAxes), a.shape);
}
return res;
};
const derB = () => {
const res = mul(dy, cast(a, 'float32'));
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
return reshape(sum$1(res, reduceAxes), b.shape);
}
return res;
};
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const negGradConfig = {
kernelName: Neg,
gradFunc: (dy) => {
return { x: () => neg(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.
* =============================================================================
*/
const oneHotGradConfig = {
kernelName: OneHot,
inputsToSave: ['indices'],
gradFunc: (dy, saved) => {
const indices = saved[0];
return { indices: () => zeros(indices.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 onesLikeGradConfig = {
kernelName: OnesLike,
gradFunc: (dy) => {
return { x: () => zerosLike(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.
* =============================================================================
*/
/**
* Unstacks a `tf.Tensor` of rank-`R` into a list of rank-`(R-1)` `tf.Tensor`s.
*
* ```js
* const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* tf.unstack(a).forEach(tensor => tensor.print());
* ```
*
* @param x A tensor object.
* @param axis The axis to unstack along. Defaults to 0 (the first dim).
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function unstack_(x, axis = 0) {
const $x = convertToTensor(x, 'x', 'unstack', 'string_or_numeric');
assert(axis >= -$x.shape.length && axis < $x.shape.length, () => `Axis = ${axis} is not in [-${$x.shape.length}, ${$x.shape.length})`);
const inputs = { value: $x };
const attrs = { axis };
return ENGINE.runKernel(Unpack, inputs, attrs);
}
const unstack = op({ unstack_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const packGradConfig = {
kernelName: Pack,
saveAllInputs: true,
gradFunc: (dy, saved, attrs) => {
const { axis } = attrs;
const derTensors = unstack(dy, axis);
return derTensors.map(t => () => 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 padV2GradConfig = {
kernelName: PadV2,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
// Pad introduces values around the original tensor, so the gradient
// slices the original shape out of the gradient.
const x = saved[0];
const { paddings } = attrs;
const begin = paddings.map(p => p[0]);
return { x: () => slice(dy, begin, x.shape) };
}
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes natural logarithm of the input `tf.Tensor` element-wise: `ln(x)`
*
* ```js
* const x = tf.tensor1d([1, 2, Math.E]);
*
* x.log().print(); // or tf.log(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function log_(x) {
const $x = convertToTensor(x, 'x', 'log');
const inputs = { x: $x };
return ENGINE.runKernel(Log, inputs);
}
const log = op({ log_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the power of one `tf.Tensor` to another. Supports broadcasting.
*
* Given a `tf.Tensor` x and a `tf.Tensor` y, this operation computes x^y for
* corresponding elements in x and y. The result's dtype will be the upcasted
* type of the `base` and `exp` dtypes.
*
* ```js
* const a = tf.tensor([[2, 3], [4, 5]])
* const b = tf.tensor([[1, 2], [3, 0]]).toInt();
*
* a.pow(b).print(); // or tf.pow(a, b)
* ```
*
* ```js
* const a = tf.tensor([[1, 2], [3, 4]])
* const b = tf.tensor(2).toInt();
*
* a.pow(b).print(); // or tf.pow(a, b)
* ```
* We also expose `powStrict` which has the same signature as this op and
* asserts that `base` and `exp` are the same shape (does not broadcast).
*
* @param base The base `tf.Tensor` to pow element-wise.
* @param exp The exponent `tf.Tensor` to pow element-wise.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function pow_(base, exp) {
let $base = convertToTensor(base, 'base', 'pow');
let $exp = convertToTensor(exp, 'exp', 'pow');
[$base, $exp] = makeTypesMatch($base, $exp);
const inputs = { a: $base, b: $exp };
return ENGINE.runKernel(Pow, inputs);
}
const pow = op({ pow_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const powGradConfig = {
kernelName: Pow,
inputsToSave: ['a', 'b'],
outputsToSave: [true],
gradFunc: (dy, saved) => {
const [a, b, y] = saved;
const base = a;
const exp = b;
const outShape = assertAndGetBroadcastShape(base.shape, exp.shape);
const derBase = () => {
const expFloat = cast(exp, 'float32');
let res = mul(dy, mul(expFloat, pow(base, sub(expFloat, scalar(1)))));
const reduceAxes = getReductionAxes(base.shape, outShape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, base.shape);
};
const derExp = () => {
const condition = greater(base, 0);
const logBase = where(condition, log(base), zerosLike(base));
let res = mul(dy, mul(y, logBase));
const reduceAxes = getReductionAxes(exp.shape, outShape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, exp.shape);
};
return { a: derBase, b: derExp };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const preluGradConfig = {
kernelName: Prelu,
inputsToSave: ['x', 'alpha'],
gradFunc: (dy, saved) => {
const [x, alpha] = saved;
const mask = greater(x, 0);
return {
x: () => where(mask, dy, mul(dy, alpha)),
alpha: () => {
let res = where(mask, zerosLike(dy), mul(dy, x));
const reduceAxes = getReductionAxes(alpha.shape, dy.shape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, alpha.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 divGradConfig = {
kernelName: RealDiv,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
const res = div(dy, cast(b, 'float32'));
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
return reshape(sum$1(res, reduceAxes), a.shape);
}
return res;
};
const derB = () => {
let res = mul(dy, cast(a, 'float32'));
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
res = reshape(sum$1(res, reduceAxes), b.shape);
}
const tmp = square(b);
return neg(div(res, cast(tmp, 'float32')));
};
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const reciprocalGradConfig = {
kernelName: Reciprocal,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => div(dy, neg(square(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 relu6GradConfig = {
kernelName: Relu6,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
const mask = mul(lessEqual(x, 6), step(x));
return { x: () => mul(dy, cast(mask, '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 reluGradConfig = {
kernelName: Relu,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(dy, cast(step(x), '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 reshapeGradConfig = {
kernelName: Reshape,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => reshape(dy, x.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 resizeBilinearGradConfig = {
kernelName: ResizeBilinear,
inputsToSave: ['images'],
gradFunc: (dy, saved, attrs) => {
const [images] = saved;
const inputs = { dy, images };
const imagesDer = () =>
// tslint:disable-next-line: no-unnecessary-type-assertion
ENGINE.runKernel(ResizeBilinearGrad, inputs, attrs);
return { images: imagesDer };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const resizeNearestNeighborGradConfig = {
kernelName: ResizeNearestNeighbor,
inputsToSave: ['images'],
gradFunc: (dy, saved, attrs) => {
const [images] = saved;
const inputs = { dy, images };
const imagesDer = () =>
// tslint:disable-next-line: no-unnecessary-type-assertion
ENGINE.runKernel(ResizeNearestNeighborGrad, inputs, attrs);
return { images: imagesDer };
}
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Reverses a `tf.Tensor` along a specified axis.
*
* Also available are stricter rank-specific methods that assert that `x` is
* of the given rank:
* - `tf.reverse1d`
* - `tf.reverse2d`
* - `tf.reverse3d`
* - `tf.reverse4d`
*
* Except `tf.reverse1d` (which does not have axis param), all methods have
* same signature as this method.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
*
* x.reverse().print();
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.reverse(axis).print();
* ```
* @param x The input tensor to be reversed.
* @param axis The set of dimensions to reverse. Must be in the
* range [-rank(x), rank(x)). Defaults to all axes.
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function reverse_(x, axis) {
const $x = convertToTensor(x, 'x', 'reverse');
const inputs = { x: $x };
const attrs = { dims: axis };
return ENGINE.runKernel(Reverse, inputs, attrs);
}
const reverse = op({ reverse_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const reverseGradConfig = {
kernelName: Reverse,
gradFunc: (dy, saved, attrs) => {
const { dims } = attrs;
const axes = parseAxisParam(dims, dy.shape);
return { x: () => reverse(dy, axes) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const roundGradConfig = {
kernelName: Round,
gradFunc: (dy) => {
// TODO(nsthorat): Let gradients be null for cases where we want to stop
// backpropgation.
return { x: () => zerosLike(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.
* =============================================================================
*/
const rsqrtGradConfig = {
kernelName: Rsqrt,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => neg(div(dy, mul(pow(x, 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.
* =============================================================================
*/
/**
* Returns the truth value of `NOT x` element-wise.
*
* ```js
* const a = tf.tensor1d([false, true], 'bool');
*
* a.logicalNot().print();
* ```
*
* @param x The input tensor. Must be of dtype 'bool'.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function logicalNot_(x) {
const $x = convertToTensor(x, 'x', 'logicalNot', 'bool');
const inputs = { x: $x };
return ENGINE.runKernel(LogicalNot, inputs);
}
const logicalNot = op({ logicalNot_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const selectGradConfig = {
kernelName: Select,
inputsToSave: ['condition'],
gradFunc: (dy, saved) => {
const [condition] = saved;
return {
// TODO(julianoks): Return null for condition gradient
// when backprop supports it.
condition: () => cast(zerosLike(condition), 'float32'),
t: () => mul(dy, cast(condition, dy.dtype)),
e: () => mul(dy, cast(logicalNot(condition), dy.dtype))
};
}
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const SELU_SCALEALPHA = 1.7580993408473768599402175208123;
const SELU_SCALE = 1.0507009873554804934193349852946;
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const seluGradConfig = {
kernelName: Selu,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return {
x: () => {
const mask = greater(x, scalar(0));
const scaleAlpha = scalar(SELU_SCALEALPHA);
const scale = scalar(SELU_SCALE);
const greaterThanZeroDer = mul(dy, scale);
const lessEqualZeroDer = mul(mul(dy, scaleAlpha), exp(cast(x, 'float32')));
return where(mask, greaterThanZeroDer, lessEqualZeroDer);
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const sigmoidGradConfig = {
kernelName: Sigmoid,
outputsToSave: [true],
gradFunc: (dy, saved) => {
const [y] = saved;
return { x: () => mul(dy, mul(y, sub(scalar(1), 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 signGradConfig = {
kernelName: Sign,
gradFunc: (dy) => {
return { x: () => zerosLike(dy) };
}
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes cos of the input `tf.Tensor` element-wise: `cos(x)`
*
* ```js
* const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);
*
* x.cos().print(); // or tf.cos(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function cos_(x) {
const $x = convertToTensor(x, 'x', 'cos');
const inputs = { x: $x };
return ENGINE.runKernel(Cos, inputs);
}
const cos = op({ cos_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const sinGradConfig = {
kernelName: Sin,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(cos(cast(x, 'float32')), dy) };
}
};
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes hyperbolic cos of the input `tf.Tensor` element-wise: `cosh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.cosh().print(); // or tf.cosh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function cosh_(x) {
const $x = convertToTensor(x, 'x', 'cosh');
const inputs = { x: $x };
return ENGINE.runKernel(Cosh, inputs);
}
const cosh = op({ cosh_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const sinhGradConfig = {
kernelName: Sinh,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(cosh(cast(x, 'float32')), 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.
* =============================================================================
*/
/**
* Pads a `tf.Tensor` with a given value and paddings.
*
* This operation implements `CONSTANT` mode. For `REFLECT` and `SYMMETRIC`,
* refer to `tf.mirrorPad`
*
* Also available are stricter rank-specific methods with the same signature
* as this method that assert that `paddings` is of given length.
* - `tf.pad1d`
* - `tf.pad2d`
* - `tf.pad3d`
* - `tf.pad4d`
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* x.pad([[1, 2]]).print();
* ```
* @param x The tensor to pad.
* @param paddings An array of length `R` (the rank of the tensor), where
* each element is a length-2 tuple of ints `[padBefore, padAfter]`,
* specifying how much to pad along each dimension of the tensor.
* @param constantValue The pad value to use. Defaults to 0.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function pad_(x, paddings, constantValue = 0) {
const $x = convertToTensor(x, 'x', 'pad');
if ($x.rank === 0) {
throw new Error('pad(scalar) is not defined. Pass non-scalar to pad');
}
const attrs = { paddings, constantValue };
const inputs = { x: $x };
return ENGINE.runKernel(PadV2, inputs, attrs);
}
const pad = op({ pad_ });
/**
* @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 assertParamsValid(input, begin, size) {
const inputRank = input.shape.length;
assert(inputRank === begin.length, () => `Error in slice${inputRank}D: Length of begin ${begin} must ` +
`match the rank of the array (${inputRank}).`);
assert(inputRank === size.length, () => `Error in slice${inputRank}D: Length of size ${size} must ` +
`match the rank of the array (${inputRank}).`);
for (let i = 0; i < inputRank; ++i) {
assert(begin[i] + size[i] <= input.shape[i], () => `Error in slice${inputRank}D: begin[${i}] + size[${i}] ` +
`(${begin[i] + size[i]}) would overflow input.shape[${i}] (${input.shape[i]})`);
}
}
/** Converts a binary mask to an array of axes. Used in stridedSlice(). */
function maskToAxes(mask) {
const axes = [];
let axis = 0;
while (mask > 0) {
if (mask & 1) {
axes.push(axis);
}
mask /= 2;
axis++;
}
return axes;
}
/** Computes the output shape given the strided slice params. */
function computeOutShape(begin, end, strides) {
const size = [];
for (let axis = 0; axis < begin.length; axis++) {
size[axis] = Math.ceil((end[axis] - begin[axis]) / strides[axis]);
}
return size;
}
// Creates full selection at the elided dimensions. If the dimension matches
// the ellipsis mask, override the current stride value. Otherwise, insert.
function stridesWithElidedDims(strides, ellipsisInsertionIndex, numElidedAxes, inputShape) {
const newStrides = [...strides];
for (let i = newStrides.length; i < inputShape.length; i++) {
newStrides.push(1);
}
for (let i = 0; i < numElidedAxes; i++) {
if (i === 0) {
newStrides[ellipsisInsertionIndex] = 1;
}
else {
newStrides.splice(ellipsisInsertionIndex, 0 /* num elements to delete */, 1 /* element to add */);
newStrides.pop();
}
}
return newStrides;
}
function unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, normalizedAxis) {
if (normalizedAxis <= ellipsisInsertionIndex) {
return normalizedAxis;
}
return normalizedAxis - (numElidedAxes - 1);
}
function getElidedAxes(numElidedAxes, ellipsisInsertionIndex) {
const elidedAxes = [];
for (let i = 0; i < numElidedAxes; i++) {
elidedAxes.push(ellipsisInsertionIndex + i);
}
return elidedAxes;
}
// Normalize the start, end and strides.
function getNormalizedAxes(inputShape, ellipsisAxes, numInterpolatedAxes, begin, end, strides, beginMask, endMask, ellipsisMask) {
const inputRank = inputShape.length;
let normalizedBegin = new Array(inputRank), normalizedEnd = new Array(inputRank), normalizedStrides = new Array(inputRank);
if (ellipsisAxes.length && numInterpolatedAxes > 0) {
const fullIndex = ellipsisAxes[0];
// The ellipsis applies to the masked index as well as any dimensions
// that are interpolated.
const numElidedAxes = numInterpolatedAxes + 1;
normalizedBegin = startIndicesWithElidedDims(beginMask, fullIndex, numElidedAxes, begin, inputShape);
normalizedEnd = stopIndicesWithElidedDims(endMask, fullIndex, numElidedAxes, end, inputShape);
normalizedStrides =
stridesWithElidedDims(strides, fullIndex, numElidedAxes, inputShape);
}
else {
for (let axis = 0; axis < inputRank; axis++) {
normalizedBegin[axis] = startForAxis(beginMask, begin, strides, inputShape, axis, ellipsisMask);
normalizedEnd[axis] =
stopForAxis(endMask, end, strides, inputShape, axis, ellipsisMask);
normalizedStrides[axis] = stridesForAxis(strides, axis, ellipsisMask);
}
}
return {
begin: normalizedBegin,
end: normalizedEnd,
strides: normalizedStrides
};
}
// Creates full selection at the elided dimensions. If the dimension matches
// the ellipsis mask, override the current start value. Otherwise, insert.
function startIndicesWithElidedDims(beginMask, ellipsisInsertionIndex, numElidedAxes, originalBegin, inputShape) {
const newIndices = [...inputShape];
const elidedAxes = getElidedAxes(numElidedAxes, ellipsisInsertionIndex);
for (let axis = 0; axis < newIndices.length; axis++) {
if (elidedAxes.indexOf(axis) > -1) {
newIndices[axis] = 0;
}
else {
const originalAxis = unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, axis);
let originalValue = originalBegin[originalAxis];
if (beginMask & 1 << originalAxis) {
originalValue = 0;
}
newIndices[axis] = originalValue;
}
}
return newIndices;
}
// Creates full selection at the elided dimensions. If the dimension matches
// the ellipsis mask, override the current stop value. Otherwise, insert.
function stopIndicesWithElidedDims(endMask, ellipsisInsertionIndex, numElidedAxes, originalEnd, inputShape) {
const newIndices = [...inputShape];
const elidedAxes = getElidedAxes(numElidedAxes, ellipsisInsertionIndex);
for (let axis = 0; axis < newIndices.length; axis++) {
if (elidedAxes.indexOf(axis) > -1) {
newIndices[axis] = Number.MAX_SAFE_INTEGER;
}
else {
const originalAxis = unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, axis);
let originalValue = originalEnd[originalAxis];
if (endMask & 1 << originalAxis) {
originalValue = Number.MAX_SAFE_INTEGER;
}
newIndices[axis] = originalValue;
}
}
for (let i = 0; i < newIndices.length; i++) {
// Handle negative indices
const axisSize = inputShape[i];
if (newIndices[i] < 0) {
newIndices[i] += axisSize;
}
newIndices[i] = clamp(0, newIndices[i], inputShape[i]);
}
return newIndices;
}
function stridesForAxis(strides, axis, ellipsisMask) {
let stride = strides[axis];
if (ellipsisMask & (1 << axis) || stride == null) {
stride = 1;
}
return stride;
}
function startForAxis(beginMask, startIndices, strides, inputShape, axis, ellipsisMask) {
// Begin with the specified index
let start = startIndices[axis];
const stride = strides[axis] || 1;
// Check the axis bit from right of masked axes, or the begin index is not set
// for the axis.
if (beginMask & 1 << axis || ellipsisMask & 1 << axis || start == null) {
if (stride > 0) {
// Forward iteration - use the first element. These values will get
// clamped below (Note: We could have set them to 0 and axis_size-1, but
// use lowest() and max() to maintain symmetry with StopForAxis())
start = Number.MIN_SAFE_INTEGER;
}
else {
// Backward iteration - use the last element.
start = Number.MAX_SAFE_INTEGER;
}
}
// Handle negative indices
const axisSize = inputShape[axis];
if (start < 0) {
start += axisSize;
}
// Clamping
start = clamp(0, start, axisSize - 1);
return start;
}
function stopForAxis(endMask, stopIndices, strides, inputShape, axis, ellipsisMask) {
// Begin with the specified index
let stop = stopIndices[axis];
const stride = strides[axis] || 1;
// Check the axis bit from right of masked axes, or if the stop index is not
// set for this axis.
if (endMask & (1 << axis) || ellipsisMask & (1 << axis) || stop == null) {
if (stride > 0) {
// Forward iteration - use the last element. These values will get
// clamped below
stop = Number.MAX_SAFE_INTEGER;
}
else {
// Backward iteration - use the first element.
stop = Number.MIN_SAFE_INTEGER;
}
}
// Handle negative indices
const axisSize = inputShape[axis];
if (stop < 0) {
stop += axisSize;
}
// Clamping
// Because the end index points one past the last element, we need slightly
// different clamping ranges depending on the direction.
if (stride > 0) {
// Forward iteration
stop = clamp(0, stop, axisSize);
}
else {
// Backward iteration
stop = clamp(-1, stop, axisSize - 1);
}
return stop;
}
/**
* Returns true if the slice occupies a continous set of elements in the
* 'flat' space.
*/
function isSliceContinous(shape, begin, size) {
// Index of the first axis that has size > 1.
let firstNonOneAxis = size.length;
for (let i = 0; i < size.length; i++) {
if (size[i] > 1) {
firstNonOneAxis = i;
break;
}
}
for (let i = firstNonOneAxis + 1; i < size.length; i++) {
if (begin[i] > 0 || size[i] !== shape[i]) {
return false;
}
}
return true;
}
function computeFlatOffset(begin, strides) {
let flatOffset = begin.length > 0 ? begin[begin.length - 1] : 1;
for (let i = 0; i < begin.length - 1; i++) {
flatOffset += begin[i] * strides[i];
}
return flatOffset;
}
function parseSliceParams(x, begin, size) {
// The following logic allows for more ergonomic calls.
let begin_;
const xRank = x.shape.length;
if (typeof begin === 'number') {
begin_ = [begin, ...new Array(xRank - 1).fill(0)];
}
else if (begin.length < xRank) {
begin_ = begin.concat(new Array(xRank - begin.length).fill(0));
}
else {
begin_ = begin.slice();
}
begin_.forEach(d => {
assert(d !== -1, () => 'slice() does not support negative begin indexing.');
});
let size_;
if (size == null) {
size_ = new Array(xRank).fill(-1);
}
else if (typeof size === 'number') {
size_ = [size, ...new Array(xRank - 1).fill(-1)];
}
else if (size.length < xRank) {
size_ = size.concat(new Array(xRank - size.length).fill(-1));
}
else {
size_ = size;
}
size_ = size_.map((d, i) => {
if (d >= 0) {
return d;
}
else {
assert(d === -1, () => `Negative size values should be exactly -1 but got ` +
`${d} for the slice() size at index ${i}.`);
return x.shape[i] - begin_[i];
}
});
return [begin_, size_];
}
function sliceInfo(xShape, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask) {
// make a copy because it may be modified further down.
let $begin = begin.slice();
let $end = end.slice();
let $strides = strides;
if (strides == null) {
$strides = new Array($begin.length);
}
const ellipsisAxes = maskToAxes(ellipsisMask);
if (ellipsisAxes.length > 1) {
throw new Error('Multiple ellipses in slice is not allowed.');
}
if (ellipsisMask !== 0 && newAxisMask !== 0) {
throw new Error('Using both ellipsisMask and newAxisMask is not yet supported.');
}
if (ellipsisMask !== 0 && shrinkAxisMask !== 0) {
throw new Error('Using both ellipsisMask and shrinkAxisMask is not yet supported.');
}
const numInterpolatedAxes = xShape.length - $begin.length;
// Expand the dims of x based on the newAxisMask.
const expandAxes = maskToAxes(newAxisMask);
const newShape = xShape.slice();
expandAxes.forEach(axis => {
$begin[axis] = 0;
$end[axis] = 1;
newShape.splice(axis, 0, 1);
});
const { begin: normalizedBegin, end: normalizedEnd, strides: normalizedStrides } = getNormalizedAxes(newShape, ellipsisAxes, numInterpolatedAxes, $begin, $end, $strides, beginMask, endMask, ellipsisMask);
$begin = normalizedBegin;
$end = normalizedEnd;
$strides = normalizedStrides;
const shrinkAxes = maskToAxes(shrinkAxisMask);
// Adjust the ends based on the shrink mask.
shrinkAxes.forEach(axis => {
$end[axis] = $begin[axis] + 1;
$strides[axis] = 1;
});
// Figure out the output shape.
const size = computeOutShape($begin, $end, $strides);
// Remove the axes based on shrinkMask.
const outShape = size.filter((_, axis) => shrinkAxes.indexOf(axis) === -1);
const nonStrided = $strides.every(v => v === 1);
return { nonStrided, $begin, $end, $strides, size, newShape, outShape };
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const sliceGradConfig = {
kernelName: Slice,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { begin, size } = attrs;
const inputShape = x.shape;
const [begin_, size_] = parseSliceParams(x, begin, size);
// Create an Nx2 padding where the first column represents how many
// zeros are prepended (at start) for each dimension, and the second
// column indicates how many zeros are appended (at end).
// The number of zeros to append is the shape of the input
// elementwise-subtracted by both the begin vector and sizes vector.
const paddings = [];
for (let i = 0; i < dy.rank; i++) {
paddings.push([begin_[i], inputShape[i] - begin_[i] - size_[i]]);
}
return { x: () => pad(dy, paddings) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const softmaxGradConfig = {
kernelName: Softmax,
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const [y] = saved;
const { dim } = attrs;
const keepDims = true;
const dyTimesY = mul(dy, y);
return {
logits: () => sub(dyTimesY, mul(sum$1(dyTimesY, [dim], keepDims), 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.
* =============================================================================
*/
/**
* Computes sigmoid element-wise, `1 / (1 + exp(-x))`
*
* ```js
* const x = tf.tensor1d([0, -1, 2, -3]);
*
* x.sigmoid().print(); // or tf.sigmoid(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function sigmoid_(x) {
const $x = convertToTensor(x, 'x', 'sigmoid');
const inputs = { x: $x };
return ENGINE.runKernel(Sigmoid, inputs);
}
const sigmoid = op({ sigmoid_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const softplusGradConfig = {
kernelName: Softplus,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(dy, sigmoid(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.
* =============================================================================
*/
/**
* This operation reshapes the "batch" dimension 0 into `M + 1` dimensions of
* shape `blockShape + [batch]`, interleaves these blocks back into the grid
* defined by the spatial dimensions `[1, ..., M]`, to obtain a result with
* the same rank as the input. The spatial dimensions of this intermediate
* result are then optionally cropped according to `crops` to produce the
* output. This is the reverse of `tf.spaceToBatchND`. See below for a precise
* description.
*
* ```js
* const x = tf.tensor4d([1, 2, 3, 4], [4, 1, 1, 1]);
* const blockShape = [2, 2];
* const crops = [[0, 0], [0, 0]];
*
* x.batchToSpaceND(blockShape, crops).print();
* ```
*
* @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +
* remainingShape`, where spatialShape has `M` dimensions.
* @param blockShape A 1-D array. Must have shape `[M]`, all values must
* be >= 1.
* @param crops A 2-D array. Must have shape `[M, 2]`, all values must be >= 0.
* `crops[i] = [cropStart, cropEnd]` specifies the amount to crop from input
* dimension `i + 1`, which corresponds to spatial dimension `i`. It is required
* that `cropStart[i] + cropEnd[i] <= blockShape[i] * inputShape[i + 1]`
*
* This operation is equivalent to the following steps:
*
* 1. Reshape `x` to `reshaped` of shape: `[blockShape[0], ...,
* blockShape[M-1], batch / prod(blockShape), x.shape[1], ...,
* x.shape[N-1]]`
*
* 2. Permute dimensions of `reshaped`to produce `permuted` of shape `[batch /
* prod(blockShape),x.shape[1], blockShape[0], ..., x.shape[M],
* blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`
*
* 3. Reshape `permuted` to produce `reshapedPermuted` of shape `[batch /
* prod(blockShape),x.shape[1] * blockShape[0], ..., x.shape[M] *
* blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`
*
* 4. Crop the start and end of dimensions `[1, ..., M]` of `reshapedPermuted`
* according to `crops` to produce the output of shape: `[batch /
* prod(blockShape),x.shape[1] * blockShape[0] - crops[0,0] - crops[0,1],
* ..., x.shape[M] * blockShape[M-1] - crops[M-1,0] -
* crops[M-1,1],x.shape[M+1], ..., x.shape[N-1]]`
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function batchToSpaceND_(x, blockShape, crops) {
const $x = convertToTensor(x, 'x', 'batchToSpaceND');
const prod = blockShape.reduce((a, b) => a * b);
assert($x.rank >= 1 + blockShape.length, () => `input rank is ${$x.rank} but should be > than blockShape.length ${blockShape.length}`);
assert(crops.length === blockShape.length, () => `crops.length is ${crops.length} but should be equal to blockShape.length ${blockShape.length}`);
assert($x.shape[0] % prod === 0, () => `input tensor batch is ${$x.shape[0]} but is not divisible by the product of ` +
`the elements of blockShape ${blockShape.join(' * ')} === ${prod}`);
const inputs = { x: $x };
const attrs = { blockShape, crops };
return ENGINE.runKernel(BatchToSpaceND, inputs, attrs);
}
const batchToSpaceND = op({ batchToSpaceND_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const spaceToBatchNDGradConfig = {
kernelName: SpaceToBatchND,
gradFunc: (dy, saved, attrs) => {
const { blockShape, paddings } = attrs;
return { x: () => batchToSpaceND(dy, blockShape, paddings) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Concatenates a list of `tf.Tensor`s along a given axis.
*
* The tensors ranks and types must match, and their sizes must match in all
* dimensions except `axis`.
*
* Also available are stricter rank-specific methods that assert that
* `tensors` are of the given rank:
* - `tf.concat1d`
* - `tf.concat2d`
* - `tf.concat3d`
* - `tf.concat4d`
*
* Except `tf.concat1d` (which does not have axis param), all methods have
* same signature as this method.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* a.concat(b).print(); // or a.concat(b)
* ```
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* const c = tf.tensor1d([5, 6]);
* tf.concat([a, b, c]).print();
* ```
*
* ```js
* const a = tf.tensor2d([[1, 2], [10, 20]]);
* const b = tf.tensor2d([[3, 4], [30, 40]]);
* const axis = 1;
* tf.concat([a, b], axis).print();
* ```
* @param tensors A list of tensors to concatenate.
* @param axis The axis to concate along. Defaults to 0 (the first dim).
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function concat_(tensors, axis = 0) {
assert(tensors.length >= 1, () => 'Pass at least one tensor to concat');
const $tensors = convertToTensorArray(tensors, 'tensors', 'concat', 'string_or_numeric');
if ($tensors[0].dtype === 'complex64') {
$tensors.forEach(tensor => {
if (tensor.dtype !== 'complex64') {
throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${tensor.dtype}. `);
}
});
}
if ($tensors.length === 1) {
return clone($tensors[0]);
}
const inputs = $tensors;
const attr = { axis };
return ENGINE.runKernel(Concat, inputs, attr);
}
const concat = op({ concat_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const splitVGradConfig = {
kernelName: SplitV,
gradFunc: (dy, saved, attrs) => {
const { axis } = attrs;
return { x: () => concat(dy, axis) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const sqrtGradConfig = {
kernelName: Sqrt,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => div(dy, mul(sqrt(cast(x, '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 squareGradConfig = {
kernelName: Square,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(dy, mul(cast(x, '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 squaredDifferenceGradConfig = {
kernelName: SquaredDifference,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const two = scalar(2);
const derA = () => mul(dy, mul(two, sub(a, b)));
const derB = () => mul(dy, mul(two, sub(b, a)));
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const stepGradConfig = {
kernelName: Step,
gradFunc: (dy) => {
// TODO(manrajgrover): Return null for gradients when backprop supports
// it.
return { x: () => zerosLike(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.
* =============================================================================
*/
const subGradConfig = {
kernelName: Sub,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
let res = dy;
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, a.shape);
};
const derB = () => {
let res = dy;
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(neg(res), b.shape);
};
return { a: derA, b: derB };
}
};
/**
* @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 sumGradConfig = {
kernelName: Sum,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const expandedDyShape = x.shape.slice();
const { axis } = attrs;
const axes = parseAxisParam(axis, x.shape);
axes.forEach(axis => {
expandedDyShape[axis] = 1;
});
const expandedDy = reshape(dy, expandedDyShape);
const derX = mul(expandedDy, ones$1(x.shape, 'float32'));
return { x: () => derX };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const tanGradConfig = {
kernelName: Tan,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => div(dy, square(cos(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 tanhGradConfig = {
kernelName: Tanh,
outputsToSave: [true],
gradFunc: (dy, saved) => {
const [y] = saved;
return { x: () => mul(sub(scalar(1), square(y)), 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.
* =============================================================================
*/
const tileGradConfig = {
kernelName: Tile,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { reps } = attrs;
const derX = () => {
let xGrad = zerosLike(x);
// TODO(cais): Maybe reduce memory footprint by avoiding repeated
// slicing.
if (x.rank === 1) {
for (let i = 0; i < reps[0]; ++i) {
xGrad = add$1(xGrad, slice(dy, [i * x.shape[0]], [x.shape[0]]));
}
}
else if (x.rank === 2) {
for (let i = 0; i < reps[0]; ++i) {
for (let j = 0; j < reps[1]; ++j) {
xGrad = add$1(xGrad, slice(dy, [i * x.shape[0], j * x.shape[1]], [
x.shape[0], x.shape[1]
]));
}
}
}
else if (x.rank === 3) {
for (let i = 0; i < reps[0]; ++i) {
for (let j = 0; j < reps[1]; ++j) {
for (let k = 0; k < reps[2]; ++k) {
xGrad =
add$1(xGrad, slice(dy, [i * x.shape[0], j * x.shape[1], k * x.shape[2]], [x.shape[0], x.shape[1], x.shape[2]]));
}
}
}
}
else if (x.rank === 4) {
for (let i = 0; i < reps[0]; ++i) {
for (let j = 0; j < reps[1]; ++j) {
for (let k = 0; k < reps[2]; ++k) {
for (let l = 0; l < reps[3]; ++l) {
xGrad =
add$1(xGrad, slice(dy, [
i * x.shape[0], j * x.shape[1], k * x.shape[2],
l * x.shape[3]
], [x.shape[0], x.shape[1], x.shape[2], x.shape[3]]));
}
}
}
}
}
else {
throw new Error(`Gradient for tile operation is not implemented for rank-` +
`${x.rank} tensors yet.`);
}
return xGrad;
};
return { x: derX };
},
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const transposeGradConfig = {
kernelName: Transpose,
gradFunc: (dy, saved, attrs) => {
const transposeAttrs = attrs;
const { perm } = transposeAttrs;
const undoPerm = getUndoAxesPermutation(perm);
return { x: () => transpose(dy, undoPerm) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Stacks a list of rank-`R` `tf.Tensor`s into one rank-`(R+1)` `tf.Tensor`.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* const c = tf.tensor1d([5, 6]);
* tf.stack([a, b, c]).print();
* ```
*
* @param tensors A list of tensor objects with the same shape and dtype.
* @param axis The axis to stack along. Defaults to 0 (the first dim).
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function stack_(tensors, axis = 0) {
const $tensors = convertToTensorArray(tensors, 'tensors', 'stack', 'string_or_numeric');
assert($tensors.length >= 1, () => 'Pass at least one tensor to tf.stack');
if ($tensors.length > 0) {
assert(axis <= $tensors[0].rank, () => 'Axis must be <= rank of the tensor');
}
const inputs = $tensors;
const attrs = { axis };
return ENGINE.runKernel(Pack, inputs, attrs);
}
const stack = op({ stack_ });
/**
* @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 unpackGradConfig = {
kernelName: Unpack,
gradFunc: (dy, saved, attrs) => {
const unpackAttrs = attrs;
const { axis } = unpackAttrs;
return { value: () => stack(dy, axis) };
}
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns a `tf.Tensor` that has expanded rank, by inserting a dimension
* into the tensor's shape.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* const axis = 1;
* x.expandDims(axis).print();
* ```
*
* @param x The input tensor whose dimensions to be expanded.
* @param axis The dimension index at which to insert shape of `1`. Defaults
* to 0 (the first dimension).
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function expandDims_(x, axis = 0) {
const $x = convertToTensor(x, 'x', 'expandDims', 'string_or_numeric');
assert(axis <= $x.rank, () => 'Axis must be <= rank of the tensor');
const inputs = { input: $x };
const attrs = { dim: axis };
return ENGINE.runKernel(ExpandDims, inputs, attrs);
}
const expandDims = op({ expandDims_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Gather slices from tensor `x`'s axis `axis` according to `indices`.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* const indices = tf.tensor1d([1, 3, 3], 'int32');
*
* x.gather(indices).print();
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
* const indices = tf.tensor1d([1, 1, 0], 'int32');
*
* x.gather(indices).print();
* ```
* @param x The input tensor whose slices to be gathered.
* @param indices The indices of the values to extract.
* @param axis The axis over which to select values. Defaults to 0.
* @param batchDims Optional. The number of batch dimensions. It must be less
* than or equal to rank(indices). Defaults to 0.
* The output tensor will have shape of
* `x.shape[:axis] + indices.shape[batchDims:] + x.shape[axis + 1:]`
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function gather_(x, indices, axis = 0, batchDims = 0) {
const $x = convertToTensor(x, 'x', 'gather');
const $indices = convertToTensor(indices, 'indices', 'gather', 'int32');
const inputs = { x: $x, indices: $indices };
const attrs = { axis, batchDims };
return ENGINE.runKernel(GatherV2, inputs, attrs);
}
const gather = op({ gather_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the max of a and b (`a > b ? a : b`) element-wise.
* Supports broadcasting.
*
* We also expose `tf.maximumStrict` which has the same signature as this op and
* asserts that `a` and `b` are the same shape (does not broadcast).
*
* ```js
* const a = tf.tensor1d([1, 4, 3, 16]);
* const b = tf.tensor1d([1, 2, 9, 4]);
*
* a.maximum(b).print(); // or tf.maximum(a, b)
* ```
*
* ```js
* // Broadcast maximum a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(5);
*
* a.maximum(b).print(); // or tf.maximum(a, b)
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function maximum_(a, b) {
let $a = convertToTensor(a, 'a', 'maximum');
let $b = convertToTensor(b, 'b', 'maximum');
[$a, $b] = makeTypesMatch($a, $b);
if ($a.dtype === 'bool') {
$a = cast($a, 'int32');
$b = cast($b, 'int32');
}
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Maximum, inputs);
}
const maximum = op({ maximum_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const unsortedSegmentSumGradConfig = {
kernelName: UnsortedSegmentSum,
inputsToSave: ['segmentIds'],
gradFunc: (dy, saved) => {
const [segmentIds] = saved;
const derX = () => {
return gatherDropNegatives(dy, segmentIds);
};
return { x: derX };
}
};
function gatherDropNegatives(x, indices) {
// Helper function for unsorted segment ops. Gathers params for
// positive segment ids and gathers 0 for inputs with negative segment id.
// Mirrors _GatherDropNegatives from tensorflow/python/ops/math_grad.py
const zeroClippedIndices = maximum(indices, zerosLike(indices));
const gathered = gather(x, zeroClippedIndices);
let isPositive = greaterEqual(indices, scalar(0, 'int32'));
const numIters = gathered.rank - isPositive.rank;
for (let i = 0; i < numIters; ++i) {
isPositive = expandDims(isPositive, i + 1);
}
isPositive = logicalAnd(isPositive, ones$1(gathered.shape, 'bool'));
const zeroSlice = zerosLike(gathered);
return where(isPositive, gathered, zeroSlice);
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const zerosLikeGradConfig = {
kernelName: ZerosLike,
gradFunc: (dy) => {
return { x: () => zerosLike(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.
* =============================================================================
*/
// Export all kernel configs here so that the package can auto register them
const gradConfigs = [
absGradConfig,
acosGradConfig,
acoshGradConfig,
addGradConfig,
addNGradConfig,
argMaxGradConfig,
argMinGradConfig,
asinGradConfig,
asinhGradConfig,
atan2GradConfig,
atanGradConfig,
atanhGradConfig,
avgPool3DGradConfig,
avgPoolGradConfig,
batchMatMulGradConfig,
batchToSpaceNDGradConfig,
broadcastToGradConfig,
castGradConfig,
ceilGradConfig,
clipByValueGradConfig,
complexAbsGradConfig,
concatGradConfig,
conv2DBackpropInputGradConfig,
conv2DGradConfig,
conv3DGradConfig,
cosGradConfig,
coshGradConfig,
cumsumGradConfig,
depthwiseConv2dNativeGradConfig,
dilation2dGradConfig,
divGradConfig,
eluGradConfig,
erfGradConfig,
expGradConfig,
expandDimsGradConfig,
expm1GradConfig,
floorDivGradConfig,
floorGradConfig,
fusedBatchNormGradConfig,
gatherGradConfig,
greaterEqualGradConfig,
identityGradConfig,
isFiniteGradConfig,
isInfGradConfig,
isNanGradConfig,
leakyReluGradConfig,
log1pGradConfig,
logGradConfig,
logSoftmaxGradConfig,
lrnGradConfig,
maxGradConfig,
maxGradConfig,
maximumGradConfig,
maxPool3DGradConfig,
maxPoolGradConfig,
meanGradConfig,
minGradConfig,
minimumGradConfig,
mirrorPadGradConfig,
modGradConfig,
multiplyGradConfig,
negGradConfig,
oneHotGradConfig,
onesLikeGradConfig,
packGradConfig,
padV2GradConfig,
padV2GradConfig,
powGradConfig,
preluGradConfig,
reciprocalGradConfig,
relu6GradConfig,
reluGradConfig,
reshapeGradConfig,
resizeBilinearGradConfig,
resizeNearestNeighborGradConfig,
reverseGradConfig,
roundGradConfig,
rsqrtGradConfig,
selectGradConfig,
seluGradConfig,
sigmoidGradConfig,
signGradConfig,
sinGradConfig,
sinhGradConfig,
sliceGradConfig,
softmaxGradConfig,
softplusGradConfig,
spaceToBatchNDGradConfig,
spaceToBatchNDGradConfig,
splitVGradConfig,
splitVGradConfig,
sqrtGradConfig,
squaredDifferenceGradConfig,
squareGradConfig,
stepGradConfig,
subGradConfig,
sumGradConfig,
tanGradConfig,
tanhGradConfig,
tileGradConfig,
transposeGradConfig,
unpackGradConfig,
unsortedSegmentSumGradConfig,
zerosLikeGradConfig
];
for (const gradientConfig of gradConfigs) {
registerGradient(gradientConfig);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes absolute value element-wise: `abs(x)`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.abs().print(); // or tf.abs(x)
* ```
* @param x The input `tf.Tensor`.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function abs_(x) {
const $x = convertToTensor(x, 'x', 'abs');
if ($x.dtype === 'complex64') {
const inputs = { x: $x };
return ENGINE.runKernel(ComplexAbs, inputs);
}
else {
const inputs = { x: $x };
return ENGINE.runKernel(Abs, inputs);
}
}
const abs = op({ abs_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes acos of the input `tf.Tensor` element-wise: `acos(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.acos().print(); // or tf.acos(x)
* ```
* @param x The input tensor.
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function acos_(x) {
const $x = convertToTensor(x, 'x', 'acos');
const inputs = { x: $x };
return ENGINE.runKernel(Acos, inputs);
}
const acos = op({ acos_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the inverse hyperbolic cos of the input `tf.Tensor` element-wise:
* `acosh(x)`
*
* ```js
* const x = tf.tensor1d([10, 1, 3, 5.7]);
*
* x.acosh().print(); // or tf.acosh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function acosh_(x) {
const $x = convertToTensor(x, 'x', 'acosh');
const inputs = { x: $x };
return ENGINE.runKernel(Acosh, inputs);
}
const acosh = op({ acosh_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Adds a list of `tf.Tensor`s element-wise, each with the same shape and dtype.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* const c = tf.tensor1d([5, 6]);
*
* tf.addN([a, b, c]).print();
* ```
* @param tensors A list of tensors with the same shape and dtype.
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function addN_(tensors) {
assert(Array.isArray(tensors), () => 'The argument passed to tf.addN() must be a list of tensors');
assert(tensors.length >= 1, () => `Must pass at least one tensor to tf.addN(), but got ` +
`${tensors.length}`);
const $tensors = tensors.map((t, i) => convertToTensor(t, `tensors${i}`, 'addN'));
const firstTensor = $tensors[0];
$tensors.forEach(t => {
if (t.dtype !== firstTensor.dtype) {
throw new Error('All tensors passed to tf.addN() must have the same dtype');
}
});
$tensors.forEach(t => {
if (!arraysEqual(t.shape, firstTensor.shape)) {
throw new Error('All tensors passed to tf.addN() must have the same shape');
}
});
const inputs = $tensors;
return ENGINE.runKernel(AddN, inputs);
}
const addN = op({ addN_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the logical and of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and an
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 1, 1], 'bool');
*
* x.all().print(); // or tf.all(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');
*
* const axis = 1;
* x.all(axis).print(); // or tf.all(x, axis)
* ```
*
* @param x The input tensor. Must be of dtype bool.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function all_(x, axis = null, keepDims = false) {
const $x = convertToTensor(x, 'x', 'all', 'bool');
const inputs = { x: $x };
const attrs = { axis, keepDims };
return ENGINE.runKernel(All, inputs, attrs);
}
const all = op({ all_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the logical or of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and an
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 1, 1], 'bool');
*
* x.any().print(); // or tf.any(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');
*
* const axis = 1;
* x.any(axis).print(); // or tf.any(x, axis)
* ```
*
* @param x The input tensor. Must be of dtype bool.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function any_(x, axis = null, keepDims = false) {
const $x = convertToTensor(x, 'x', 'any', 'bool');
const inputs = { x: $x };
const attrs = { axis, keepDims };
return ENGINE.runKernel(Any, inputs, attrs);
}
// tslint:disable-next-line:variable-name
const any = op({ any_ });
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the indices of the maximum values along an `axis`.
*
* The result has the same shape as `input` with the dimension along `axis`
* removed.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.argMax().print(); // or tf.argMax(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 4, 3], [2, 2]);
*
* const axis = 1;
* x.argMax(axis).print(); // or tf.argMax(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension to reduce. Defaults to 0 (outer-most dimension).
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function argMax_(x, axis = 0) {
const $x = convertToTensor(x, 'x', 'argMax');
const inputs = { x: $x };
const attrs = { axis };
return ENGINE.runKernel(ArgMax, inputs, attrs);
}
const argMax = op({ argMax_ });
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the indices of the minimum values along an `axis`.
*
* The result has the same shape as `input` with the dimension along `axis`
* removed.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.argMin().print(); // or tf.argMin(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 4, 3], [2, 2]);
*
* const axis = 1;
* x.argMin(axis).print(); // or tf.argMin(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension to reduce. Defaults to 0 (outer-most dimension).
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function argMin_(x, axis = 0) {
const $x = convertToTensor(x, 'x', 'argMin');
const inputs = { x: $x };
const attrs = { axis };
return ENGINE.runKernel(ArgMin, inputs, attrs);
}
const argMin = op({ argMin_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes asin of the input `tf.Tensor` element-wise: `asin(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.asin().print(); // or tf.asin(x)
* ```
* @param x The input tensor.
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function asin_(x) {
const $x = convertToTensor(x, 'x', 'asin');
const inputs = { x: $x };
return ENGINE.runKernel(Asin, inputs);
}
const asin = op({ asin_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes inverse hyperbolic sin of the input `tf.Tensor` element-wise:
* `asinh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.asinh().print(); // or tf.asinh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function asinh_(x) {
const $x = convertToTensor(x, 'x', 'asinh');
const inputs = { x: $x };
return ENGINE.runKernel(Asinh, inputs);
}
const asinh = op({ asinh_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes atan of the input `tf.Tensor` element-wise: `atan(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.atan().print(); // or tf.atan(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function atan_(x) {
const $x = convertToTensor(x, 'x', 'atan');
const inputs = { x: $x };
return ENGINE.runKernel(Atan, inputs);
}
const atan = op({ atan_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes arctangent of `tf.Tensor`s a / b element-wise: `atan2(a, b)`.
* Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1.0, 1.0, -1.0, .7]);
* const b = tf.tensor1d([2.0, 13.0, 3.5, .21]);
*
* tf.atan2(a, b).print()
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function atan2_(a, b) {
let $a = convertToTensor(a, 'a', 'atan2');
let $b = convertToTensor(b, 'b', 'atan2');
[$a, $b] = makeTypesMatch($a, $b);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Atan2, inputs);
}
const atan2 = op({ atan2_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes inverse hyperbolic tan of the input `tf.Tensor` element-wise:
* `atanh(x)`
*
* ```js
* const x = tf.tensor1d([0, .1, -.1, .7]);
*
* x.atanh().print(); // or tf.atanh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function atanh_(x) {
const $x = convertToTensor(x, 'x', 'atanh');
const inputs = { x: $x };
return ENGINE.runKernel(Atanh, inputs);
}
const atanh = op({ atanh_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the 2D average pooling of an image.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad The type of padding algorithm:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function avgPool_(x, filterSize, strides, pad, dimRoundingMode) {
const $x = convertToTensor(x, 'x', 'avgPool', 'float32');
const dilations = 1;
assert(eitherStridesOrDilationsAreOne(strides, dilations), () => 'Error in avgPool: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
assert(x4D.rank === 4, () => `Error in avgPool: x must be rank 4 but got rank ${x4D.rank}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in avgPool: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x4D };
const attrs = { filterSize, strides, pad, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
let res = ENGINE.runKernel(AvgPool, inputs, attrs);
res = cast(res, $x.dtype);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const avgPool = op({ avgPool_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the 3D average pooling.
*
* ```js
* const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);
* const result = tf.avgPool3d(x, 2, 1, 'valid');
* result.print();
* ```
*
* @param x The input tensor, of rank 5 or rank 4 of shape
* `[batch, depth, height, width, inChannels]`.
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* If `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideDepth == strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
* @param dataFormat An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function avgPool3d_(x, filterSize, strides, pad, dimRoundingMode, dataFormat = 'NDHWC') {
const $x = convertToTensor(x, 'x', 'avgPool3d', 'float32');
let x5D = $x;
let reshapedTo5D = false;
if ($x.rank === 4) {
reshapedTo5D = true;
x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
}
assert(x5D.rank === 5, () => `Error in avgPool3d: x must be rank 5 but got rank ${x5D.rank}.`);
assert(dataFormat === 'NDHWC', () => `Error in avgPool3d: Only NDHWC is currently supported, ` +
`but got dataFormat of ${dataFormat}`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in avgPool3d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x5D };
const attrs = { filterSize, strides, pad, dimRoundingMode, dataFormat };
// tslint:disable-next-line: no-unnecessary-type-assertion
let res = ENGINE.runKernel(AvgPool3D, inputs, attrs);
res = cast(res, x5D.dtype);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const avgPool3d = op({ avgPool3d_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes hyperbolic tangent of the input `tf.Tensor` element-wise: `tanh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, 70]);
*
* x.tanh().print(); // or tf.tanh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function tanh_(x) {
const $x = convertToTensor(x, 'x', 'tanh');
const inputs = { x: $x };
return ENGINE.runKernel(Tanh, inputs);
}
const tanh$1 = op({ tanh_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the next state and output of a BasicLSTMCell.
*
* Returns `[newC, newH]`.
*
* Derived from tf.contrib.rnn.BasicLSTMCell.
*
* @param forgetBias Forget bias for the cell.
* @param lstmKernel The weights for the cell.
* @param lstmBias The bias for the cell.
* @param data The input to the cell.
* @param c Previous cell state.
* @param h Previous cell output.
*
* @doc {heading: 'Operations', subheading: 'RNN'}
*/
function basicLSTMCell_(forgetBias, lstmKernel, lstmBias, data, c, h) {
const $forgetBias = convertToTensor(forgetBias, 'forgetBias', 'basicLSTMCell');
const $lstmKernel = convertToTensor(lstmKernel, 'lstmKernel', 'basicLSTMCell');
const $lstmBias = convertToTensor(lstmBias, 'lstmBias', 'basicLSTMCell');
const $data = convertToTensor(data, 'data', 'basicLSTMCell');
const $c = convertToTensor(c, 'c', 'basicLSTMCell');
const $h = convertToTensor(h, 'h', 'basicLSTMCell');
const combined = concat([$data, $h], 1);
const weighted = matMul(combined, $lstmKernel);
const res = add$1(weighted, $lstmBias);
// i = input_gate, j = new_input, f = forget_gate, o = output_gate
const batchSize = res.shape[0];
const sliceCols = res.shape[1] / 4;
const sliceSize = [batchSize, sliceCols];
const i = slice(res, [0, 0], sliceSize);
const j = slice(res, [0, sliceCols], sliceSize);
const f = slice(res, [0, sliceCols * 2], sliceSize);
const o = slice(res, [0, sliceCols * 3], sliceSize);
const newC = add$1(mul(sigmoid(i), tanh$1(j)), mul($c, sigmoid(add$1($forgetBias, f))));
const newH = mul(tanh$1(newC), sigmoid(o));
return [newC, newH];
}
const basicLSTMCell = op({ basicLSTMCell_ });
function xAs4D(x) {
let x4D;
if (x.rank === 0 || x.rank === 1) {
x4D = reshape(x, [1, 1, 1, x.size]);
}
else if (x.rank === 2) {
x4D = reshape(x, [1, 1, x.shape[0], x.shape[1]]);
}
else if (x.rank === 3) {
x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
}
else {
x4D = x;
}
return x4D;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Batch normalization.
*
* As described in
* [http://arxiv.org/abs/1502.03167](http://arxiv.org/abs/1502.03167).
*
* Mean, variance, scale, and offset can be of two shapes:
* - The same shape as the input.
* - In the common case, the depth dimension is the last dimension of x, so
* the values would be an `tf.Tensor1D` of shape [depth].
*
* Also available are stricter rank-specific methods with the same signature
* as this method that assert that parameters passed are of given rank
* - `tf.batchNorm2d`
* - `tf.batchNorm3d`
* - `tf.batchNorm4d`
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function batchNorm_(x, mean, variance, offset, scale, varianceEpsilon) {
if (varianceEpsilon == null) {
varianceEpsilon = 0.001;
}
const $x = convertToTensor(x, 'x', 'batchNorm');
const $mean = convertToTensor(mean, 'mean', 'batchNorm');
const $variance = convertToTensor(variance, 'variance', 'batchNorm');
let $scale;
if (scale != null) {
$scale = convertToTensor(scale, 'scale', 'batchNorm');
}
let $offset;
if (offset != null) {
$offset = convertToTensor(offset, 'offset', 'batchNorm');
}
assert($mean.rank === $variance.rank, () => 'Batch normalization gradient requires mean and variance to have ' +
'equal ranks.');
assert($offset == null || $mean.rank === $offset.rank, () => 'Batch normalization gradient requires mean and offset to have ' +
'equal ranks.');
assert($scale == null || $mean.rank === $scale.rank, () => 'Batch normalization gradient requires mean and scale to have ' +
'equal ranks.');
const x4D = xAs4D($x);
const inputs = {
x: x4D,
scale: $scale,
offset: $offset,
mean: $mean,
variance: $variance
};
const attrs = { varianceEpsilon };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(FusedBatchNorm, inputs, attrs);
return reshape(res, $x.shape);
}
const batchNorm = op({ batchNorm_ });
/**
* Batch normalization, strictly for 2D. For the more relaxed version, see
* `tf.batchNorm`.
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*/
function batchNorm2d_(x, mean, variance, offset, scale, varianceEpsilon) {
const $x = convertToTensor(x, 'x', 'batchNorm');
const $mean = convertToTensor(mean, 'mean', 'batchNorm');
const $variance = convertToTensor(variance, 'variance', 'batchNorm');
let $scale;
if (scale != null) {
$scale = convertToTensor(scale, 'scale', 'batchNorm');
}
let $offset;
if (offset != null) {
$offset = convertToTensor(offset, 'offset', 'batchNorm');
}
assert($x.rank === 2, () => `Error in batchNorm2D: x must be rank 2 but got rank ` +
`${$x.rank}.`);
assert($mean.rank === 2 || $mean.rank === 1, () => `Error in batchNorm2D: mean must be rank 2 or rank 1 but ` +
`got rank ${$mean.rank}.`);
assert($variance.rank === 2 || $variance.rank === 1, () => `Error in batchNorm2D: variance must be rank 2 or rank 1 ` +
`but got rank ${$variance.rank}.`);
if ($scale != null) {
assert($scale.rank === 2 || $scale.rank === 1, () => `Error in batchNorm2D: scale must be rank 2 or rank 1 ` +
`but got rank ${$scale.rank}.`);
}
if ($offset != null) {
assert($offset.rank === 2 || $offset.rank === 1, () => `Error in batchNorm2D: offset must be rank 2 or rank 1 ` +
`but got rank ${$offset.rank}.`);
}
return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);
}
const batchNorm2d = op({ batchNorm2d_ });
/**
* Batch normalization, strictly for 3D. For the more relaxed version, see
* `tf.batchNorm`.
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*/
function batchNorm3d_(x, mean, variance, offset, scale, varianceEpsilon) {
const $x = convertToTensor(x, 'x', 'batchNorm');
const $mean = convertToTensor(mean, 'mean', 'batchNorm');
const $variance = convertToTensor(variance, 'variance', 'batchNorm');
let $scale;
if (scale != null) {
$scale = convertToTensor(scale, 'scale', 'batchNorm');
}
let $offset;
if (offset != null) {
$offset = convertToTensor(offset, 'offset', 'batchNorm');
}
assert($x.rank === 3, () => `Error in batchNorm3D: x must be rank 3 but got rank ` +
`${$x.rank}.`);
assert($mean.rank === 3 || $mean.rank === 1, () => `Error in batchNorm3D: mean must be rank 3 or rank 1 but ` +
`got rank ${$mean.rank}.`);
assert($variance.rank === 3 || $variance.rank === 1, () => `Error in batchNorm3D: variance must be rank 3 or rank 1 ` +
`but got rank ${$variance.rank}.`);
if ($scale != null) {
assert($scale.rank === 3 || $scale.rank === 1, () => `Error in batchNorm3D: scale must be rank 3 or rank 1 ` +
`but got rank ${$scale.rank}.`);
}
if ($offset != null) {
assert($offset.rank === 3 || $offset.rank === 1, () => `Error in batchNorm3D: offset must be rank 3 or rank 1 ` +
`but got rank ${$offset.rank}.`);
}
return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);
}
const batchNorm3d = op({ batchNorm3d_ });
/**
* Batch normalization, strictly for 4D. For the more relaxed version, see
* `tf.batchNorm`.
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*/
function batchNorm4d_(x, mean, variance, offset, scale, varianceEpsilon) {
const $x = convertToTensor(x, 'x', 'batchNorm');
const $mean = convertToTensor(mean, 'mean', 'batchNorm');
const $variance = convertToTensor(variance, 'variance', 'batchNorm');
let $scale;
if (scale != null) {
$scale = convertToTensor(scale, 'scale', 'batchNorm');
}
let $offset;
if (offset != null) {
$offset = convertToTensor(offset, 'offset', 'batchNorm');
}
assert($x.rank === 4, () => `Error in batchNorm4D: x must be rank 4 but got rank ` +
`${$x.rank}.`);
assert($mean.rank === 4 || $mean.rank === 1, () => `Error in batchNorm4D: mean must be rank 4 or rank 1 but ` +
`got rank ${$mean.rank}.`);
assert($variance.rank === 4 || $variance.rank === 1, () => `Error in batchNorm4D: variance must be rank 4 or rank 1 ` +
`but got rank ${$variance.rank}.`);
if ($scale != null) {
assert($scale.rank === 4 || $scale.rank === 1, () => `Error in batchNorm4D: scale must be rank 4 or rank 1 ` +
`but got rank ${$scale.rank}.`);
}
if ($offset != null) {
assert($offset.rank === 4 || $offset.rank === 1, () => `Error in batchNorm4D: offset must be rank 4 or rank 1 ` +
`but got rank ${$offset.rank}.`);
}
return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);
}
const batchNorm4d = op({ batchNorm4d_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Outputs a vector with length `size` and the same dtype as `weights`.
*
* If `weights` are empty, then index `i` stores the number of times the value
* `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the
* sum of the value in `weights` at each index where the corresponding value in
* `x` is `i`.
*
* Values in `x` outside of the range [0, size) are ignored.
*
* @param x The input int tensor, rank 1.
* @param weights The weights tensor, must have the same shape as x, or a
* length-0 Tensor, in which case it acts as all weights equal to 1.
* @param size Non-negative integer.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function bincount_(x, weights, size) {
const $x = convertToTensor(x, 'x', 'bincount');
const $weights = convertToTensor(weights, 'weights', 'bincount');
assert($x.dtype === 'int32', () => `Error in bincount: input ` +
`dtype must be int32, but got ${$x.dtype}`);
assert(size >= 0, () => `size must be non-negative, but got ${size}.`);
assert($weights.size === $x.size || $weights.size === 0, () => `Error in bincount: weights must have the same size as input or` +
`0-length, but got input shape: ${$x.shape}, weights shape: ` +
`${$weights.shape}.`);
const inputs = { x: $x, weights: $weights };
const attrs = { size };
return ENGINE.runKernel(Bincount, inputs, attrs);
}
const bincount = op({ bincount_ });
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates an empty `tf.TensorBuffer` with the specified `shape` and `dtype`.
*
* The values are stored in CPU as `TypedArray`. Fill the buffer using
* `buffer.set()`, or by modifying directly `buffer.values`.
*
* When done, call `buffer.toTensor()` to get an immutable `tf.Tensor` with
* those values.
*
* ```js
* // Create a buffer and set values at particular indices.
* const buffer = tf.buffer([2, 2]);
* buffer.set(3, 0, 0);
* buffer.set(5, 1, 0);
*
* // Convert the buffer back to a tensor.
* buffer.toTensor().print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param dtype The dtype of the buffer. Defaults to 'float32'.
* @param values The values of the buffer as `TypedArray`. Defaults to
* zeros.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function buffer(shape, dtype = 'float32', values) {
dtype = dtype || 'float32';
assertNonNegativeIntegerDimensions(shape);
return new TensorBuffer(shape, dtype, values);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes ceiling of input `tf.Tensor` element-wise: `ceil(x)`
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3]);
*
* x.ceil().print(); // or tf.ceil(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function ceil_(x) {
const $x = convertToTensor(x, 'x', 'ceil');
const inputs = { x: $x };
return ENGINE.runKernel(Ceil, inputs);
}
const ceil = op({ ceil_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Clips values element-wise. `max(min(x, clipValueMax), clipValueMin)`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.clipByValue(-2, 3).print(); // or tf.clipByValue(x, -2, 3)
* ```
* @param x The input tensor.
* @param clipValueMin Lower-bound of range to be clipped to.
* @param clipValueMax Upper-bound of range to be clipped to.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function clipByValue_(x, clipValueMin, clipValueMax) {
const $x = convertToTensor(x, 'x', 'clipByValue');
assert((clipValueMin <= clipValueMax), () => `Error in clip: min (${clipValueMin}) must be ` +
`less than or equal to max (${clipValueMax}).`);
const inputs = { x: $x };
const attrs = { clipValueMin, clipValueMax };
return ENGINE.runKernel(ClipByValue, inputs, attrs);
}
const clipByValue = op({ clipByValue_ });
/**
* Concatenates a list of`tf.Tensor1D`s along an axis. See `concat` for details.
*
* For example, if:
* A: shape(3) = |r1, g1, b1|
* B: shape(2) = |r2, g2|
* C = tf.concat1d([A, B]) == |r1, g1, b1, r2, g2|
*
* @param tensors A list of`tf.Tensor`s to concatenate.
* @return The concatenated array.
*/
function concat1d_(tensors) {
return concat(tensors, 0 /* axis */);
}
const concat1d = op({ concat1d_ });
/**
* Concatenates a list of`tf.Tensor2D`s along an axis. See `concat` for details.
*
* For example, if:
* A: shape(2, 3) = | r1, g1, b1 |
* | r2, g2, b2 |
*
* B: shape(2, 3) = | r3, g3, b3 |
* | r4, g4, b4 |
*
* C = tf.concat2d([A, B], axis)
*
* if axis = 0:
* C: shape(4, 3) = | r1, g1, b1 |
* | r2, g2, b2 |
* | r3, g3, b3 |
* | r4, g4, b4 |
*
* if axis = 1:
* C = shape(2, 6) = | r1, g1, b1, r3, g3, b3 |
* | r2, g2, b2, r4, g4, b4 |
*
*
* @param tensors A list of `tf.Tensor`s to concatenate.
* @param axis The axis to concatenate along.
* @return The concatenated array.
*/
function concat2d_(tensors, axis) {
return concat(tensors, axis);
}
const concat2d = op({ concat2d_ });
/**
* Concatenates a list of `tf.Tensor3D`s along an axis.
* See `concat` for details.
*
* For example, if:
* A: shape(2, 1, 3) = | r1, g1, b1 |
* | r2, g2, b2 |
*
* B: shape(2, 1, 3) = | r3, g3, b3 |
* | r4, g4, b4 |
*
* C = tf.concat3d([A, B], axis)
*
* if axis = 0:
* C: shape(4, 1, 3) = | r1, g1, b1 |
* | r2, g2, b2 |
* | r3, g3, b3 |
* | r4, g4, b4 |
*
* if axis = 1:
* C: shape(2, 2, 3) = | r1, g1, b1, r3, g3, b3 |
* | r2, g2, b2, r4, g4, b4 |
*
* if axis = 2:
* C = shape(2, 1, 6) = | r1, g1, b1, r3, g3, b3 |
* | r2, g2, b2, r4, g4, b4 |
*
* @param tensors A list of`tf.Tensor`s to concatenate.
* @param axis The axis to concate along.
* @return The concatenated array.
*/
function concat3d_(tensors, axis) {
return concat(tensors, axis);
}
const concat3d = op({ concat3d_ });
/**
* Concatenates a list of `tf.Tensor4D`s along an axis.
* See `concat` for details.
*
* @param tensors A list of `tf.Tensor`s to concatenate.
* @param axis The axis to concate along.
* @return The concatenated array.
*/
function concat4d_(tensors, axis) {
return concat(tensors, axis);
}
const concat4d = op({ concat4d_ });
/**
* Computes a 1D convolution over the input x.
*
* @param x The input tensor, of rank 3 or rank 2, of shape
* `[batch, width, inChannels]`. If rank 2, batch of 1 is assumed.
* @param filter The filter, rank 3, of shape
* `[filterWidth, inDepth, outDepth]`.
* @param stride The number of entries by which the filter is moved right at
* each step.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dataFormat An optional string from "NWC", "NCW". Defaults to "NWC",
* the data is stored in the order of [batch, in_width, in_channels]. Only
* "NWC" is currently supported.
* @param dilation The dilation rate in which we sample input values in
* atrous convolution. Defaults to `1`. If it is greater than 1, then
* stride must be `1`.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function conv1d_(x, filter, stride, pad, dataFormat = 'NWC', dilation = 1, dimRoundingMode) {
const $x = convertToTensor(x, 'x', 'conv1d');
const $filter = convertToTensor(filter, 'filter', 'conv1d');
let x3D = $x;
let reshapedTo3D = false;
if ($x.rank === 2) {
reshapedTo3D = true;
x3D = reshape($x, [1, $x.shape[0], $x.shape[1]]);
}
assert(x3D.rank === 3, () => `Error in conv1d: input must be rank 3, but got rank ${x3D.rank}.`);
assert($filter.rank === 3, () => `Error in conv1d: filter must be rank 3, but got rank ` +
`${$filter.rank}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in conv1d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
assert(x3D.shape[2] === $filter.shape[1], () => `Error in conv1d: depth of input (${x3D.shape[2]}) must match ` +
`input depth for filter ${$filter.shape[1]}.`);
assert(eitherStridesOrDilationsAreOne(stride, dilation), () => 'Error in conv1D: Either stride or dilation must be 1. ' +
`Got stride ${stride} and dilation '${dilation}'`);
assert(dataFormat === 'NWC', () => `Error in conv1d: got dataFormat of ${dataFormat} but only NWC is currently supported.`);
const filter4D = reshape($filter, [1, $filter.shape[0], $filter.shape[1], $filter.shape[2]]);
const input4D = reshape(x3D, [x3D.shape[0], 1, x3D.shape[1], x3D.shape[2]]);
const strides = [1, stride];
const dilations = [1, dilation];
const conv2dDataFormat = 'NHWC';
const res = conv2d(input4D, filter4D, strides, pad, conv2dDataFormat, dilations, dimRoundingMode);
if (reshapedTo3D) {
return reshape(res, [res.shape[2], res.shape[3]]);
}
return reshape(res, [res.shape[0], res.shape[2], res.shape[3]]);
}
const conv1d = op({ conv1d_ });
/**
* Computes the transposed 2D convolution of an image, also known as a
* deconvolution.
*
* @param x The input image, of rank 4 or rank 3, of shape
* `[batch, height, width, inDepth]`. If rank 3, batch of 1 is assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, outDepth, inDepth]`.
* `inDepth` must match `inDepth` in `x`.
* @param outputShape Output shape, of rank 4 or rank 3:
* `[batch, height, width, outDepth]`. If rank 3, batch of 1 is assumed.
* @param strides The strides of the original convolution:
* `[strideHeight, strideWidth]`.
* @param pad The type of padding algorithm used in the non-transpose version
* of the op.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function conv2dTranspose_(x, filter, outputShape, strides, pad, dimRoundingMode) {
const $x = convertToTensor(x, 'x', 'conv2dTranspose');
const $filter = convertToTensor(filter, 'filter', 'conv2dTranspose');
return conv2DBackpropInput(outputShape, $x, $filter, strides, pad, 'NHWC', dimRoundingMode);
}
const conv2dTranspose = op({ conv2dTranspose_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes a 3D convolution over the input x.
*
* @param x The input tensor, of rank 5 or rank 4, of shape
* `[batch, depth, height, width, channels]`. If rank 4,
* batch of 1 is assumed.
* @param filter The filter, rank 5, of shape
* `[filterDepth, filterHeight, filterWidth, inChannels, outChannels]`.
* inChannels must match between input and filter.
* @param strides The strides of the convolution: `[strideDepth, strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dataFormat: An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
* @param dilations The dilation rates: `[dilationDepth, dilationHeight,
* dilationWidth]` in which we sample input values across the height
* and width dimensions in atrous convolution. Defaults to `[1, 1, 1]`.
* If `dilations` is a single number, then
* `dilationDepth == dilationHeight == dilationWidth`. If it is greater
* than 1, then all values of `strides` must be 1.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function conv3d_(x, filter, strides, pad, dataFormat = 'NDHWC', dilations = [1, 1, 1]) {
const $x = convertToTensor(x, 'x', 'conv3d');
const $filter = convertToTensor(filter, 'filter', 'conv3d');
let x5D = $x;
let reshapedTo5D = false;
if ($x.rank === 4) {
reshapedTo5D = true;
x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
}
assert(x5D.rank === 5, () => `Error in conv3d: input must be rank 5, but got rank ${x5D.rank}.`);
assert($filter.rank === 5, () => `Error in conv3d: filter must be rank 5, but got rank ` +
`${$filter.rank}.`);
assert(x5D.shape[4] === $filter.shape[3], () => `Error in conv3d: depth of input (${x5D.shape[4]}) must match ` +
`input depth for filter ${$filter.shape[3]}.`);
assert(eitherStridesOrDilationsAreOne(strides, dilations), () => 'Error in conv3D: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
assert(dataFormat === 'NDHWC', () => `Error in conv3d: got dataFormat of ${dataFormat} but only NDHWC is currently supported.`);
const inputs = { x: x5D, filter: $filter };
const attrs = { strides, pad, dataFormat, dilations };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(Conv3D, inputs, attrs);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const conv3d = op({ conv3d_ });
/**
* Computes the transposed 3D convolution of a volume, also known as a
* deconvolution.
*
* @param x The input image, of rank 5 or rank 4, of shape
* `[batch, depth, height, width, inDepth]`. If rank 4, batch of 1 is assumed.
* @param filter The filter, rank 4, of shape
* `[depth, filterHeight, filterWidth, outDepth, inDepth]`.
* `inDepth` must match `inDepth` in `x`.
* @param outputShape Output shape, of rank 5 or rank 4:
* `[batch, depth, height, width, outDepth]`. If rank 3, batch of 1 is
* assumed.
* @param strides The strides of the original convolution:
* `[strideDepth, strideHeight, strideWidth]`.
* @param pad The type of padding algorithm used in the non-transpose version
* of the op.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function conv3dTranspose_(x, filter, outputShape, strides, pad) {
const $x = convertToTensor(x, 'x', 'conv3dTranspose');
const $filter = convertToTensor(filter, 'filter', 'conv3dTranspose');
return conv3DBackpropInput(outputShape, $x, $filter, strides, pad);
}
const conv3dTranspose = op({ conv3dTranspose_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Outputs a vector with length `size` and the same dtype as `weights`.
*
* If `weights` are empty, then index `i` stores the number of times the value
* `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the
* sum of the value in `weights` at each index where the corresponding value in
* `x` is `i`.
*
* Values in `x` outside of the range [0, size) are ignored.
*
* @param x The input int tensor, rank 1 or rank 2.
* @param weights The weights tensor, must have the same shape as x, or a
* length-0 Tensor, in which case it acts as all weights equal to 1.
* @param size Non-negative integer.
* @param binaryOutput Optional. Whether the kernel should count the appearance
* or number of occurrences. Defaults to False.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function denseBincount_(x, weights, size, binaryOutput = false) {
const $x = convertToTensor(x, 'x', 'denseBincount');
const $weights = convertToTensor(weights, 'weights', 'denseBincount');
assert($x.dtype === 'int32', () => `Error in denseBincount: input ` +
`dtype must be int32, but got ${$x.dtype}`);
assert($x.rank <= 2, () => `Error in denseBincount: input must be at most rank 2, but got ` +
`rank ${$x.rank}.`);
assert(size >= 0, () => `size must be non-negative, but got ${size}.`);
assert($weights.size === $x.size || $weights.size === 0, () => `Error in denseBincount: weights must have the same shape as x or ` +
`0-length, but got x shape: ${$x.shape}, weights shape: ` +
`${$weights.shape}.`);
const inputs = { x: $x, weights: $weights };
const attrs = { size, binaryOutput };
return ENGINE.runKernel(DenseBincount, inputs, attrs);
}
const denseBincount = op({ denseBincount_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Rearranges data from depth into blocks of spatial data. More specifically,
* this op outputs a copy of the input tensor where values from the `depth`
* dimension are moved in spatial blocks to the `height` and `width` dimensions.
* The attr `blockSize` indicates the input block size and how the data is
* moved.
*
* - Chunks of data of size `blockSize * blockSize` from depth are rearranged
* into non-overlapping blocks of size `blockSize x blockSize`
*
* - The width the output tensor is `inputWidth * blockSize`, whereas the
* height is `inputHeight * blockSize`
*
* - The Y, X coordinates within each block of the output image are determined
* by the high order component of the input channel index
*
* - The depth of the input tensor must be divisible by `blockSize *
* blockSize`
*
* The `dataFormat` attr specifies the layout of the input and output tensors
* with the following options: "NHWC": [ `batch, height, width, channels` ]
* "NCHW": [ `batch, channels, height, width` ]
*
* ```js
* const x = tf.tensor4d([1, 2, 3, 4], [1, 1, 1, 4]);
* const blockSize = 2;
* const dataFormat = "NHWC";
*
* tf.depthToSpace(x, blockSize, dataFormat).print();
* ```
*
* @param x The input tensor of rank 4
* @param blockSIze An `int` that is `>= 2`. The size of the spatial block
* @param dataFormat An optional string from: "NHWC", "NCHW". Defaults to "NHWC"
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function depthToSpace_(x, blockSize, dataFormat = 'NHWC') {
const $x = convertToTensor(x, 'x', 'depthToSpace');
const inputHeight = (dataFormat === 'NHWC') ? $x.shape[1] : $x.shape[2];
const inputWidth = (dataFormat === 'NHWC') ? $x.shape[2] : $x.shape[3];
const inputDepth = (dataFormat === 'NHWC') ? $x.shape[3] : $x.shape[1];
assert(inputHeight * blockSize >= 0, () => `Negative dimension size caused by overflow when multiplying
${inputHeight} and ${blockSize} for depthToSpace with input shape
${$x.shape}`);
assert(inputWidth * blockSize >= 0, () => `Negative dimension size caused by overflow when multiplying
${inputWidth} and ${blockSize} for depthToSpace with input shape
${$x.shape}`);
assert((inputDepth % (blockSize * blockSize) === 0), () => `Dimension size must be evenly divisible by ${blockSize * blockSize} but is ${inputDepth} for depthToSpace with input shape ${$x.shape}`);
const inputs = { x: $x };
const attrs = { blockSize, dataFormat };
return ENGINE.runKernel(DepthToSpace, inputs, attrs);
}
const depthToSpace = op({ depthToSpace_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Depthwise 2D convolution.
*
* Given a 4D `input` array and a `filter` array of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]` containing
* `inChannels` convolutional filters of depth 1, this op applies a
* different filter to each input channel (expanding from 1 channel to
* `channelMultiplier` channels for each), then concatenates the results
* together. The output has `inChannels * channelMultiplier` channels.
*
* See
* [https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d](
* https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)
* for more details.
*
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter tensor, rank 4, of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`. If strides is a single number, then `strideHeight ==
* strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels]. Only "NHWC" is currently supported.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function depthwiseConv2d_(x, filter, strides, pad, dataFormat = 'NHWC', dilations = [1, 1], dimRoundingMode) {
const $x = convertToTensor(x, 'x', 'depthwiseConv2d');
const $filter = convertToTensor(filter, 'filter', 'depthwiseConv2d');
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
assert(x4D.rank === 4, () => `Error in depthwiseConv2d: input must be rank 4, but got ` +
`rank ${x4D.rank}.`);
assert($filter.rank === 4, () => `Error in depthwiseConv2d: filter must be rank 4, but got rank ` +
`${$filter.rank}.`);
assert(x4D.shape[3] === $filter.shape[2], () => `Error in depthwiseConv2d: number of input channels ` +
`(${x4D.shape[3]}) must match the inChannels dimension in ` +
`filter ${$filter.shape[2]}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in depthwiseConv2d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x4D, filter: $filter };
const attrs = { strides, pad, dataFormat, dilations, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(DepthwiseConv2dNative, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const depthwiseConv2d = op({ depthwiseConv2d_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns a diagonal tensor with a given diagonal values.
*
* Given a diagonal, this operation returns a tensor with the diagonal and
* everything else padded with zeros.
*
* Assume the input has dimensions `[D1,..., Dk]`, then the output is a tensor
* of rank 2k with dimensions `[D1,..., Dk, D1,..., Dk]`
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
*
* tf.diag(x).print()
* ```
* ```js
* const x = tf.tensor1d([1, 2, 3, 4, 5, 6, 6, 8], [4, 2])
*
* tf.diag(x).print()
* ```
* @param x The input tensor.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function diag_(x) {
const $x = convertToTensor(x, 'x', 'diag');
const inputs = { x: $x };
return ENGINE.runKernel(Diag, inputs);
}
const diag = op({ diag_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the grayscale dilation over the input `x`.
*
* @param x The input tensor, rank 3 or rank 4 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filter The filter tensor, rank 3, of shape
* `[filterHeight, filterWidth, depth]`.
* @param strides The strides of the sliding window for each dimension of the
* input tensor: `[strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dataFormat Specify the data format of the input and output data.
* Defaults to 'NHWC'. Only 'NHWC' is currently supported. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* for atrous morphological dilation. Defaults to `[1, 1]`. If `dilations`
* is a single number, then `dilationHeight == dilationWidth`. If it is
* greater than 1, then all values of `strides` must be 1.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function dilation2d_(x, filter, strides, pad, dilations = [1, 1], dataFormat = 'NHWC') {
const $x = convertToTensor(x, 'x', 'dilation2d');
const $filter = convertToTensor(filter, 'filter', 'dilation2d');
assert($x.rank === 3 || $x.rank === 4, () => `Error in dilation2d: input must be rank 3 or 4, but got rank ` +
`${$x.rank}.`);
assert($filter.rank === 3, () => `Error in dilation2d: filter must be rank 3, but got rank ` +
`${$filter.rank}.`);
assert(dataFormat === 'NHWC', () => `Error in dilation2d: Only NHWC is currently supported, ` +
`but got dataFormat of ${dataFormat}`);
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
reshapedTo4D = true;
}
const inputs = { x: x4D, filter: $filter };
const attrs = { strides, pad, dilations };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(Dilation2D, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const dilation2d = op({ dilation2d_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting. Return 0
* if denominator is 0.
*
*
* ```js
* const a = tf.tensor1d([1, 4, 9, 16]);
* const b = tf.tensor1d([1, 2, 3, 4]);
* const c = tf.tensor1d([0, 0, 0, 0]);
*
* a.divNoNan(b).print(); // or tf.divNoNan(a, b)
* a.divNoNan(c).print(); // or tf.divNoNan(a, c)
* ```
*
* ```js
* // Broadcast div a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(2);
* const c = tf.scalar(0);
*
* a.divNoNan(b).print(); // or tf.divNoNan(a, b)
* a.divNoNan(c).print(); // or tf.divNoNan(a, c)
* ```
*
* @param a The first tensor as the numerator.
* @param b The second tensor as the denominator. Must have the same dtype as
* `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function divNoNan_(a, b) {
// TODO: Make this into its own kernel.
let $a = convertToTensor(a, 'a', 'div');
let $b = convertToTensor(b, 'b', 'div');
[$a, $b] = makeTypesMatch($a, $b);
const divResult = div($a, $b);
const zeros = zerosLike(divResult);
const bEqualsZero = equal($b, zeros);
return where(bEqualsZero, zeros, divResult);
}
const divNoNan = op({ divNoNan_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the dot product of two matrices and/or vectors, `t1` and `t2`.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor2d([[1, 2], [3, 4]]);
* const c = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);
*
* a.dot(b).print(); // or tf.dot(a, b)
* b.dot(a).print();
* b.dot(c).print();
* ```
* @param t1 The first tensor in the dot operation.
* @param t2 The second tensor in the dot operation.
*
* @doc {heading: 'Operations', subheading: 'Matrices'}
*/
function dot_(t1, t2) {
const $t1 = convertToTensor(t1, 't1', 'dot');
const $t2 = convertToTensor(t2, 't2', 'dot');
assert(($t1.rank === 1 || $t1.rank === 2) && ($t2.rank === 1 || $t2.rank === 2), () => `Error in dot: inputs must all be rank 1 or 2, but got ranks ` +
`${$t1.rank} and ${$t2.rank}.`);
const t1Inner = ($t1.rank === 1 ? $t1.size : $t1.shape[1]);
const t2Inner = ($t2.rank === 1 ? $t2.size : $t2.shape[0]);
assert(t1Inner === t2Inner, () => `Error in dot: inner dimensions of inputs must match, but got ` +
`${t1Inner} and ${t2Inner}.`);
if ($t1.rank === 1 && $t2.rank === 1) {
const t12D = reshape($t1, [1, -1]);
const t22D = reshape($t2, [-1, 1]);
const t1t2 = matMul(t12D, t22D);
return reshape(t1t2, []);
}
else if ($t1.rank === 1 && $t2.rank === 2) {
const t12D = reshape($t1, [1, -1]);
const t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);
const t1t2 = matMul(t12D, t22D);
return reshape(t1t2, [t1t2.size]);
}
else if ($t1.rank === 2 && $t2.rank === 1) {
const t22D = reshape($t2, [-1, 1]);
const t1t2 = matMul($t1, t22D);
return reshape(t1t2, [t1t2.size]);
}
else {
const t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);
const t1t2 = matMul($t1, t22D);
return t1t2;
}
}
const dot = op({ dot_ });
/**
* @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.
* =============================================================================
*/
/**
* Tensor contraction over specified indices and outer product.
*
* `einsum` allows defining Tensors by defining their element-wise computation.
* This computation is based on
* [Einstein summation](https://en.wikipedia.org/wiki/Einstein_notation).
*
* Some special cases include:
*
* Matrix multiplication:
* ```js
* const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);
* const y = tf.tensor2d([[0, 1], [2, 3], [4, 5]]);
* x.print();
* y.print();
* tf.einsum('ij,jk->ik', x, y).print();
* ```
*
* Dot product:
* ```js
* const x = tf.tensor1d([1, 2, 3]);
* const y = tf.tensor1d([0, 1, 2]);
* x.print();
* y.print();
* tf.einsum('i,i->', x, y).print();
* ```
*
* Batch dot product:
* ```js
* const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);
* const y = tf.tensor2d([[0, 1, 2], [3, 4, 5]]);
* x.print();
* y.print();
* tf.einsum('bi,bi->b', x, y).print();
* ```
*
* Outer prouduct:
* ```js
* const x = tf.tensor1d([1, 3, 5]);
* const y = tf.tensor1d([2, 4, 6]);
* x.print();
* y.print();
* tf.einsum('i,j->ij', x, y).print();
* ```
*
* Matrix transpose:
* ```js
* const x = tf.tensor2d([[1, 2], [3, 4]]);
* x.print();
* tf.einsum('ij->ji', x).print();
* ```
*
* Batch matrix transpose:
* ```js
* const x = tf.tensor3d([[[1, 2], [3, 4]], [[-1, -2], [-3, -4]]]);
* x.print();
* tf.einsum('bij->bji', x).print();
* ```
*
* Limitations:
*
* This implementation of einsum has the following limitations:
*
* - Does not support >2 input tensors.
* - Does not support duplicate axes for any given input tensor. E.g., equation
* 'ii->' is not suppoted.
* - The `...` notation is not supported.
*
* @param equation a string describing the contraction, in the same format as
* [numpy.einsum](https://numpy.org/doc/stable/reference/generated/numpy.einsum.html).
* @param tensors the input(s) to contract (each one a Tensor), whose shapes
* should be consistent with equation.
* @returns The output tensor.
*
* @doc {heading: 'Tensors', subheading: 'Matrices'}
*/
function einsum_(equation, ...tensors) {
const $tensors = tensors.map((t, i) => convertToTensor(t, `tensors${i}`, 'einsum'));
const attrs = { equation };
return ENGINE.runKernel(Einsum, $tensors, attrs);
}
const einsum = op({ einsum_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes exponential linear element-wise: `x > 0 ? e ^ x - 1 : 0`.
*
* ```js
* const x = tf.tensor1d([-1, 1, -3, 2]);
*
* x.elu().print(); // or tf.elu(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function elu_(x) {
const $x = convertToTensor(x, 'x', 'elu');
const inputs = { x: $x };
return ENGINE.runKernel(Elu, inputs);
}
const elu = op({ elu_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes gause error function of the input `tf.Tensor` element-wise:
* `erf(x)`
*
* ```js
* const x = tf.tensor1d([0, .1, -.1, .7]);
*
* x.erf().print(); // or tf.erf(x);
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function erf_(x) {
let $x = convertToTensor(x, 'x', 'erf');
assert($x.dtype === 'int32' || $x.dtype === 'float32', () => 'Input dtype must be `int32` or `float32`.');
if ($x.dtype === 'int32') {
$x = cast($x, 'float32');
}
const inputs = { x: $x };
return ENGINE.runKernel(Erf, inputs);
}
const erf = op({ erf_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes exponential of the input `tf.Tensor` minus one element-wise.
* `e ^ x - 1`
*
* ```js
* const x = tf.tensor1d([1, 2, -3]);
*
* x.expm1().print(); // or tf.expm1(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function expm1_(x) {
const $x = convertToTensor(x, 'x', 'expm1');
const inputs = { x: $x };
return ENGINE.runKernel(Expm1, inputs);
}
const expm1 = op({ expm1_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Create an identity matrix.
*
* @param numRows Number of rows.
* @param numColumns Number of columns. Defaults to `numRows`.
* @param batchShape If provided, will add the batch shape to the beginning
* of the shape of the returned `tf.Tensor` by repeating the identity
* matrix.
* @param dtype Data type.
* @returns Identity matrix of the specified size and data type, possibly
* with batch repetition if `batchShape` is specified.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function eye_(numRows, numColumns, batchShape, dtype = 'float32') {
if (numColumns == null) {
numColumns = numRows;
}
const buff = buffer([numRows, numColumns], dtype);
const n = numRows <= numColumns ? numRows : numColumns;
for (let i = 0; i < n; ++i) {
buff.set(1, i, i);
}
const out = reshape(buff.toTensor(), [numRows, numColumns]);
if (batchShape == null) {
return out;
}
else {
if (batchShape.length === 1) {
return tile(expandDims(out, 0), [batchShape[0], 1, 1]);
}
else if (batchShape.length === 2) {
// tslint:disable-next-line:no-unnecessary-type-assertion
return tile(expandDims(expandDims(out, 0), 0), [batchShape[0], batchShape[1], 1, 1]);
}
else if (batchShape.length === 3) {
// tslint:disable-next-line:no-unnecessary-type-assertion
return tile(expandDims(expandDims(expandDims(out, 0), 0), 0), [
batchShape[0], batchShape[1], batchShape[2], 1, 1
]);
}
else {
throw new Error(`eye() currently supports only 1D and 2D ` +
// tslint:disable-next-line:no-any
`batchShapes, but received ${batchShape.length}D.`);
}
}
}
const eye = op({ eye_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` filled with a scalar value.
*
* ```js
* tf.fill([2, 2], 4).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param value The scalar value to fill the tensor with.
* @param dtype The type of an element in the resulting tensor. Defaults to
* 'float'.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function fill(shape, value, dtype) {
const attrs = { shape, value, dtype };
return ENGINE.runKernel(Fill, {}, attrs);
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the imaginary part of a complex (or real) tensor.
*
* Given a tensor input, this operation returns a tensor of type float that is
* the imaginary part of each element in input considered as a complex number.
* If input is real, a tensor of all zeros is returned.
*
* ```js
* const x = tf.complex([-2.25, 3.25], [4.75, 5.75]);
* tf.imag(x).print();
* ```
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function imag_(input) {
const $input = convertToTensor(input, 'input', 'imag');
const inputs = { input: $input };
return ENGINE.runKernel(Imag, inputs);
}
const imag = op({ imag_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns which elements of x are finite.
*
* ```js
* const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);
*
* x.isFinite().print(); // or tf.isNaN(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function isFinite_(x) {
const $x = convertToTensor(x, 'x', 'isFinite');
const inputs = { x: $x };
return ENGINE.runKernel(IsFinite, inputs);
}
const isFinite$1 = op({ isFinite_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns which elements of x are Infinity or -Infinity.
*
* ```js
* const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);
*
* x.isInf().print(); // or tf.isNaN(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function isInf_(x) {
const $x = convertToTensor(x, 'x', 'isInf');
const inputs = { x: $x };
return ENGINE.runKernel(IsInf, inputs);
}
const isInf = op({ isInf_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* RReturns which elements of x are NaN.
*
* ```js
* const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);
*
* x.isNaN().print(); // or tf.isNaN(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function isNaN_(x) {
const $x = convertToTensor(x, 'x', 'isNaN');
const inputs = { x: $x };
return ENGINE.runKernel(IsNan, inputs);
}
const isNaN$1 = op({ isNaN_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes leaky rectified linear element-wise.
*
* See
* [http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf](
* http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf)
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.leakyRelu(0.1).print(); // or tf.leakyRelu(x, 0.1)
* ```
* @param x The input tensor.
* @param alpha The scaling factor for negative values, defaults to 0.2.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function leakyRelu_(x, alpha = 0.2) {
const $x = convertToTensor(x, 'x', 'leakyRelu');
const inputs = { x: $x };
const attrs = { alpha };
return ENGINE.runKernel(LeakyRelu, inputs, attrs);
}
const leakyRelu = op({ leakyRelu_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Return an evenly spaced sequence of numbers over the given interval.
*
* ```js
* tf.linspace(0, 9, 10).print();
* ```
* @param start The start value of the sequence.
* @param stop The end value of the sequence.
* @param num The number of values to generate.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function linspace(start, stop, num) {
if (num <= 0) {
throw new Error('The number of values should be positive.');
}
const attrs = { start, stop, num };
return ENGINE.runKernel(LinSpace, {}, attrs);
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Normalizes the activation of a local neighborhood across or within
* channels.
*
* @param x The input tensor. The 4-D input tensor is treated as a 3-D array
* of 1D vectors (along the last dimension), and each vector is
* normalized independently.
* @param depthRadius The number of adjacent channels in the 1D normalization
* window.
* @param bias A constant bias term for the basis.
* @param alpha A scale factor, usually positive.
* @param beta An exponent.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function localResponseNormalization_(x, depthRadius = 5, bias = 1, alpha = 1, beta = 0.5) {
const $x = convertToTensor(x, 'x', 'localResponseNormalization');
assert($x.rank === 4 || $x.rank === 3, () => `Error in localResponseNormalization: x must be rank 3 or 4 but got
rank ${$x.rank}.`);
assert(isInt(depthRadius), () => `Error in localResponseNormalization: depthRadius must be an ` +
`integer but got depthRadius ${depthRadius}.`);
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
const inputs = { x: x4D };
const attrs = { depthRadius, bias, alpha, beta };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(LRN, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
else {
return res;
}
}
const localResponseNormalization = op({ localResponseNormalization_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes natural logarithm of the input `tf.Tensor` plus one
* element-wise: `ln(1 + x)`
*
* ```js
* const x = tf.tensor1d([1, 2, Math.E - 1]);
*
* x.log1p().print(); // or tf.log1p(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function log1p_(x) {
const $x = convertToTensor(x, 'x', 'log1p');
const inputs = { x: $x };
return ENGINE.runKernel(Log1p, inputs);
}
const log1p = op({ log1p_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Provided `f(x)`, returns another function `g(x, dy?)`, which gives the
* gradient of `f(x)` with respect to `x`.
*
* If `dy` is provided, the gradient of `f(x).mul(dy).sum()` with respect to
* `x` is computed instead. `f(x)` must take a single tensor `x` and return a
* single tensor `y`. If `f()` takes multiple inputs, use `tf.grads` instead.
*
* ```js
* // f(x) = x ^ 2
* const f = x => x.square();
* // f'(x) = 2x
* const g = tf.grad(f);
*
* const x = tf.tensor1d([2, 3]);
* g(x).print();
* ```
*
* ```js
* // f(x) = x ^ 3
* const f = x => x.pow(tf.scalar(3, 'int32'));
* // f'(x) = 3x ^ 2
* const g = tf.grad(f);
* // f''(x) = 6x
* const gg = tf.grad(g);
*
* const x = tf.tensor1d([2, 3]);
* gg(x).print();
* ```
*
* @param f The function f(x), to compute gradient for.
*
* @doc {heading: 'Training', subheading: 'Gradients'}
*/
function grad(f) {
assert(isFunction(f), () => 'The f passed in grad(f) must be a function');
return (x, dy) => {
// x can be of any dtype, thus null as the last argument.
const $x = convertToTensor(x, 'x', 'tf.grad', 'string_or_numeric');
const $dy = (dy != null) ? convertToTensor(dy, 'dy', 'tf.grad') : null;
return ENGINE.tidy(() => {
const { value, grads } = ENGINE.gradients(() => f($x), [$x], $dy);
if ($dy != null) {
assertShapesMatch(value.shape, $dy.shape, 'The shape of dy passed in grad(f)(x, dy) must match the shape ' +
'returned by f(x)');
}
checkGrads(grads);
return grads[0];
});
};
}
/**
* Provided `f(x1, x2,...)`, returns another function `g([x1, x2,...], dy?)`,
* which gives an array of gradients of `f()` with respect to each input
* [`x1`,`x2`,...].
*
* If `dy` is passed when calling `g()`, the gradient of
* `f(x1,...).mul(dy).sum()` with respect to each input is computed instead.
* The provided `f` must take one or more tensors and return a single tensor
* `y`. If `f()` takes a single input, we recommend using `tf.grad` instead.
*
* ```js
* // f(a, b) = a * b
* const f = (a, b) => a.mul(b);
* // df / da = b, df / db = a
* const g = tf.grads(f);
*
* const a = tf.tensor1d([2, 3]);
* const b = tf.tensor1d([-2, -3]);
* const [da, db] = g([a, b]);
* console.log('da');
* da.print();
* console.log('db');
* db.print();
* ```
*
* @param f The function `f(x1, x2,...)` to compute gradients for.
*
* @doc {heading: 'Training', subheading: 'Gradients'}
*/
function grads(f) {
assert(isFunction(f), () => 'The f passed in grads(f) must be a function');
return (args, dy) => {
assert(Array.isArray(args), () => 'The args passed in grads(f)(args) must be an array ' +
'of `Tensor`s or `TensorLike`s');
// args can be of any dtype, thus null as the last argument.
const $args = convertToTensorArray(args, 'args', 'tf.grads', 'string_or_numeric');
const $dy = (dy != null) ? convertToTensor(dy, 'dy', 'tf.grads') : null;
return ENGINE.tidy(() => {
const { value, grads } = ENGINE.gradients(() => f(...$args), $args, $dy);
if ($dy != null) {
assertShapesMatch(value.shape, $dy.shape, 'The shape of dy passed in grads(f)([x1,...], dy) must ' +
'match the shape returned by f([x1,...])');
}
checkGrads(grads);
return grads;
});
};
}
/**
* Like `tf.grad`, but also returns the value of `f()`. Useful when `f()`
* returns a metric you want to show.
*
* The result is a rich object with the following properties:
* - grad: The gradient of `f(x)` w.r.t `x` (result of `tf.grad`).
* - value: The value returned by `f(x)`.
*
* ```js
* // f(x) = x ^ 2
* const f = x => x.square();
* // f'(x) = 2x
* const g = tf.valueAndGrad(f);
*
* const x = tf.tensor1d([2, 3]);
* const {value, grad} = g(x);
*
* console.log('value');
* value.print();
* console.log('grad');
* grad.print();
* ```
*
* @doc {heading: 'Training', subheading: 'Gradients'}
*/
function valueAndGrad(f) {
assert(isFunction(f), () => 'The f passed in valueAndGrad(f) must be a function');
return (x, dy) => {
assert(x instanceof Tensor, () => 'The x passed in valueAndGrad(f)(x) must be a tensor');
assert(dy == null || dy instanceof Tensor, () => 'The dy passed in valueAndGrad(f)(x, dy) must be a tensor');
const { grads, value } = ENGINE.gradients(() => f(x), [x], dy);
checkGrads(grads);
return { grad: grads[0], value };
};
}
/**
* Like `tf.grads`, but returns also the value of `f()`. Useful when `f()`
* returns a metric you want to show.
*
* The result is a rich object with the following properties:
* - grads: The gradients of `f()` w.r.t each input (result of `tf.grads`).
* - value: The value returned by `f(x)`.
*
* ```js
* // f(a, b) = a * b
* const f = (a, b) => a.mul(b);
* // df/da = b, df/db = a
* const g = tf.valueAndGrads(f);
*
* const a = tf.tensor1d([2, 3]);
* const b = tf.tensor1d([-2, -3]);
* const {value, grads} = g([a, b]);
*
* const [da, db] = grads;
*
* console.log('value');
* value.print();
*
* console.log('da');
* da.print();
* console.log('db');
* db.print();
* ```
*
* @doc {heading: 'Training', subheading: 'Gradients'}
*/
function valueAndGrads(f) {
assert(isFunction(f), () => 'The f passed in valueAndGrads(f) must be a function');
return (args, dy) => {
assert(Array.isArray(args) && args.every(arg => arg instanceof Tensor), () => 'The args passed in valueAndGrads(f)(args) must be array of ' +
'tensors');
assert(dy == null || dy instanceof Tensor, () => 'The dy passed in valueAndGrads(f)(args, dy) must be a tensor');
const res = ENGINE.gradients(() => f(...args), args, dy);
if (dy != null) {
assertShapesMatch(res.value.shape, dy.shape, 'The shape of dy passed in valueAndGrads(f)([x1,...], dy) must ' +
'match the shape returned by f([x1,...])');
}
checkGrads(res.grads);
return res;
};
}
/**
* Computes and returns the gradient of f(x) with respect to the list of
* trainable variables provided by `varList`. If no list is provided, it
* defaults to all trainable variables.
*
* ```js
* const a = tf.variable(tf.tensor1d([3, 4]));
* const b = tf.variable(tf.tensor1d([5, 6]));
* const x = tf.tensor1d([1, 2]);
*
* // f(a, b) = a * x ^ 2 + b * x
* const f = () => a.mul(x.square()).add(b.mul(x)).sum();
* // df/da = x ^ 2, df/db = x
* const {value, grads} = tf.variableGrads(f);
*
* Object.keys(grads).forEach(varName => grads[varName].print());
* ```
*
* @param f The function to execute. f() should return a scalar.
* @param varList The list of variables to compute the gradients with respect
* to. Defaults to all trainable variables.
* @returns An object with the following keys and values:
* - `value`: The value of the function `f`.
* - `grads`: A map from the names of the variables to the gradients.
* If the `varList` argument is provided explicitly and contains a subset of
* non-trainable variables, this map in the return value will contain keys
* that map the names of the non-trainable variables to `null`.
*
* @doc {heading: 'Training', subheading: 'Gradients'}
*/
function variableGrads(f, varList) {
assert(isFunction(f), () => 'The f passed in variableGrads(f) must be a function');
assert(varList == null ||
Array.isArray(varList) && varList.every(v => v instanceof Variable), () => 'The varList passed in variableGrads(f, varList) must be an array ' +
'of variables');
const specifiedVarList = varList != null;
if (!specifiedVarList) {
// Get all of the trainable variables.
varList = [];
for (const varName in ENGINE.registeredVariables) {
varList.push(ENGINE.registeredVariables[varName]);
}
}
const specifiedNonTrainable = specifiedVarList ? varList.filter(variable => !variable.trainable) : null;
// Prune non-trainable variables.
const originalVarCount = varList.length;
varList = varList.filter(variable => variable.trainable);
assert(varList.length > 0, () => `variableGrads() expects at least one of the input variables to ` +
`be trainable, but none of the ${originalVarCount} variables is ` +
`trainable.`);
const allowNoGradients = true;
const { value, grads } = ENGINE.gradients(f, varList, null, allowNoGradients);
assert(grads.some(g => g != null), () => 'Cannot find a connection between any variable and the result of ' +
'the loss function y=f(x). Please make sure the operations that ' +
'use variables are inside the function f passed to minimize().');
assert(value.rank === 0, () => `The f passed in variableGrads(f) must return a scalar, but it ` +
`returned a rank-${value.rank} tensor`);
const namedGrads = {};
varList.forEach((v, i) => {
if (grads[i] != null) {
namedGrads[v.name] = grads[i];
}
});
if (specifiedNonTrainable != null) {
// If varList is explicitly provided and contains non-trainable values,
// add them to the returned gradients with `null` values.
specifiedNonTrainable.forEach(v => namedGrads[v.name] = null);
}
return { value, grads: namedGrads };
}
/**
* Overrides the gradient computation of a function `f`.
*
* Takes a function
* `f(...inputs, save) => {value: Tensor, gradFunc: (dy, saved) => Tensor[]}`
* and returns another function `g(...inputs)` which takes the same inputs as
* `f`. When called, `g` returns `f().value`. In backward mode, custom gradients
* with respect to each input of `f` are computed using `f().gradFunc`.
*
* The `save` function passsed to `f` should be used for saving tensors needed
* in the gradient. And the `saved` passed to the `gradFunc` is a
* `NamedTensorMap`, which contains those saved tensor.
*
* ```js
* const customOp = tf.customGrad((x, save) => {
* // Save x to make sure it's available later for the gradient.
* save([x]);
* // Override gradient of our custom x ^ 2 op to be dy * abs(x);
* return {
* value: x.square(),
* // Note `saved.x` which points to the `x` we saved earlier.
* gradFunc: (dy, saved) => [dy.mul(saved[0].abs())]
* };
* });
*
* const x = tf.tensor1d([-1, -2, 3]);
* const dx = tf.grad(x => customOp(x));
*
* console.log(`f(x):`);
* customOp(x).print();
* console.log(`f'(x):`);
* dx(x).print();
* ```
*
* @param f The function to evaluate in forward mode, which should return
* `{value: Tensor, gradFunc: (dy, saved) => Tensor[]}`, where `gradFunc`
* returns the custom gradients of `f` with respect to its inputs.
*
* @doc {heading: 'Training', subheading: 'Gradients'}
*/
function customGrad(f) {
return ENGINE.customGrad(f);
}
function checkGrads(grads) {
const numNullGradients = grads.filter(g => g == null).length;
if (numNullGradients > 0) {
throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
the f you passed encloses all operations that lead from x to y.`);
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes softplus of the input `tf.Tensor` element-wise: `log(exp(x) + 1)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.softplus().print(); // or tf.softplus(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function softplus_(x) {
const $x = convertToTensor(x, 'x', 'softplus');
const inputs = { x: $x };
return ENGINE.runKernel(Softplus, inputs);
}
const softplus = op({ softplus_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes log sigmoid of the input `tf.Tensor` element-wise:
* `logSigmoid(x)`. For numerical stability, we use `-tf.softplus(-x)`.
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.logSigmoid().print(); // or tf.logSigmoid(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function logSigmoid_(x) {
const $x = convertToTensor(x, 'x', 'logSigmoid');
// Use a custom gradient to maintain previous implementation.
// There is no LogSigmoid kernel in TF so we can't use engine.runKernel
// directly
const customOp = customGrad((x) => {
// TODO(yassogba) we can remove the chained softplus call here only
// after backends have modualrized softplus at which point we can call
// engine runKernel(..., Sotfplus, ...) directly.
const value = neg(softplus(neg(x)));
const gradFunc = (dy) => {
const derX = mul(dy, sigmoid(neg(x)));
return derX;
};
return { value, gradFunc };
});
return customOp($x);
}
const logSigmoid = op({ logSigmoid_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the maximum of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and an
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.max().print(); // or tf.max(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.max(axis).print(); // or tf.max(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function max_(x, axis = null, keepDims = false) {
const $x = convertToTensor(x, 'x', 'max');
const inputs = { x: $x };
const attrs = { reductionIndices: axis, keepDims };
return ENGINE.runKernel(Max, inputs, attrs);
}
const max = op({ max_ });
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the log softmax.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
*
* a.logSoftmax().print(); // or tf.logSoftmax(a)
* ```
*
* ```js
* const a = tf.tensor2d([2, 4, 6, 1, 2, 3], [2, 3]);
*
* a.logSoftmax().print(); // or tf.logSoftmax(a)
* ```
*
* @param logits The logits array.
* @param axis The dimension softmax would be performed on. Defaults to `-1`
* which indicates the last dimension.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function logSoftmax_(logits, axis = -1) {
const $logits = convertToTensor(logits, 'logits', 'logSoftmax');
if (axis === -1) {
axis = $logits.rank - 1;
}
if (axis !== $logits.rank - 1) {
throw Error('Log Softmax along a non-last dimension is not yet supported. ' +
`Logits was rank ${$logits.rank} and axis was ${axis}`);
}
// const forward: ForwardFunc = (backend, save) => {
// const keepDims = true;
// const xMax = max(logits, axis, true);
// const shifted = sub(logits, xMax);
// const value =
// sub(cast(shifted, 'float32'), log(sum(exp(shifted), axis,
// keepDims)));
// save([value]);
// return value;
// };
// Use a custom gradient for numerical stability.
const customOp = customGrad((logits, save) => {
const keepDims = true;
const xMax = max(logits, axis, true);
const shifted = sub(logits, xMax);
const value = sub(cast(shifted, 'float32'), log(sum$1(exp(shifted), axis, keepDims)));
save([value]);
const gradFunc = (dy, saved) => {
const [value] = saved;
const keepDims = true;
const softmax = exp(value);
return sub(dy, mul(sum$1(dy, axis, keepDims), softmax));
};
return { value, gradFunc };
});
return customOp($logits);
// TODO Use Engine.runKernel when CPU/WebGL/WASM backends implement this.
// const inputs: LogSoftmaxInputs = {logits: $logits};
// const attrs: LogSoftmaxAttrs = {axis};
// return ENGINE.runKernel(
// LogSoftmax, inputs as {} as NamedTensorMap,
// attrs as {} as NamedAttrMap);
}
const logSoftmax = op({ logSoftmax_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the log(sum(exp(elements across the reduction dimensions)).
*
* Reduces the input along the dimensions given in `axis`. Unless `keepDims`
* is true, the rank of the array is reduced by 1 for each entry in `axis`.
* If `keepDims` is true, the reduced dimensions are retained with length 1.
* If `axis` has no entries, all dimensions are reduced, and an array with a
* single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.logSumExp().print(); // or tf.logSumExp(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.logSumExp(axis).print(); // or tf.logSumExp(a, axis)
* ```
* @param x The input tensor.
* @param axis The dimension(s) to reduce. If null (the default),
* reduces all dimensions.
* @param keepDims If true, retains reduced dimensions with length
* of 1. Defaults to false.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function logSumExp_(x, axis = null, keepDims = false) {
const $x = convertToTensor(x, 'x', 'logSumExp');
const axes = parseAxisParam(axis, $x.shape);
const xMax = max($x, axes, true /* keepDims */);
const a = sub($x, xMax);
const b = exp(a);
const c = sum$1(b, axes);
const d = log(c);
const res = add$1(reshape(xMax, d.shape), d);
if (keepDims) {
const newShape = expandShapeToKeepDim(res.shape, axes);
return reshape(res, newShape);
}
return res;
}
const logSumExp = op({ logSumExp_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of `a OR b` element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([false, false, true, true], 'bool');
* const b = tf.tensor1d([false, true, false, true], 'bool');
*
* a.logicalOr(b).print();
* ```
* @param a The first input tensor. Must be of dtype bool.
* @param b The second input tensor. Must be of dtype bool.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function logicalOr_(a, b) {
const $a = convertToTensor(a, 'a', 'logicalOr', 'bool');
const $b = convertToTensor(b, 'b', 'logicalOr', 'bool');
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(LogicalOr, inputs);
}
const logicalOr = op({ logicalOr_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of `a XOR b` element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([false, false, true, true], 'bool');
* const b = tf.tensor1d([false, true, false, true], 'bool');
*
* a.logicalXor(b).print();
* ```
*
* @param a The first input tensor. Must be of dtype bool.
* @param b The second input tensor. Must be of dtype bool.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function logicalXor_(a, b) {
const $a = convertToTensor(a, 'a', 'logicalXor', 'bool');
const $b = convertToTensor(b, 'b', 'logicalXor', 'bool');
assertAndGetBroadcastShape($a.shape, $b.shape);
// x ^ y = (x | y) & ~(x & y)
return logicalAnd(logicalOr(a, b), logicalNot(logicalAnd(a, b)));
}
const logicalXor = op({ logicalXor_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the 2D max pooling of an image.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in dilated pooling. Defaults to `[1, 1]`. If `dilations` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function maxPool_(x, filterSize, strides, pad, dimRoundingMode) {
const $x = convertToTensor(x, 'x', 'maxPool');
const dilations = 1;
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
assert(x4D.rank === 4, () => `Error in maxPool: input must be rank 4 but got rank ${x4D.rank}.`);
assert(eitherStridesOrDilationsAreOne(strides, dilations), () => 'Error in maxPool: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in maxPool: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x4D };
const attrs = { filterSize, strides, pad, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(MaxPool, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const maxPool = op({ maxPool_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the 3D max pooling.
*
* ```js
* const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);
* const result = tf.maxPool3d(x, 2, 1, 'valid');
* result.print();
* ```
*
* @param x The input tensor, of rank 5 or rank 4 of shape
* `[batch, depth, height, width, inChannels]`.
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* If `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideDepth == strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
* @param dataFormat An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function maxPool3d_(x, filterSize = [1, 1, 1], strides, pad, dimRoundingMode, dataFormat = 'NDHWC') {
const $x = convertToTensor(x, 'x', 'maxPool3d');
let x5D = $x;
let reshapedTo5D = false;
if ($x.rank === 4) {
reshapedTo5D = true;
x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
}
assert(x5D.rank === 5, () => `Error in maxPool3d: x must be rank 5 but got rank ${x5D.rank}.`);
assert(dataFormat === 'NDHWC', () => `Error in maxPool3d: Only NDHWC is currently supported, ` +
`but got dataFormat of ${dataFormat}`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in maxPool3d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x5D };
const attrs = { filterSize, strides, pad, dimRoundingMode, dataFormat };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(MaxPool3D, inputs, attrs);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const maxPool3d = op({ maxPool3d_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the 2D max pooling of an image with Argmax index.
* The indices in argmax are flattened, so that a maximum value at position `[b,
* y, x, c]` becomes flattened index: `(y * width + x) * channels + c` if
* include_batch_in_index is False; `((b * height + y) * width + x) * channels
* +c` if include_batch_in_index is True.
*
* The indices returned are always in `[0, height) x [0, width)` before
* flattening.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param dataFormat An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param includeBatchIndex Defaults to False. Whether to include batch
* dimension in flattened index of argmax.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function maxPoolWithArgmax_(x, filterSize, strides, pad, includeBatchInIndex = false) {
const $x = convertToTensor(x, 'x', 'maxPoolWithArgmax');
const inputs = { x: $x };
const attrs = { filterSize, strides, pad, includeBatchInIndex };
// tslint:disable-next-line: no-unnecessary-type-assertion
const result = ENGINE.runKernel(MaxPoolWithArgmax, inputs, attrs);
return { result: result[0], indexes: result[1] };
}
const maxPoolWithArgmax = op({ maxPoolWithArgmax_ });
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the mean of elements across dimensions of a `tf.Tensor`.
*
* Reduces `x` along the dimensions given in `axis`. Unless `keepDims` is
* true, the rank of the `tf.Tensor` is reduced by 1 for each entry in `axis`.
* If `keepDims` is true, the reduced dimensions are retained with length 1.
* If `axis` has no entries, all dimensions are reduced, and a `tf.Tensor` with
* a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.mean().print(); // or tf.mean(a)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.mean(axis).print(); // or tf.mean(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function mean_(x, axis = null, keepDims = false) {
const $x = convertToTensor(x, 'x', 'mean');
const inputs = { x: $x };
const attrs = { axis, keepDims };
return ENGINE.runKernel(Mean, inputs, attrs);
}
const mean = op({ mean_ });
/**
* @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.
* =============================================================================
*/
/**
* Broadcasts parameters for evaluation on an N-D grid.
*
* Given N one-dimensional coordinate arrays `*args`, returns a list `outputs`
* of N-D coordinate arrays for evaluating expressions on an N-D grid.
*
* Notes:
* `meshgrid` supports cartesian ('xy') and matrix ('ij') indexing conventions.
* When the `indexing` argument is set to 'xy' (the default), the broadcasting
* instructions for the first two dimensions are swapped.
* Examples:
* Calling `const [X, Y] = meshgrid(x, y)` with the tensors
*
* ```javascript
* const x = [1, 2, 3];
* const y = [4, 5, 6];
* const [X, Y] = tf.meshgrid(x, y);
* // X = [[1, 2, 3],
* // [1, 2, 3],
* // [1, 2, 3]]
* // Y = [[4, 4, 4],
* // [5, 5, 5],
* // [6, 6, 6]]
* ```
*
* @param x Tensor with rank geq 1.
* @param y Tensor with rank geq 1.
* @param indexing
*
* @doc {heading: 'Operations', subheading: 'Slicing and Joining'}
*/
function meshgrid(x, y, { indexing = 'xy' } = {}) {
if (indexing !== 'xy' && indexing !== 'ij') {
throw new TypeError(`${indexing} is not a valid third argument to meshgrid`);
}
if (x === undefined) {
return [];
}
let $x = convertToTensor(x, 'x', 'meshgrid', x instanceof Tensor ? x.dtype : 'float32');
if (y === undefined) {
return [$x];
}
let $y = convertToTensor(y, 'y', 'meshgrid', y instanceof Tensor ? y.dtype : 'float32');
const w = sizeFromShape($x.shape);
const h = sizeFromShape($y.shape);
if (indexing === 'xy') {
$x = reshape($x, [1, -1]);
$y = reshape($y, [-1, 1]);
return [
matMul(ones$1([h, 1], $x.dtype), $x),
matMul($y, ones$1([1, w], $y.dtype)),
];
}
$x = reshape($x, [-1, 1]);
$y = reshape($y, [1, -1]);
return [
matMul($x, ones$1([1, h], $x.dtype)),
matMul(ones$1([w, 1], $y.dtype), $y),
];
}
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the minimum value from the input.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the array is reduced by 1 for each entry in `axes`.
* If `keepDims` is true, the reduced dimensions are retained with length 1.
* If `axes` has no entries, all dimensions are reduced, and an array with a
* single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.min().print(); // or tf.min(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.min(axis).print(); // or tf.min(x, axis)
* ```
*
* @param x The input Tensor.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function min_(x, axis = null, keepDims = false) {
const $x = convertToTensor(x, 'x', 'min');
const inputs = { x: $x };
const attrs = { axis, keepDims };
// tslint:disable-next-line: no-unnecessary-type-assertion
return ENGINE.runKernel(Min, inputs, attrs);
}
const min = op({ min_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the min of a and b (`a < b ? a : b`) element-wise.
* Supports broadcasting.
*
* We also expose `minimumStrict` which has the same signature as this op and
* asserts that `a` and `b` are the same shape (does not broadcast).
*
* ```js
* const a = tf.tensor1d([1, 4, 3, 16]);
* const b = tf.tensor1d([1, 2, 9, 4]);
*
* a.minimum(b).print(); // or tf.minimum(a, b)
* ```
*
* ```js
* // Broadcast minimum a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(5);
*
* a.minimum(b).print(); // or tf.minimum(a, b)
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function minimum_(a, b) {
let $a = convertToTensor(a, 'a', 'minimum');
let $b = convertToTensor(b, 'b', 'minimum');
[$a, $b] = makeTypesMatch($a, $b);
if ($a.dtype === 'bool') {
$a = cast($a, 'int32');
$b = cast($b, 'int32');
}
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Minimum, inputs);
}
const minimum = op({ minimum_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Pads a `tf.Tensor` using mirror padding.
*
* This operation implements the `REFLECT` and `SYMMETRIC` modes of pad.
*
* ```js
* const x = tf.range(0, 9).reshape([1, 1, 3, 3]);
* x.mirrorPad([[0, 0], [0, 0], [2, 2], [2, 2]], 'reflect').print();
* ```
* @param x The tensor to pad.
* @param paddings An array of length `R` (the rank of the tensor), where
* each element is a length-2 tuple of ints `[padBefore, padAfter]`,
* specifying how much to pad along each dimension of the tensor.
* In "reflect" mode, the padded regions do not include the borders,
* while in "symmetric" mode the padded regions do include the borders.
* For example, if the input is `[1, 2, 3]` and paddings is `[0, 2]`,
* then the output is `[1, 2, 3, 2, 1]` in "reflect" mode, and
* `[1, 2, 3, 3, 2]` in "symmetric" mode.
* If `mode` is "reflect" then both `paddings[D, 0]` and `paddings[D, 1]`
* must be no greater than `x.shape[D] - 1`. If mode is "symmetric"
* then both `paddings[D, 0]` and `paddings[D, 1]` must be no greater than
* `x.shape[D]`
* @param mode String to specify padding mode. Can be `'reflect' | 'symmetric'`
*/
/** @doc {heading: 'Tensors', subheading: 'Transformations'} */
function mirrorPad_(x, paddings, mode) {
assert(mode === 'reflect' || mode === 'symmetric', () => `Invalid mode. Mode must be either reflect or symmetric. ` +
`Got ${mode}.`);
const $x = convertToTensor(x, 'x', 'mirrorPad');
if ($x.rank === 0) {
throw new Error('mirrorPad(scalar) is not defined. ' +
'Pass non-scalar to mirrorPad');
}
assert(paddings.length === $x.rank, () => `Padding doesn't match input. Must be ${$x.rank}. ` +
`Got ${paddings.length}.`);
const shapeOffset = mode === 'reflect' ? 1 : 0;
for (let i = 0; i < $x.rank; i++) {
assert(paddings[i].length === 2, () => `Invalid number of paddings. Must be length of 2 each.`);
assert(paddings[i][0] >= 0 && paddings[i][0] <= $x.shape[i] - shapeOffset &&
paddings[i][1] >= 0 && paddings[i][1] <= $x.shape[i] - shapeOffset, () => `Padding in dimension ${i} cannot be greater than or equal ` +
`to ${$x.shape[i] - shapeOffset} or less than 0 for input of ` +
`shape ${$x.shape}`);
}
const attrs = { paddings, mode };
const inputs = { x: $x };
return ENGINE.runKernel(MirrorPad, inputs, attrs);
}
const mirrorPad = op({ mirrorPad_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the mod of a and b element-wise.
* `floor(x / y) * y + mod(x, y) = x`
* Supports broadcasting.
*
* We also expose `tf.modStrict` which has the same signature as this op and
* asserts that `a` and `b` are the same shape (does not broadcast).
*
* ```js
* const a = tf.tensor1d([1, 4, 3, 16]);
* const b = tf.tensor1d([1, 2, 9, 4]);
*
* a.mod(b).print(); // or tf.mod(a, b)
* ```
*
* ```js
* // Broadcast a mod b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(5);
*
* a.mod(b).print(); // or tf.mod(a, b)
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function mod_(a, b) {
let $a = convertToTensor(a, 'a', 'mod');
let $b = convertToTensor(b, 'b', 'mod');
[$a, $b] = makeTypesMatch($a, $b);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Mod, inputs);
}
const mod = op({ mod_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Calculates the mean and variance of `x`. The mean and variance are
* calculated by aggregating the contents of `x` across `axes`. If `x` is
* 1-D and `axes = [0]` this is just the mean and variance of a vector.
*
* @param x The input tensor.
* @param axis The dimension(s) along with to compute mean and
* variance. By default it reduces all dimensions.
* @param keepDims If true, the moments have the same dimensionality as the
* input.
* @return An object with two keys: `mean` and `variance`.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function moments_(x, axis = null, keepDims = false) {
x = convertToTensor(x, 'x', 'moments');
const axes = parseAxisParam(axis, x.shape);
const xMean = mean(x, axes, keepDims);
let keepDimsShape = xMean.shape;
if (!keepDims) {
keepDimsShape = expandShapeToKeepDim(xMean.shape, axes);
}
const devSquared = square(sub(cast(x, 'float32'), reshape(xMean, keepDimsShape)));
const variance = mean(devSquared, axes, keepDims);
return { mean: xMean, variance };
}
const moments = op({ moments_ });
/**
* Computes the next states and outputs of a stack of LSTMCells.
*
* Each cell output is used as input to the next cell.
*
* Returns `[cellState, cellOutput]`.
*
* Derived from tf.contrib.rn.MultiRNNCell.
*
* @param lstmCells Array of LSTMCell functions.
* @param data The input to the cell.
* @param c Array of previous cell states.
* @param h Array of previous cell outputs.
*
* @doc {heading: 'Operations', subheading: 'RNN'}
*/
function multiRNNCell_(lstmCells, data, c, h) {
const $data = convertToTensor(data, 'data', 'multiRNNCell');
const $c = convertToTensorArray(c, 'c', 'multiRNNCell');
const $h = convertToTensorArray(h, 'h', 'multiRNNCell');
let input = $data;
const newStates = [];
for (let i = 0; i < lstmCells.length; i++) {
const output = lstmCells[i](input, $c[i], $h[i]);
newStates.push(output[0]);
newStates.push(output[1]);
input = output[1];
}
const newC = [];
const newH = [];
for (let i = 0; i < newStates.length; i += 2) {
newC.push(newStates[i]);
newH.push(newStates[i + 1]);
}
return [newC, newH];
}
const multiRNNCell = op({ multiRNNCell_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values drawn from a multinomial distribution.
*
* ```js
* const probs = tf.tensor([.75, .25]);
* tf.multinomial(probs, 3).print();
* ```
*
* @param logits 1D array with unnormalized log-probabilities, or
* 2D array of shape `[batchSize, numOutcomes]`. See the `normalized`
* parameter.
* @param numSamples Number of samples to draw for each row slice.
* @param seed The seed number.
* @param normalized Whether the provided `logits` are normalized true
* probabilities (sum to 1). Defaults to false.
* @return 1D array of shape `[numSamples]`, or 2D array of shape
* `[batchSize, numSamples]`, depending on the rank of the input.
*
* @doc {heading: 'Tensors', subheading: 'Random'}
*/
function multinomial_(logits, numSamples, seed, normalized = false) {
const $logits = convertToTensor(logits, 'logits', 'multinomial');
const numOutcomes = $logits.size;
const origRank = $logits.rank;
if (numOutcomes < 2) {
throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ` +
`${numOutcomes}.`);
}
if (origRank > 2) {
throw new Error(`Rank of probabilities must be 1 or 2, but is ${origRank}`);
}
// TODO(lina128): Investigate correct seed behavior. The code seems not allow
// setting see to 0.
seed = seed || Math.random();
// The kernel only accepts (and returns) rank 2 tensors.
const logits2D = origRank === 1 ? reshape($logits, [1, -1]) : $logits;
const inputs = { logits: logits2D };
const attrs = { numSamples, seed, normalized };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(Multinomial, inputs, attrs);
// tslint:disable-next-line:no-unnecessary-type-assertion
return origRank === 1 ? reshape(res, [res.size]) : res;
}
const multinomial = op({ multinomial_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the truth value of (a != b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([0, 2, 3]);
*
* a.notEqual(b).print();
* ```
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function notEqual_(a, b) {
let $a = convertToTensor(a, 'a', 'notEqual');
let $b = convertToTensor(b, 'b', 'notEqual');
[$a, $b] = makeTypesMatch($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(NotEqual, inputs);
}
const notEqual = op({ notEqual_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a one-hot `tf.Tensor`. The locations represented by `indices` take
* value `onValue` (defaults to 1), while all other locations take value
* `offValue` (defaults to 0). If `indices` is rank `R`, the output has rank
* `R+1` with the last axis of size `depth`.
*
* ```js
* tf.oneHot(tf.tensor1d([0, 1], 'int32'), 3).print();
* ```
*
* @param indices `tf.Tensor` of indices with dtype `int32`.
* @param depth The depth of the one hot dimension.
* @param onValue A number used to fill in the output when the index matches
* the location.
* @param offValue A number used to fill in the output when the index does
* not match the location.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function oneHot_(indices, depth, onValue = 1, offValue = 0) {
if (depth < 2) {
throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`);
}
const $indices = convertToTensor(indices, 'indices', 'oneHot', 'int32');
const inputs = { indices: $indices };
const attrs = { depth, onValue, offValue };
return ENGINE.runKernel(OneHot, inputs, attrs);
}
const oneHot = op({ oneHot_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with all elements set to 1 with the same shape as the
* given tensor.
*
* ```js
* const x = tf.tensor([1, 2]);
* tf.onesLike(x).print();
* ```
* @param x A tensor.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function onesLike_(x) {
const $x = convertToTensor(x, 'x', 'onesLike');
const inputs = { x: $x };
return ENGINE.runKernel(OnesLike, inputs);
}
const onesLike = op({ onesLike_ });
/**
* Computes the outer product of two vectors, `v1` and `v2`.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([3, 4, 5]);
*
* tf.outerProduct(a, b).print();
* ```
* @param v1 The first vector in the outer product operation.
* @param v2 The second vector in the outer product operation.
*
* @doc {heading: 'Operations', subheading: 'Matrices'}
*/
function outerProduct_(v1, v2) {
const $v1 = convertToTensor(v1, 'v1', 'outerProduct');
const $v2 = convertToTensor(v2, 'v2', 'outerProduct');
assert($v1.rank === 1 && $v2.rank === 1, () => `Error in outerProduct: inputs must be rank 1, but got ranks ` +
`${$v1.rank} and ${$v2.rank}.`);
const v12D = reshape($v1, [-1, 1]);
const v22D = reshape($v2, [1, -1]);
return matMul(v12D, v22D);
}
const outerProduct = op({ outerProduct_ });
/**
* Pads a `tf.Tensor1D` with a given value and paddings. See `pad` for details.
*/
function pad1d_(x, paddings, constantValue = 0) {
assert(paddings.length === 2, () => 'Invalid number of paddings. Must be length of 2.');
return pad(x, [paddings], constantValue);
}
const pad1d = op({ pad1d_ });
/**
* Pads a `tf.Tensor2D` with a given value and paddings. See `pad` for details.
*/
function pad2d_(x, paddings, constantValue = 0) {
assert(paddings.length === 2 && paddings[0].length === 2 &&
paddings[1].length === 2, () => 'Invalid number of paddings. Must be length of 2 each.');
return pad(x, paddings, constantValue);
}
const pad2d = op({ pad2d_ });
/**
* Pads a `tf.Tensor3D` with a given value and paddings. See `pad` for details.
*/
function pad3d_(x, paddings, constantValue = 0) {
assert(paddings.length === 3 && paddings[0].length === 2 &&
paddings[1].length === 2 && paddings[2].length === 2, () => 'Invalid number of paddings. Must be length of 2 each.');
return pad(x, paddings, constantValue);
}
const pad3d = op({ pad3d_ });
/**
* Pads a `tf.Tensor4D` with a given value and paddings. See `pad` for details.
*/
function pad4d_(x, paddings, constantValue = 0) {
assert(paddings.length === 4 && paddings[0].length === 2 &&
paddings[1].length === 2 && paddings[2].length === 2 &&
paddings[3].length === 2, () => 'Invalid number of paddings. Must be length of 2 each.');
return pad(x, paddings, constantValue);
}
const pad4d = op({ pad4d_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Performs an N-D pooling operation
*
* @param input The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param windowShape The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param poolingType The type of pooling, either 'max' or 'avg'.
* @param pad The type of padding algorithm:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in dilated pooling. Defaults to `[1, 1]`. If `dilationRate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function pool_(input, windowShape, poolingType, pad, dilations, strides) {
if (dilations == null) {
dilations = [1, 1];
}
if (strides == null) {
strides = 1;
}
if (pad === 0) {
pad = 'valid';
}
const $x = convertToTensor(input, 'x', 'maxPool');
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
assert(eitherStridesOrDilationsAreOne(strides, dilations), () => 'Error in pool: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
const convInfo = computePool2DInfo(x4D.shape, windowShape, strides, dilations, pad);
const dilation = [convInfo.dilationHeight, convInfo.dilationWidth];
// The following implementation does batchToSpace(pool(spaceToBatch(x)))
// whenever dilation > 1 since the TF kernels do not support dilation > 1.
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L1037
let basePadding;
if (pad === 'same') {
basePadding = withSpaceToBatchBasePaddings([convInfo.filterHeight, convInfo.filterWidth], dilation);
}
else {
basePadding = [[0, 0], [0, 0]];
}
const isDilationOne = dilation[0] === 1 && dilation[1] === 1;
const [adjustedPadding, adjustedCrops] = requiredSpaceToBatchPaddings([convInfo.inHeight, convInfo.inWidth], dilation, basePadding);
const convertedPad = isDilationOne ? pad : 'valid';
const convertedX = isDilationOne ? x4D : spaceToBatchND(x4D, dilation, adjustedPadding);
const forwardOp = poolingType === 'avg' ?
() => avgPool(convertedX, windowShape, strides, convertedPad) :
() => maxPool(convertedX, windowShape, strides, convertedPad);
const y = forwardOp();
const res = isDilationOne ? y : batchToSpaceND(y, dilation, adjustedCrops);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
// Helper function to compute crops and paddings for pool with dilation > 1.
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/array_ops.py#L2184
function requiredSpaceToBatchPaddings(inputShape, blockShape, basePadding) {
const padStart = basePadding.map(b => b[0]);
const origPadEnd = basePadding.map(b => b[1]);
const fullInputShape = inputShape.concat(padStart, origPadEnd);
const padEndExtra = blockShape.map((b, i) => (b - fullInputShape[i] % b) % b);
const padEnd = origPadEnd.map((s, i) => s + padEndExtra[i]);
const paddings = blockShape.map((_, i) => [padStart[i], padEnd[i]]);
const crops = blockShape.map((_, i) => [0, padEndExtra[i]]);
return [paddings, crops];
}
// Helper function to compute base paddings for pool with dilation > 1.
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L524
function withSpaceToBatchBasePaddings(filterShape, dilation) {
// Spatial dimensions of the filters and the upsampled filters in which we
// introduce (rate - 1) zeros between consecutive filter values.
const dilatedFilterShape = filterShape.map((s, i) => {
return s + (s - 1) * (dilation[i] - 1);
});
const padExtraShape = dilatedFilterShape.map(s => s - 1);
// When padding is odd, we pad more at end, following the same
// convention as conv2d.
const padExtraStart = padExtraShape.map(s => Math.floor(s / 2));
const padExtraEnd = padExtraShape.map((s, i) => s - padExtraStart[i]);
return padExtraShape.map((_, i) => {
return [padExtraStart[i], padExtraEnd[i]];
});
}
const pool = op({ pool_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes leaky rectified linear element-wise with parametric alphas.
*
* `x < 0 ? alpha * x : f(x) = x`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
* const alpha = tf.scalar(0.1);
*
* x.prelu(alpha).print(); // or tf.prelu(x, alpha)
* ```
* @param x The input tensor.
* @param alpha Scaling factor for negative values.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function prelu_(x, alpha) {
const $x = convertToTensor(x, 'x', 'prelu');
const $alpha = convertToTensor(alpha, 'alpha', 'prelu');
const inputs = { x: $x, alpha: $alpha };
return ENGINE.runKernel(Prelu, inputs);
}
const prelu = op({ prelu_ });
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Prints information about the `tf.Tensor` including its data.
*
* ```js
* const verbose = true;
* tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);
* ```
* @param x The tensor to be printed.
* @param verbose Whether to print verbose information about the ` Tensor`,
* including dtype and size.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function print(x, verbose = false) {
console.log(x.toString(verbose));
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the product of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and a
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.prod().print(); // or tf.prod(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.prod(axis).print(); // or tf.prod(x, axis)
* ```
*
* @param x The input tensor to compute the product over. If the dtype is `bool`
* it will be converted to `int32` and the output dtype will be `int32`.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function prod_(x, axis = null, keepDims = false) {
let $x = convertToTensor(x, 'x', 'prod');
if ($x.dtype === 'bool') {
// bool is not an allowed type for the underlying kernel.
$x = cast($x, 'int32');
}
const inputs = { x: $x };
const attrs = { axis, keepDims };
return ENGINE.runKernel(Prod, inputs, attrs);
}
const prod = op({ prod_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a random number generator
* function defined by the user.
*
* @param shape An array of integers defining the output tensor shape.
* @param randFunction A random number generator function which is called
* for each element in the output tensor.
* @param dtype The data type of the output tensor. Defaults to 'float32'.
*
* @doc {heading: 'Tensors', subheading: 'Random'}
*/
function rand_(shape, randFunction, dtype) {
const size = sizeFromShape(shape);
let values = null;
if (dtype == null || dtype === 'float32') {
values = new Float32Array(size);
}
else if (dtype === 'int32') {
values = new Int32Array(size);
}
else if (dtype === 'bool') {
values = new Uint8Array(size);
}
else {
throw new Error(`Unknown data type ${dtype}`);
}
for (let i = 0; i < size; i++) {
values[i] = randFunction();
}
return ENGINE.makeTensor(values, shape, dtype);
}
const rand = op({ rand_ });
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
function getCjsExportFromNamespace (n) {
return n && n['default'] || n;
}
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
}
var alea = createCommonjsModule(function (module) {
// A port of an algorithm by Johannes Baagøe , 2010
// http://baagoe.com/en/RandomMusings/javascript/
// https://github.com/nquinlan/better-random-numbers-for-javascript-mirror
// Original work is under MIT license -
// Copyright (C) 2010 by Johannes Baagøe
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
(function(global, module, define) {
function Alea(seed) {
var me = this, mash = Mash();
me.next = function() {
var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32
me.s0 = me.s1;
me.s1 = me.s2;
return me.s2 = t - (me.c = t | 0);
};
// Apply the seeding algorithm from Baagoe.
me.c = 1;
me.s0 = mash(' ');
me.s1 = mash(' ');
me.s2 = mash(' ');
me.s0 -= mash(seed);
if (me.s0 < 0) { me.s0 += 1; }
me.s1 -= mash(seed);
if (me.s1 < 0) { me.s1 += 1; }
me.s2 -= mash(seed);
if (me.s2 < 0) { me.s2 += 1; }
mash = null;
}
function copy(f, t) {
t.c = f.c;
t.s0 = f.s0;
t.s1 = f.s1;
t.s2 = f.s2;
return t;
}
function impl(seed, opts) {
var xg = new Alea(seed),
state = opts && opts.state,
prng = xg.next;
prng.int32 = function() { return (xg.next() * 0x100000000) | 0; };
prng.double = function() {
return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
};
prng.quick = prng;
if (state) {
if (typeof(state) == 'object') copy(state, xg);
prng.state = function() { return copy(xg, {}); };
}
return prng;
}
function Mash() {
var n = 0xefc8249d;
var mash = function(data) {
data = data.toString();
for (var i = 0; i < data.length; i++) {
n += data.charCodeAt(i);
var h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000; // 2^32
}
return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
};
return mash;
}
if (module && module.exports) {
module.exports = impl;
} else if (define && define.amd) {
define(function() { return impl; });
} else {
this.alea = impl;
}
})(
commonjsGlobal,
true && module, // present in node.js
false && false // present with an AMD loader
);
});
var xor128 = createCommonjsModule(function (module) {
// A Javascript implementaion of the "xor128" prng algorithm by
// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper
(function(global, module, define) {
function XorGen(seed) {
var me = this, strseed = '';
me.x = 0;
me.y = 0;
me.z = 0;
me.w = 0;
// Set up generator function.
me.next = function() {
var t = me.x ^ (me.x << 11);
me.x = me.y;
me.y = me.z;
me.z = me.w;
return me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8);
};
if (seed === (seed | 0)) {
// Integer seed.
me.x = seed;
} else {
// String seed.
strseed += seed;
}
// Mix in string seed, then discard an initial batch of 64 values.
for (var k = 0; k < strseed.length + 64; k++) {
me.x ^= strseed.charCodeAt(k) | 0;
me.next();
}
}
function copy(f, t) {
t.x = f.x;
t.y = f.y;
t.z = f.z;
t.w = f.w;
return t;
}
function impl(seed, opts) {
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function() { return (xg.next() >>> 0) / 0x100000000; };
prng.double = function() {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (typeof(state) == 'object') copy(state, xg);
prng.state = function() { return copy(xg, {}); };
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (define && define.amd) {
define(function() { return impl; });
} else {
this.xor128 = impl;
}
})(
commonjsGlobal,
true && module, // present in node.js
false && false // present with an AMD loader
);
});
var xorwow = createCommonjsModule(function (module) {
// A Javascript implementaion of the "xorwow" prng algorithm by
// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper
(function(global, module, define) {
function XorGen(seed) {
var me = this, strseed = '';
// Set up generator function.
me.next = function() {
var t = (me.x ^ (me.x >>> 2));
me.x = me.y; me.y = me.z; me.z = me.w; me.w = me.v;
return (me.d = (me.d + 362437 | 0)) +
(me.v = (me.v ^ (me.v << 4)) ^ (t ^ (t << 1))) | 0;
};
me.x = 0;
me.y = 0;
me.z = 0;
me.w = 0;
me.v = 0;
if (seed === (seed | 0)) {
// Integer seed.
me.x = seed;
} else {
// String seed.
strseed += seed;
}
// Mix in string seed, then discard an initial batch of 64 values.
for (var k = 0; k < strseed.length + 64; k++) {
me.x ^= strseed.charCodeAt(k) | 0;
if (k == strseed.length) {
me.d = me.x << 10 ^ me.x >>> 4;
}
me.next();
}
}
function copy(f, t) {
t.x = f.x;
t.y = f.y;
t.z = f.z;
t.w = f.w;
t.v = f.v;
t.d = f.d;
return t;
}
function impl(seed, opts) {
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function() { return (xg.next() >>> 0) / 0x100000000; };
prng.double = function() {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (typeof(state) == 'object') copy(state, xg);
prng.state = function() { return copy(xg, {}); };
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (define && define.amd) {
define(function() { return impl; });
} else {
this.xorwow = impl;
}
})(
commonjsGlobal,
true && module, // present in node.js
false && false // present with an AMD loader
);
});
var xorshift7 = createCommonjsModule(function (module) {
// A Javascript implementaion of the "xorshift7" algorithm by
// François Panneton and Pierre L'ecuyer:
// "On the Xorgshift Random Number Generators"
// http://saluc.engr.uconn.edu/refs/crypto/rng/panneton05onthexorshift.pdf
(function(global, module, define) {
function XorGen(seed) {
var me = this;
// Set up generator function.
me.next = function() {
// Update xor generator.
var X = me.x, i = me.i, t, v, w;
t = X[i]; t ^= (t >>> 7); v = t ^ (t << 24);
t = X[(i + 1) & 7]; v ^= t ^ (t >>> 10);
t = X[(i + 3) & 7]; v ^= t ^ (t >>> 3);
t = X[(i + 4) & 7]; v ^= t ^ (t << 7);
t = X[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);
X[i] = v;
me.i = (i + 1) & 7;
return v;
};
function init(me, seed) {
var j, w, X = [];
if (seed === (seed | 0)) {
// Seed state array using a 32-bit integer.
w = X[0] = seed;
} else {
// Seed state using a string.
seed = '' + seed;
for (j = 0; j < seed.length; ++j) {
X[j & 7] = (X[j & 7] << 15) ^
(seed.charCodeAt(j) + X[(j + 1) & 7] << 13);
}
}
// Enforce an array length of 8, not all zeroes.
while (X.length < 8) X.push(0);
for (j = 0; j < 8 && X[j] === 0; ++j);
if (j == 8) w = X[7] = -1; else w = X[j];
me.x = X;
me.i = 0;
// Discard an initial 256 values.
for (j = 256; j > 0; --j) {
me.next();
}
}
init(me, seed);
}
function copy(f, t) {
t.x = f.x.slice();
t.i = f.i;
return t;
}
function impl(seed, opts) {
if (seed == null) seed = +(new Date);
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function() { return (xg.next() >>> 0) / 0x100000000; };
prng.double = function() {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (state.x) copy(state, xg);
prng.state = function() { return copy(xg, {}); };
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (define && define.amd) {
define(function() { return impl; });
} else {
this.xorshift7 = impl;
}
})(
commonjsGlobal,
true && module, // present in node.js
false && false // present with an AMD loader
);
});
var xor4096 = createCommonjsModule(function (module) {
// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.
//
// This fast non-cryptographic random number generator is designed for
// use in Monte-Carlo algorithms. It combines a long-period xorshift
// generator with a Weyl generator, and it passes all common batteries
// of stasticial tests for randomness while consuming only a few nanoseconds
// for each prng generated. For background on the generator, see Brent's
// paper: "Some long-period random number generators using shifts and xors."
// http://arxiv.org/pdf/1004.3115v1.pdf
//
// Usage:
//
// var xor4096 = require('xor4096');
// random = xor4096(1); // Seed with int32 or string.
// assert.equal(random(), 0.1520436450538547); // (0, 1) range, 53 bits.
// assert.equal(random.int32(), 1806534897); // signed int32, 32 bits.
//
// For nonzero numeric keys, this impelementation provides a sequence
// identical to that by Brent's xorgens 3 implementaion in C. This
// implementation also provides for initalizing the generator with
// string seeds, or for saving and restoring the state of the generator.
//
// On Chrome, this prng benchmarks about 2.1 times slower than
// Javascript's built-in Math.random().
(function(global, module, define) {
function XorGen(seed) {
var me = this;
// Set up generator function.
me.next = function() {
var w = me.w,
X = me.X, i = me.i, t, v;
// Update Weyl generator.
me.w = w = (w + 0x61c88647) | 0;
// Update xor generator.
v = X[(i + 34) & 127];
t = X[i = ((i + 1) & 127)];
v ^= v << 13;
t ^= t << 17;
v ^= v >>> 15;
t ^= t >>> 12;
// Update Xor generator array state.
v = X[i] = v ^ t;
me.i = i;
// Result is the combination.
return (v + (w ^ (w >>> 16))) | 0;
};
function init(me, seed) {
var t, v, i, j, w, X = [], limit = 128;
if (seed === (seed | 0)) {
// Numeric seeds initialize v, which is used to generates X.
v = seed;
seed = null;
} else {
// String seeds are mixed into v and X one character at a time.
seed = seed + '\0';
v = 0;
limit = Math.max(limit, seed.length);
}
// Initialize circular array and weyl value.
for (i = 0, j = -32; j < limit; ++j) {
// Put the unicode characters into the array, and shuffle them.
if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);
// After 32 shuffles, take v as the starting w value.
if (j === 0) w = v;
v ^= v << 10;
v ^= v >>> 15;
v ^= v << 4;
v ^= v >>> 13;
if (j >= 0) {
w = (w + 0x61c88647) | 0; // Weyl.
t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.
i = (0 == t) ? i + 1 : 0; // Count zeroes.
}
}
// We have detected all zeroes; make the key nonzero.
if (i >= 128) {
X[(seed && seed.length || 0) & 127] = -1;
}
// Run the generator 512 times to further mix the state before using it.
// Factoring this as a function slows the main generator, so it is just
// unrolled here. The weyl generator is not advanced while warming up.
i = 127;
for (j = 4 * 128; j > 0; --j) {
v = X[(i + 34) & 127];
t = X[i = ((i + 1) & 127)];
v ^= v << 13;
t ^= t << 17;
v ^= v >>> 15;
t ^= t >>> 12;
X[i] = v ^ t;
}
// Storing state as object members is faster than using closure variables.
me.w = w;
me.X = X;
me.i = i;
}
init(me, seed);
}
function copy(f, t) {
t.i = f.i;
t.w = f.w;
t.X = f.X.slice();
return t;
};
function impl(seed, opts) {
if (seed == null) seed = +(new Date);
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function() { return (xg.next() >>> 0) / 0x100000000; };
prng.double = function() {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (state.X) copy(state, xg);
prng.state = function() { return copy(xg, {}); };
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (define && define.amd) {
define(function() { return impl; });
} else {
this.xor4096 = impl;
}
})(
commonjsGlobal, // window object or global
true && module, // present in node.js
false && false // present with an AMD loader
);
});
var tychei = createCommonjsModule(function (module) {
// A Javascript implementaion of the "Tyche-i" prng algorithm by
// Samuel Neves and Filipe Araujo.
// See https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf
(function(global, module, define) {
function XorGen(seed) {
var me = this, strseed = '';
// Set up generator function.
me.next = function() {
var b = me.b, c = me.c, d = me.d, a = me.a;
b = (b << 25) ^ (b >>> 7) ^ c;
c = (c - d) | 0;
d = (d << 24) ^ (d >>> 8) ^ a;
a = (a - b) | 0;
me.b = b = (b << 20) ^ (b >>> 12) ^ c;
me.c = c = (c - d) | 0;
me.d = (d << 16) ^ (c >>> 16) ^ a;
return me.a = (a - b) | 0;
};
/* The following is non-inverted tyche, which has better internal
* bit diffusion, but which is about 25% slower than tyche-i in JS.
me.next = function() {
var a = me.a, b = me.b, c = me.c, d = me.d;
a = (me.a + me.b | 0) >>> 0;
d = me.d ^ a; d = d << 16 ^ d >>> 16;
c = me.c + d | 0;
b = me.b ^ c; b = b << 12 ^ d >>> 20;
me.a = a = a + b | 0;
d = d ^ a; me.d = d = d << 8 ^ d >>> 24;
me.c = c = c + d | 0;
b = b ^ c;
return me.b = (b << 7 ^ b >>> 25);
}
*/
me.a = 0;
me.b = 0;
me.c = 2654435769 | 0;
me.d = 1367130551;
if (seed === Math.floor(seed)) {
// Integer seed.
me.a = (seed / 0x100000000) | 0;
me.b = seed | 0;
} else {
// String seed.
strseed += seed;
}
// Mix in string seed, then discard an initial batch of 64 values.
for (var k = 0; k < strseed.length + 20; k++) {
me.b ^= strseed.charCodeAt(k) | 0;
me.next();
}
}
function copy(f, t) {
t.a = f.a;
t.b = f.b;
t.c = f.c;
t.d = f.d;
return t;
};
function impl(seed, opts) {
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function() { return (xg.next() >>> 0) / 0x100000000; };
prng.double = function() {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (typeof(state) == 'object') copy(state, xg);
prng.state = function() { return copy(xg, {}); };
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (define && define.amd) {
define(function() { return impl; });
} else {
this.tychei = impl;
}
})(
commonjsGlobal,
true && module, // present in node.js
false && false // present with an AMD loader
);
});
var seedrandom = createCommonjsModule(function (module) {
/*
Copyright 2014 David Bau.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function (pool, math) {
//
// The following constants are related to IEEE 754 limits.
//
var global = this,
width = 256, // each RC4 output is 0 <= x < 256
chunks = 6, // at least six RC4 outputs for each double
digits = 52, // there are 52 significant digits in a double
rngname = 'random', // rngname: name for Math.random and Math.seedrandom
startdenom = math.pow(width, chunks),
significance = math.pow(2, digits),
overflow = significance * 2,
mask = width - 1,
nodecrypto; // node.js crypto module, initialized at the bottom.
//
// seedrandom()
// This is the seedrandom function described above.
//
function seedrandom(seed, options, callback) {
var key = [];
options = (options == true) ? { entropy: true } : (options || {});
// Flatten the seed string or build one from local entropy if needed.
var shortseed = mixkey(flatten(
options.entropy ? [seed, tostring(pool)] :
(seed == null) ? autoseed() : seed, 3), key);
// Use the seed to initialize an ARC4 generator.
var arc4 = new ARC4(key);
// This function returns a random double in [0, 1) that contains
// randomness in every bit of the mantissa of the IEEE 754 value.
var prng = function() {
var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
d = startdenom, // and denominator d = 2 ^ 48.
x = 0; // and no 'extra last byte'.
while (n < significance) { // Fill up all significant digits by
n = (n + x) * width; // shifting numerator and
d *= width; // denominator and generating a
x = arc4.g(1); // new least-significant-byte.
}
while (n >= overflow) { // To avoid rounding up, before adding
n /= 2; // last byte, shift everything
d /= 2; // right using integer math until
x >>>= 1; // we have exactly the desired bits.
}
return (n + x) / d; // Form the number within [0, 1).
};
prng.int32 = function() { return arc4.g(4) | 0; };
prng.quick = function() { return arc4.g(4) / 0x100000000; };
prng.double = prng;
// Mix the randomness into accumulated entropy.
mixkey(tostring(arc4.S), pool);
// Calling convention: what to return as a function of prng, seed, is_math.
return (options.pass || callback ||
function(prng, seed, is_math_call, state) {
if (state) {
// Load the arc4 state from the given state if it has an S array.
if (state.S) { copy(state, arc4); }
// Only provide the .state method if requested via options.state.
prng.state = function() { return copy(arc4, {}); };
}
// If called as a method of Math (Math.seedrandom()), mutate
// Math.random because that is how seedrandom.js has worked since v1.0.
if (is_math_call) { math[rngname] = prng; return seed; }
// Otherwise, it is a newer calling convention, so return the
// prng directly.
else return prng;
})(
prng,
shortseed,
'global' in options ? options.global : (this == math),
options.state);
}
math['seed' + rngname] = seedrandom;
//
// ARC4
//
// An ARC4 implementation. The constructor takes a key in the form of
// an array of at most (width) integers that should be 0 <= x < (width).
//
// The g(count) method returns a pseudorandom integer that concatenates
// the next (count) outputs from ARC4. Its return value is a number x
// that is in the range 0 <= x < (width ^ count).
//
function ARC4(key) {
var t, keylen = key.length,
me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
// The empty key [] is treated as [0].
if (!keylen) { key = [keylen++]; }
// Set up S using the standard key scheduling algorithm.
while (i < width) {
s[i] = i++;
}
for (i = 0; i < width; i++) {
s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
s[j] = t;
}
// The "g" method returns the next (count) outputs as one number.
(me.g = function(count) {
// Using instance members instead of closure state nearly doubles speed.
var t, r = 0,
i = me.i, j = me.j, s = me.S;
while (count--) {
t = s[i = mask & (i + 1)];
r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
}
me.i = i; me.j = j;
return r;
// For robust unpredictability, the function call below automatically
// discards an initial batch of values. This is called RC4-drop[256].
// See http://google.com/search?q=rsa+fluhrer+response&btnI
})(width);
}
//
// copy()
// Copies internal state of ARC4 to or from a plain object.
//
function copy(f, t) {
t.i = f.i;
t.j = f.j;
t.S = f.S.slice();
return t;
};
//
// flatten()
// Converts an object tree to nested arrays of strings.
//
function flatten(obj, depth) {
var result = [], typ = (typeof obj), prop;
if (depth && typ == 'object') {
for (prop in obj) {
try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
}
}
return (result.length ? result : typ == 'string' ? obj : obj + '\0');
}
//
// mixkey()
// Mixes a string seed into a key that is an array of integers, and
// returns a shortened string seed that is equivalent to the result key.
//
function mixkey(seed, key) {
var stringseed = seed + '', smear, j = 0;
while (j < stringseed.length) {
key[mask & j] =
mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
}
return tostring(key);
}
//
// autoseed()
// Returns an object for autoseeding, using window.crypto and Node crypto
// module if available.
//
function autoseed() {
try {
var out;
if (nodecrypto && (out = nodecrypto.randomBytes)) {
// The use of 'out' to remember randomBytes makes tight minified code.
out = out(width);
} else {
out = new Uint8Array(width);
(global.crypto || global.msCrypto).getRandomValues(out);
}
return tostring(out);
} catch (e) {
var browser = global.navigator,
plugins = browser && browser.plugins;
return [+new Date, global, plugins, global.screen, tostring(pool)];
}
}
//
// tostring()
// Converts an array of charcodes to a string
//
function tostring(a) {
return String.fromCharCode.apply(0, a);
}
//
// When seedrandom.js is loaded, we immediately mix a few bits
// from the built-in RNG into the entropy pool. Because we do
// not want to interfere with deterministic PRNG state later,
// seedrandom will not call math.random on its own again after
// initialization.
//
mixkey(math.random(), pool);
//
// Nodejs and AMD support: export the implementation as a module using
// either convention.
//
if ( true && module.exports) {
module.exports = seedrandom;
// When in node.js, try using crypto package for autoseeding.
try {
nodecrypto = __webpack_require__(293);
} catch (ex) {}
} else if (false) {}
// End anonymous scope, and pass initial values.
})(
[], // pool: entropy pool starts empty
Math // math: package containing random, pow, and seedrandom
);
});
// A library of seedable RNGs implemented in Javascript.
//
// Usage:
//
// var seedrandom = require('seedrandom');
// var random = seedrandom(1); // or any seed.
// var x = random(); // 0 <= x < 1. Every bit is random.
// var x = random.quick(); // 0 <= x < 1. 32 bits of randomness.
// alea, a 53-bit multiply-with-carry generator by Johannes Baagøe.
// Period: ~2^116
// Reported to pass all BigCrush tests.
// xor128, a pure xor-shift generator by George Marsaglia.
// Period: 2^128-1.
// Reported to fail: MatrixRank and LinearComp.
// xorwow, George Marsaglia's 160-bit xor-shift combined plus weyl.
// Period: 2^192-2^32
// Reported to fail: CollisionOver, SimpPoker, and LinearComp.
// xorshift7, by François Panneton and Pierre L'ecuyer, takes
// a different approach: it adds robustness by allowing more shifts
// than Marsaglia's original three. It is a 7-shift generator
// with 256 bits, that passes BigCrush with no systmatic failures.
// Period 2^256-1.
// No systematic BigCrush failures reported.
// xor4096, by Richard Brent, is a 4096-bit xor-shift with a
// very long period that also adds a Weyl generator. It also passes
// BigCrush with no systematic failures. Its long period may
// be useful if you have many generators and need to avoid
// collisions.
// Period: 2^4128-2^32.
// No systematic BigCrush failures reported.
// Tyche-i, by Samuel Neves and Filipe Araujo, is a bit-shifting random
// number generator derived from ChaCha, a modern stream cipher.
// https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf
// Period: ~2^127
// No systematic BigCrush failures reported.
// The original ARC4-based prng included in this library.
// Period: ~2^1600
seedrandom.alea = alea;
seedrandom.xor128 = xor128;
seedrandom.xorwow = xorwow;
seedrandom.xorshift7 = xorshift7;
seedrandom.xor4096 = xor4096;
seedrandom.tychei = tychei;
var seedrandom$1 = seedrandom;
var seedrandom_1 = seedrandom$1.alea;
/**
* @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 TEST_EPSILON_FLOAT32 = 1e-3;
const TEST_EPSILON_FLOAT16 = 1e-1;
function expectArraysClose(actual, expected, epsilon) {
if (epsilon == null) {
epsilon = testEpsilon();
}
return expectArraysPredicate(actual, expected, (a, b) => areClose(a, b, epsilon));
}
function testEpsilon() {
return ENGINE.backend.floatPrecision() === 32 ? TEST_EPSILON_FLOAT32 :
TEST_EPSILON_FLOAT16;
}
function expectArraysPredicate(actual, expected, predicate) {
let checkClassType = true;
if (isTypedArray(actual) || isTypedArray(expected)) {
checkClassType = false;
}
if (isTypedArray(actual) && isTypedArray(expected)) {
checkClassType = true;
}
if (checkClassType) {
const aType = actual.constructor.name;
const bType = expected.constructor.name;
if (aType !== bType) {
throw new Error(`Arrays are of different type. Actual: ${aType}. ` +
`Expected: ${bType}`);
}
}
if (Array.isArray(actual) && Array.isArray(expected)) {
const actualShape = inferShape(actual);
const expectedShape = inferShape(expected);
if (!arraysEqual(actualShape, expectedShape)) {
throw new Error(`Arrays have different shapes. ` +
`Actual: [${actualShape}]. Expected: [${expectedShape}]`);
}
}
const actualFlat = isTypedArray(actual) ? actual : flatten(actual);
const expectedFlat = isTypedArray(expected) ?
expected :
flatten(expected);
if (actualFlat.length !== expectedFlat.length) {
throw new Error(`Arrays have different lengths actual: ${actualFlat.length} vs ` +
`expected: ${expectedFlat.length}.\n` +
`Actual: ${actualFlat}.\n` +
`Expected: ${expectedFlat}.`);
}
for (let i = 0; i < expectedFlat.length; ++i) {
const a = actualFlat[i];
const e = expectedFlat[i];
if (!predicate(a, e)) {
throw new Error(`Arrays differ: actual[${i}] = ${a}, expected[${i}] = ${e}.\n` +
`Actual: ${actualFlat}.\n` +
`Expected: ${expectedFlat}.`);
}
}
}
function expectPromiseToFail(fn, done) {
fn().then(() => done.fail(), () => done());
}
function expectArraysEqual(actual, expected) {
const exp = typeof expected === 'string' || typeof expected === 'number' ||
typeof expected === 'boolean' ?
[expected] :
expected;
if (isString(actual) || isString(actual[0]) ||
isString(expected) || isString(expected[0])) {
// tslint:disable-next-line: triple-equals
return expectArraysPredicate(actual, exp, (a, b) => a == b);
}
return expectArraysPredicate(actual, expected, (a, b) => areClose(a, b, 0));
}
function expectNumbersClose(a, e, epsilon) {
if (epsilon == null) {
epsilon = testEpsilon();
}
if (!areClose(a, e, epsilon)) {
throw new Error(`Numbers differ: actual === ${a}, expected === ${e}`);
}
}
function areClose(a, e, epsilon) {
if (!isFinite(a) && !isFinite(e)) {
return true;
}
if (isNaN(a) || isNaN(e) || Math.abs(a - e) > epsilon) {
return false;
}
return true;
}
function expectValuesInRange(actual, low, high) {
for (let i = 0; i < actual.length; i++) {
if (actual[i] < low || actual[i] > high) {
throw new Error(`Value out of range:${actual[i]} low: ${low}, high: ${high}`);
}
}
}
function expectArrayBuffersEqual(actual, expected) {
// Safari & Jasmine don't like comparing ArrayBuffers directly. Wrapping in
// a Float32Array solves this issue.
expect(new Float32Array(actual)).toEqual(new Float32Array(expected));
}
/** Encodes strings into utf-8 bytes. */
function encodeStrings(a) {
for (let i = 0; i < a.length; i++) {
const val = a[i];
if (Array.isArray(val)) {
encodeStrings(val);
}
else {
a[i] = encodeString(val);
}
}
return 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.
* =============================================================================
*/
// https://en.wikipedia.org/wiki/Marsaglia_polar_method
class MPRandGauss {
constructor(mean, stdDeviation, dtype, truncated, seed) {
this.mean = mean;
this.stdDev = stdDeviation;
this.dtype = dtype;
this.nextVal = NaN;
this.truncated = truncated;
if (this.truncated) {
this.upper = this.mean + this.stdDev * 2;
this.lower = this.mean - this.stdDev * 2;
}
const seedValue = seed ? seed : Math.random();
this.random = seedrandom_1(seedValue.toString());
}
/** Returns next sample from a Gaussian distribution. */
nextValue() {
if (!isNaN(this.nextVal)) {
const value = this.nextVal;
this.nextVal = NaN;
return value;
}
let resultX, resultY;
let isValid = false;
while (!isValid) {
let v1, v2, s;
do {
v1 = 2 * this.random() - 1;
v2 = 2 * this.random() - 1;
s = v1 * v1 + v2 * v2;
} while (s >= 1 || s === 0);
const mul = Math.sqrt(-2.0 * Math.log(s) / s);
resultX = this.mean + this.stdDev * v1 * mul;
resultY = this.mean + this.stdDev * v2 * mul;
if (!this.truncated || this.isValidTruncated(resultX)) {
isValid = true;
}
}
if (!this.truncated || this.isValidTruncated(resultY)) {
this.nextVal = this.convertValue(resultY);
}
return this.convertValue(resultX);
}
/** Handles proper rounding for non-floating-point numbers. */
convertValue(value) {
if (this.dtype == null || this.dtype === 'float32') {
return value;
}
return Math.round(value);
}
/** Returns true if less than 2-standard-deviations from the mean. */
isValidTruncated(value) {
return value <= this.upper && value >= this.lower;
}
}
// Marsaglia, George, and Wai Wan Tsang. 2000. "A Simple Method for Generating
// Gamma Variables."
class RandGamma {
constructor(alpha, beta, dtype, seed) {
this.alpha = alpha;
this.beta = 1 / beta; // convert rate to scale parameter
this.dtype = dtype;
const seedValue = seed ? seed : Math.random();
this.randu = seedrandom_1(seedValue.toString());
this.randn = new MPRandGauss(0, 1, dtype, false, this.randu());
if (alpha < 1) {
this.d = alpha + (2 / 3);
}
else {
this.d = alpha - (1 / 3);
}
this.c = 1 / Math.sqrt(9 * this.d);
}
/** Returns next sample from a gamma distribution. */
nextValue() {
let x2, v0, v1, x, u, v;
while (true) {
do {
x = this.randn.nextValue();
v = 1 + (this.c * x);
} while (v <= 0);
v *= v * v;
x2 = x * x;
v0 = 1 - (0.331 * x2 * x2);
v1 = (0.5 * x2) + (this.d * (1 - v + Math.log(v)));
u = this.randu();
if (u < v0 || Math.log(u) < v1) {
break;
}
}
v = (1 / this.beta) * this.d * v;
if (this.alpha < 1) {
v *= Math.pow(this.randu(), 1 / this.alpha);
}
return this.convertValue(v);
}
/** Handles proper rounding for non-floating-point numbers. */
convertValue(value) {
if (this.dtype === 'float32') {
return value;
}
return Math.round(value);
}
}
class UniformRandom {
constructor(min = 0, max = 1, dtype, seed) {
/** Handles proper rounding for non floating point numbers. */
this.canReturnFloat = () => (this.dtype == null || this.dtype === 'float32');
this.min = min;
this.range = max - min;
this.dtype = dtype;
if (seed == null) {
seed = Math.random();
}
if (typeof seed === 'number') {
seed = seed.toString();
}
if (!this.canReturnFloat() && this.range <= 1) {
throw new Error(`The difference between ${min} - ${max} <= 1 and dtype is not float`);
}
this.random = seedrandom_1(seed);
}
convertValue(value) {
if (this.canReturnFloat()) {
return value;
}
return Math.round(value);
}
nextValue() {
return this.convertValue(this.min + this.range * this.random());
}
}
function jarqueBeraNormalityTest(values) {
// https://en.wikipedia.org/wiki/Jarque%E2%80%93Bera_test
const n = values.length;
const s = skewness(values);
const k = kurtosis(values);
const jb = n / 6 * (Math.pow(s, 2) + 0.25 * Math.pow(k - 3, 2));
// JB test requires 2-degress of freedom from Chi-Square @ 0.95:
// http://www.itl.nist.gov/div898/handbook/eda/section3/eda3674.htm
const CHI_SQUARE_2DEG = 5.991;
if (jb > CHI_SQUARE_2DEG) {
throw new Error(`Invalid p-value for JB: ${jb}`);
}
}
function expectArrayInMeanStdRange(actual, expectedMean, expectedStdDev, epsilon) {
if (epsilon == null) {
epsilon = testEpsilon();
}
const actualMean = mean$1(actual);
expectNumbersClose(actualMean, expectedMean, epsilon);
expectNumbersClose(standardDeviation(actual, actualMean), expectedStdDev, epsilon);
}
function mean$1(values) {
let sum = 0;
for (let i = 0; i < values.length; i++) {
sum += values[i];
}
return sum / values.length;
}
function standardDeviation(values, mean) {
let squareDiffSum = 0;
for (let i = 0; i < values.length; i++) {
const diff = values[i] - mean;
squareDiffSum += diff * diff;
}
return Math.sqrt(squareDiffSum / values.length);
}
function kurtosis(values) {
// https://en.wikipedia.org/wiki/Kurtosis
const valuesMean = mean$1(values);
const n = values.length;
let sum2 = 0;
let sum4 = 0;
for (let i = 0; i < n; i++) {
const v = values[i] - valuesMean;
sum2 += Math.pow(v, 2);
sum4 += Math.pow(v, 4);
}
return (1 / n) * sum4 / Math.pow((1 / n) * sum2, 2);
}
function skewness(values) {
// https://en.wikipedia.org/wiki/Skewness
const valuesMean = mean$1(values);
const n = values.length;
let sum2 = 0;
let sum3 = 0;
for (let i = 0; i < n; i++) {
const v = values[i] - valuesMean;
sum2 += Math.pow(v, 2);
sum3 += Math.pow(v, 3);
}
return (1 / n) * sum3 / Math.pow((1 / (n - 1)) * sum2, 3 / 2);
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a gamma distribution.
*
* ```js
* tf.randomGamma([2, 2], 1).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param alpha The shape parameter of the gamma distribution.
* @param beta The inverse scale parameter of the gamma distribution. Defaults
* to 1.
* @param dtype The data type of the output. Defaults to float32.
* @param seed The seed for the random number generator.
*
* @doc {heading: 'Tensors', subheading: 'Random'}
*/
function randomGamma_(shape, alpha, beta = 1, dtype = 'float32', seed) {
if (beta == null) {
beta = 1;
}
if (dtype == null) {
dtype = 'float32';
}
if (dtype !== 'float32' && dtype !== 'int32') {
throw new Error(`Unsupported data type ${dtype}`);
}
const rgamma = new RandGamma(alpha, beta, dtype, seed);
const res = buffer(shape, dtype);
for (let i = 0; i < res.values.length; i++) {
res.values[i] = rgamma.nextValue();
}
return res.toTensor();
}
const randomGamma = op({ randomGamma_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a normal distribution.
*
* ```js
* tf.randomNormal([2, 2]).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param mean The mean of the normal distribution.
* @param stdDev The standard deviation of the normal distribution.
* @param dtype The data type of the output.
* @param seed The seed for the random number generator.
*
* @doc {heading: 'Tensors', subheading: 'Random'}
*/
function randomNormal_(shape, mean = 0, stdDev = 1, dtype, seed) {
if (dtype != null && dtype === 'bool') {
throw new Error(`Unsupported data type ${dtype}`);
}
const randGauss = new MPRandGauss(mean, stdDev, dtype, false /* truncated */, seed);
const res = buffer(shape, dtype);
for (let i = 0; i < res.values.length; i++) {
res.values[i] = randGauss.nextValue();
}
return res.toTensor();
}
const randomNormal = op({ randomNormal_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a uniform distribution.
*
* The generated values follow a uniform distribution in the range [minval,
* maxval). The lower bound minval is included in the range, while the upper
* bound maxval is excluded.
*
* ```js
* tf.randomUniform([2, 2]).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param minval The lower bound on the range of random values to generate.
* Defaults to 0.
* @param maxval The upper bound on the range of random values to generate.
* Defaults to 1.
* @param dtype The data type of the output tensor. Defaults to 'float32'.
*
* @doc {heading: 'Tensors', subheading: 'Random'}
*/
function randomUniform_(shape, minval = 0, maxval = 1, dtype = 'float32', seed) {
const res = buffer(shape, dtype);
const random = new UniformRandom(minval, maxval, null, seed);
for (let i = 0; i < res.values.length; i++) {
res.values[i] = random.nextValue();
}
return res.toTensor();
}
const randomUniform = op({ randomUniform_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a new `tf.Tensor1D` filled with the numbers in the range provided.
*
* The tensor is a is half-open interval meaning it includes start, but
* excludes stop. Decrementing ranges and negative step values are also
* supported.sv
*
*
* ```js
* tf.range(0, 9, 2).print();
* ```
*
* @param start An integer start value
* @param stop An integer stop value
* @param step An integer increment (will default to 1 or -1)
* @param dtype The data type of the output tensor. Defaults to 'float32'.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function range(start, stop, step = 1, dtype = 'float32') {
if (step === 0) {
throw new Error('Cannot have a step of zero');
}
const attrs = { start, stop, step, dtype };
return ENGINE.runKernel(Range, {} /* inputs */, attrs);
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the real part of a complex (or real) tensor.
*
* Given a tensor input, this operation returns a tensor of type float that is
* the real part of each element in input considered as a complex number.
*
* If the input is real, it simply makes a clone.
*
* ```js
* const x = tf.complex([-2.25, 3.25], [4.75, 5.75]);
* tf.real(x).print();
* ```
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function real_(input) {
const $input = convertToTensor(input, 'input', 'real');
const inputs = { input: $input };
return ENGINE.runKernel(Real, inputs);
}
const real = op({ real_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes reciprocal of x element-wise: `1 / x`
*
* ```js
* const x = tf.tensor1d([0, 1, 2]);
*
* x.reciprocal().print(); // or tf.reciprocal(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function reciprocal_(x) {
const $x = convertToTensor(x, 'x', 'reciprocal');
const inputs = { x: $x };
return ENGINE.runKernel(Reciprocal, inputs);
}
const reciprocal = op({ reciprocal_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes rectified linear element-wise: `max(x, 0)`.
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.relu().print(); // or tf.relu(x)
* ```
* @param x The input tensor. If the dtype is `bool`, the output dtype will be
* `int32'.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function relu_(x) {
const $x = convertToTensor(x, 'x', 'relu');
const inputs = { x: $x };
return ENGINE.runKernel(Relu, inputs);
}
const relu = op({ relu_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes rectified linear 6 element-wise: `min(max(x, 0), 6)`.
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 8]);
*
* x.relu6().print(); // or tf.relu6(x)
* ```
* @param x The input tensor. If the dtype is `bool`, the output dtype will be
* `int32'.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function relu6_(x) {
const $x = convertToTensor(x, 'x', 'relu6');
const inputs = { x: $x };
return ENGINE.runKernel(Relu6, inputs);
}
const relu6 = op({ relu6_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Reverses a `tf.Tensor1D`.
*
* @param x The input tensor.
*/
function reverse1d_(x) {
const $x = convertToTensor(x, 'x', 'reverse');
assert($x.rank === 1, () => `Error in reverse1D: x must be rank 1 but got rank ${$x.rank}.`);
return reverse($x, 0);
}
const reverse1d = op({ reverse1d_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Reverses a `tf.Tensor2D` along a specified axis.
*
* @param x The input tensor.
* @param axis The set of dimensions to reverse. Must be in the
* range [-rank(x), rank(x)). Defaults to all axes.
*/
function reverse2d_(x, axis) {
const $x = convertToTensor(x, 'x', 'reverse');
assert($x.rank === 2, () => `Error in reverse2D: x must be rank 2 but got rank ${$x.rank}.`);
return reverse($x, axis);
}
const reverse2d = op({ reverse2d_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Reverses a `tf.Tensor3D` along a specified axis.
*
* @param x The input tensor.
* @param axis The set of dimensions to reverse. Must be in the
* range [-rank(x), rank(x)). Defaults to all axes.
*/
function reverse3d_(x, axis) {
const $x = convertToTensor(x, 'x', 'reverse');
assert($x.rank === 3, () => `Error in reverse3D: x must be rank 3 but got rank ${$x.rank}.`);
return reverse($x, axis);
}
const reverse3d = op({ reverse3d_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Reverses a `tf.Tensor4D` along a specified axis.
*
* @param x The input tensor.
* @param axis The set of dimensions to reverse. Must be in the
* range [-rank(x), rank(x)). Defaults to all axes.
*/
function reverse4d_(x, axis) {
const $x = convertToTensor(x, 'x', 'reverse');
assert($x.rank === 4, () => `Error in reverse4D: x must be rank 4 but got rank ${$x.rank}.`);
return reverse($x, axis);
}
const reverse4d = op({ reverse4d_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes round of input `tf.Tensor` element-wise: `round(x)`.
* It implements banker's rounding.
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3]);
*
* x.round().print(); // or tf.round(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function round_(x) {
const $x = convertToTensor(x, 'x', 'round');
const inputs = { x: $x };
return ENGINE.runKernel(Round, inputs);
}
const round$1 = op({ round_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes scaled exponential linear element-wise.
*
* `x < 0 ? scale * alpha * (exp(x) - 1) : x`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.selu().print(); // or tf.selu(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function selu_(x) {
const $x = convertToTensor(x, 'x', 'selu');
const inputs = { x: $x };
return ENGINE.runKernel(Selu, inputs);
}
const selu = op({ selu_ });
/**
* 2-D convolution with separable filters.
*
* Performs a depthwise convolution that acts separately on channels followed
* by a pointwise convolution that mixes channels. Note that this is
* separability between dimensions [1, 2] and 3, not spatial separability
* between dimensions 1 and 2.
*
* See
* [https://www.tensorflow.org/api_docs/python/tf/nn/separable_conv2d](
* https://www.tensorflow.org/api_docs/python/tf/nn/separable_conv2d)
* for more details.
*
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param depthwiseFilter The depthwise filter tensor, rank 4, of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]`. This is
* the filter used in the first step.
* @param pointwiseFilter The pointwise filter tensor, rank 4, of shape
* `[1, 1, inChannels * channelMultiplier, outChannels]`. This is
* the filter used in the second step.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`. If strides is a single number, then `strideHeight ==
* strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels]. Only "NHWC" is currently supported.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function separableConv2d_(x, depthwiseFilter, pointwiseFilter, strides, pad, dilation = [1, 1], dataFormat = 'NHWC') {
const $x = convertToTensor(x, 'x', 'separableConv2d');
const $depthwiseFilter = convertToTensor(depthwiseFilter, 'depthwiseFilter', 'separableConv2d');
const $pointwiseFilter = convertToTensor(pointwiseFilter, 'pointwiseFilter', 'separableConv2d');
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
if (dataFormat === 'NCHW') {
throw new Error('separableConv2d currently does not support dataFormat NCHW; only ' +
'NHWC is supported');
}
assert(x4D.rank === 4, () => `Error in separableConv2d: input must be rank 4, but got ` +
`rank ${x4D.rank}.`);
assert($depthwiseFilter.rank === 4, () => `Error in separableConv2d: depthwise filter must be rank 4, but ` +
`got rank ${$depthwiseFilter.rank}.`);
assert($pointwiseFilter.rank === 4, () => `Error in separableConv2d: pointwise filter must be rank 4, but ` +
`got rank ${$depthwiseFilter.rank}.`);
assert($pointwiseFilter.shape[0] === 1, () => `Error in separableConv2d: the first dimension of pointwise filter ` +
` must be 1, but got ${$pointwiseFilter.shape[0]}.`);
assert($pointwiseFilter.shape[1] === 1, () => `Error in separableConv2d: the second dimension of pointwise ` +
`filter must be 1, but got ${$pointwiseFilter.shape[1]}.`);
const inChannels = $depthwiseFilter.shape[2];
const channelMultiplier = $depthwiseFilter.shape[3];
assert($pointwiseFilter.shape[2] === inChannels * channelMultiplier, () => `Error in separableConv2d: the third dimension of pointwise filter ` +
`must be ${inChannels * channelMultiplier}, ` +
`but got ${$pointwiseFilter.shape[2]}.`);
const depthwise = depthwiseConv2d(x4D, $depthwiseFilter, strides, pad, dataFormat, dilation);
const pointwiseStride = 1;
const res = conv2d(depthwise, $pointwiseFilter, pointwiseStride, 'valid', dataFormat);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const separableConv2d = op({ separableConv2d_ });
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the difference between two lists of numbers.
*
* Given a Tensor `x` and a Tensor `y`, this operation returns a Tensor `out`
* that represents all values that are in `x` but not in `y`. The returned
* Tensor `out` is sorted in the same order that the numbers appear in `x`
* (duplicates are preserved). This operation also returns a Tensor indices that
* represents the position of each out element in `x`. In other words:
*
* `out[i] = x[idx[i]] for i in [0, 1, ..., out.length - 1]`
*
* ```js
* const x = [1, 2, 3, 4, 5, 6];
* const y = [1, 3, 5];
*
* const [out, indices] = await tf.setdiff1dAsync(x, y);
* out.print(); // [2, 4, 6]
* indices.print(); // [1, 3, 5]
* ```
*
* @param x 1-D Tensor. Values to keep.
* @param y 1-D Tensor. Must have the same type as x. Values to exclude in the
* output.
* @returns Promise of Tensor tuple [out, indices].
* out: Tensor with the same type as x.
* indices: A Tensor of type int32.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
async function setdiff1dAsync_(x, y) {
const $x = convertToTensor(x, 'x', 'setdiff1d');
const $y = convertToTensor(y, 'y', 'setdiff1d');
assert($x.dtype === $y.dtype, () => `x and y should have the same dtype, but got x (${$x.dtype}) and y (${$y.dtype}).`);
assert($x.rank === 1, () => `x should be 1D tensor, but got x (${$x.shape}).`);
assert($y.rank === 1, () => `y should be 1D tensor, but got y (${$y.shape}).`);
const xVals = await $x.data();
const yVals = await $y.data();
const ySet = new Set(yVals);
let outputSize = 0;
for (let i = 0; i < xVals.length; i++) {
if (!ySet.has(xVals[i])) {
outputSize++;
}
}
const buffer = new TensorBuffer([outputSize], $x.dtype);
const indices = new TensorBuffer([outputSize], 'int32');
for (let i = 0, p = 0; i < xVals.length; i++) {
if (!ySet.has(xVals[i])) {
buffer.values[p] = xVals[i];
indices.values[p] = i;
p++;
}
}
return [buffer.toTensor(), indices.toTensor()];
}
const setdiff1dAsync = setdiff1dAsync_;
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns an element-wise indication of the sign of a number.
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3, NaN, 0]);
*
* x.sign().print(); // or tf.sign(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function sign_(x) {
const $x = convertToTensor(x, 'x', 'sign');
const inputs = { x: $x };
return ENGINE.runKernel(Sign, inputs);
}
const sign = op({ sign_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Extracts a 1D slice from 1D array starting at coordinates `begin` and is
* of length `size`. See `slice` for details.
*/
function slice1d_(x, begin, size) {
const $x = convertToTensor(x, 'x', 'slice1d');
assert($x.rank === 1, () => `slice1d expects a rank-1 tensor, but got a rank-${$x.rank} tensor`);
return slice($x, [begin], [size]);
}
const slice1d = op({ slice1d_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Extracts a 2D slice from a 2D array starting at coordinates `begin` and
* is of size `size`. See `slice` for details.
*/
function slice2d_(x, begin, size) {
const $x = convertToTensor(x, 'x', 'slice2d');
assert($x.rank === 2, () => `slice2d expects a rank-2 tensor, but got a rank-${$x.rank} tensor`);
return slice($x, begin, size);
}
const slice2d = op({ slice2d_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Extracts a 3D slice from a 3D array starting at coordinates `begin` and
* is of size `size`. See `slice` for details.
*/
function slice3d_(x, begin, size) {
const $x = convertToTensor(x, 'x', 'slice3d');
assert($x.rank === 3, () => `slice3d expects a rank-3 tensor, but got a rank-${$x.rank} tensor`);
return slice($x, begin, size);
}
const slice3d = op({ slice3d_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Extracts a 4D slice from a 4D array starting at coordinates `begin` and
* is of size `size`. See `slice` for details.
*/
function slice4d_(x, begin, size) {
const $x = convertToTensor(x, 'x', 'slice4d');
assert($x.rank === 4, () => `slice4d expects a rank-4 tensor, but got a rank-${$x.rank} tensor`);
return slice($x, begin, size);
}
const slice4d = op({ slice4d_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the softmax normalized vector given the logits.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
*
* a.softmax().print(); // or tf.softmax(a)
* ```
*
* ```js
* const a = tf.tensor2d([2, 4, 6, 1, 2, 3], [2, 3]);
*
* a.softmax().print(); // or tf.softmax(a)
* ```
*
* @param logits The logits array.
* @param dim The dimension softmax would be performed on. Defaults to `-1`
* which indicates the last dimension.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function softmax_(logits, dim = -1) {
const $logits = convertToTensor(logits, 'logits', 'softmax', 'float32');
if (dim === -1) {
dim = $logits.rank - 1;
}
if (dim !== $logits.rank - 1) {
throw Error('Softmax along a non-last dimension is not yet supported. ' +
`Logits was rank ${$logits.rank} and dim was ${dim}`);
}
const inputs = { logits: $logits };
const attrs = { dim };
return ENGINE.runKernel(Softmax, inputs, attrs);
}
const softmax = op({ softmax_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Fast Fourier transform.
*
* Computes the 1-dimensional discrete Fourier transform over the inner-most
* dimension of input.
*
* ```js
* const real = tf.tensor1d([1, 2, 3]);
* const imag = tf.tensor1d([1, 2, 3]);
* const x = tf.complex(real, imag);
*
* x.fft().print(); // tf.spectral.fft(x).print();
* ```
* @param input The complex input to compute an fft over.
*
* @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}
*/
function fft_(input) {
assert(input.dtype === 'complex64', () => `The dtype for tf.spectral.fft() must be complex64 ` +
`but got ${input.dtype}.`);
const inputs = { input };
return ENGINE.runKernel(FFT, inputs);
}
const fft = op({ fft_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Inverse fast Fourier transform.
*
* Computes the inverse 1-dimensional discrete Fourier transform over the
* inner-most dimension of input.
*
* ```js
* const real = tf.tensor1d([1, 2, 3]);
* const imag = tf.tensor1d([1, 2, 3]);
* const x = tf.complex(real, imag);
*
* x.ifft().print(); // tf.spectral.ifft(x).print();
* ```
* @param input The complex input to compute an ifft over.
*
* @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}
*/
function ifft_(input) {
assert(input.dtype === 'complex64', () => `The dtype for tf.spectral.ifft() must be complex64 ` +
`but got ${input.dtype}.`);
const inputs = { input };
return ENGINE.runKernel(IFFT, inputs);
}
const ifft = op({ ifft_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Inversed real value input fast Fourier transform.
*
* Computes the 1-dimensional inversed discrete Fourier transform over the
* inner-most dimension of the real input.
*
* ```js
* const real = tf.tensor1d([1, 2, 3]);
* const imag = tf.tensor1d([0, 0, 0]);
* const x = tf.complex(real, imag);
*
* x.irfft().print();
* ```
* @param input The real value input to compute an irfft over.
*
* @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}
*/
function irfft_(input) {
const innerDimensionSize = input.shape[input.shape.length - 1];
const batch = input.size / innerDimensionSize;
let ret;
if (innerDimensionSize <= 2) {
const complexInput = reshape(input, [batch, innerDimensionSize]);
ret = ifft(complexInput);
}
else {
// The length of unique components of the DFT of a real-valued signal
// is 2 * (input_len - 1)
const outputShape = [batch, 2 * (innerDimensionSize - 1)];
const realInput = reshape(real(input), [batch, innerDimensionSize]);
const imagInput = reshape(imag(input), [batch, innerDimensionSize]);
const realConjugate = reverse(slice(realInput, [0, 1], [batch, innerDimensionSize - 2]), 1);
const imagConjugate = mul(reverse(slice(imagInput, [0, 1], [batch, innerDimensionSize - 2]), 1), scalar(-1));
const r = concat([realInput, realConjugate], 1);
const i = concat([imagInput, imagConjugate], 1);
const complexInput = reshape(complex(r, i), [outputShape[0], outputShape[1]]);
ret = ifft(complexInput);
}
ret = real(ret);
// reshape the result if the input is 3D tensor.
if (input.rank === 3 && input.shape[0] !== 0) {
const temp = ret;
const batch = input.shape[0];
ret = reshape(ret, [batch, ret.shape[0] / batch, ret.shape[1]]);
temp.dispose();
}
return ret;
}
const irfft = op({ irfft_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Real value input fast Fourier transform.
*
* Computes the 1-dimensional discrete Fourier transform over the
* inner-most dimension of the real input.
*
* ```js
* const real = tf.tensor1d([1, 2, 3]);
*
* real.rfft().print();
* ```
* @param input The real value input to compute an rfft over.
*
* @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}
*/
function rfft_(input, fftLength) {
assert(input.dtype === 'float32', () => `The dtype for rfft() must be real value but got ${input.dtype}`);
let innerDimensionSize = input.shape[input.shape.length - 1];
const batch = input.size / innerDimensionSize;
let adjustedInput;
if (fftLength != null && fftLength < innerDimensionSize) {
// Need to crop
const begin = input.shape.map(v => 0);
const size = input.shape.map(v => v);
size[input.shape.length - 1] = fftLength;
adjustedInput = slice(input, begin, size);
innerDimensionSize = fftLength;
}
else if (fftLength != null && fftLength > innerDimensionSize) {
// Need to pad with zeros
const zerosShape = input.shape.map(v => v);
zerosShape[input.shape.length - 1] = fftLength - innerDimensionSize;
adjustedInput = concat([input, zeros(zerosShape)], input.shape.length - 1);
innerDimensionSize = fftLength;
}
else {
adjustedInput = input;
}
// Complement the input with zero imaginary numbers.
const zerosInput = zerosLike(adjustedInput);
const complexInput = reshape(complex(adjustedInput, zerosInput), [batch, innerDimensionSize]);
const ret = fft(complexInput);
// Exclude complex conjugations. These conjugations are put symmetrically.
const half = Math.floor(innerDimensionSize / 2) + 1;
const realValues = real(ret);
const imagValues = imag(ret);
const realComplexConjugate = split(realValues, [half, innerDimensionSize - half], realValues.shape.length - 1);
const imagComplexConjugate = split(imagValues, [half, innerDimensionSize - half], imagValues.shape.length - 1);
const outputShape = adjustedInput.shape.slice();
outputShape[adjustedInput.shape.length - 1] = half;
return reshape(complex(realComplexConjugate[0], imagComplexConjugate[0]), outputShape);
}
const rfft = op({ rfft_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns (a - b) * (a - b) element-wise.
* Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 4, 3, 16]);
* const b = tf.tensor1d([1, 2, 9, 4]);
*
* a.squaredDifference(b).print(); // or tf.squaredDifference(a, b)
* ```
*
* ```js
* // Broadcast squared difference a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(5);
*
* a.squaredDifference(b).print(); // or tf.squaredDifference(a, b)
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function squaredDifference_(a, b) {
let $a = convertToTensor(a, 'a', 'squaredDifference');
let $b = convertToTensor(b, 'b', 'squaredDifference');
[$a, $b] = makeTypesMatch($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
const attrs = {};
return ENGINE.runKernel(SquaredDifference, inputs, attrs);
}
const squaredDifference = op({ squaredDifference_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Removes dimensions of size 1 from the shape of a `tf.Tensor`.
*
* ```js
* const x = tf.tensor([1, 2, 3, 4], [1, 1, 4]);
* x.squeeze().print();
* ```
*
* @param x The input tensor to be squeezed.
* @param axis An optional list of numbers. If specified, only
* squeezes the dimensions listed. The dimension index starts at 0. It
* is an error to squeeze a dimension that is not 1.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function squeeze_(x, axis) {
const $x = convertToTensor(x, 'x', 'squeeze');
return reshape($x, squeezeShape($x.shape, axis).newShape);
}
const squeeze = op({ squeeze_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Extracts a strided slice of a tensor.
*
* Roughly speaking, this op extracts a slice of size (end-begin)/stride from
* the given input tensor (x). Starting at the location specified by begin the
* slice continues by adding stride to the index until all dimensions are not
* less than end. Note that a stride can be negative, which causes a reverse
* slice.
*
* ```js
* const t = tf.tensor3d([1, 1, 1 ,2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6],
* [3, 2, 3]);
* t.stridedSlice([1, 0, 0], [2, 1, 3], [1, 1, 1]).print() // [[[3, 3, 3]]]
* t.stridedSlice([1, 0, 0], [2, 2, 3], [1, 1, 1]).print() // [[[3, 3, 3],
* // [4, 4, 4]]]
* t.stridedSlice([1, -1, 0], [2, -3, 3], [1, -1, 1]).print() // [[[4, 4, 4],
* // [3, 3, 3]]]
* ```
*
* @param x The tensor to stride slice.
* @param begin The coordinates to start the slice from.
* @param end: The coordinates to end the slice at.
* @param strides: The size of the slice.
* @param beginMask: If the ith bit of beginMask is set, begin[i] is ignored
* and the fullest possible range in that dimension is used instead.
* @param endMask: If the ith bit of endMask is set, end[i] is ignored
* and the fullest possible range in that dimension is used instead.
* @param shrinkAxisMask: a bitmask where bit i implies that
* the ith specification should shrink the dimensionality. begin and end must
* imply a slice of size 1 in the dimension.
*
* @doc {heading: 'Operations', subheading: 'Slicing and Joining'}
*/
function stridedSlice_(x, begin, end, strides, beginMask = 0, endMask = 0, ellipsisMask = 0, newAxisMask = 0, shrinkAxisMask = 0) {
const $x = convertToTensor(x, 'x', 'stridedSlice');
const inputs = { x: $x };
const attrs = {
begin,
end,
strides,
beginMask,
endMask,
ellipsisMask,
newAxisMask,
shrinkAxisMask
};
return ENGINE.runKernel(StridedSlice, inputs, attrs);
}
const stridedSlice = op({ stridedSlice_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes tan of the input `tf.Tensor` element-wise, `tan(x)`
*
* ```js
* const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);
*
* x.tan().print(); // or tf.tan(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function tan_(x) {
const $x = convertToTensor(x, 'x', 'tan');
const inputs = { x: $x };
return ENGINE.runKernel(Tan, inputs);
}
const tan = op({ tan_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with the provided values, shape and dtype.
*
* ```js
* // Pass an array of values to create a vector.
* tf.tensor([1, 2, 3, 4]).print();
* ```
*
* ```js
* // Pass a nested array of values to make a matrix or a higher
* // dimensional tensor.
* tf.tensor([[1, 2], [3, 4]]).print();
* ```
*
* ```js
* // Pass a flat array and specify a shape yourself.
* tf.tensor([1, 2, 3, 4], [2, 2]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`. If the values are strings,
* they will be encoded as utf-8 and kept as `Uint8Array[]`.
* @param shape The shape of the tensor. Optional. If not provided,
* it is inferred from `values`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor(values, shape, dtype) {
const inferredShape = inferShape(values, dtype);
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates rank-1 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor1d` as it makes the code more readable.
*
* ```js
* tf.tensor1d([1, 2, 3]).print();
* ```
*
* @param values The values of the tensor. Can be array of numbers,
* or a `TypedArray`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor1d(values, dtype) {
assertNonNull(values);
const inferredShape = inferShape(values, dtype);
if (inferredShape.length !== 1) {
throw new Error('tensor1d() requires values to be a flat/TypedArray');
}
const shape = null;
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates rank-2 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor2d` as it makes the code more readable.
*
* ```js
* // Pass a nested array.
* tf.tensor2d([[1, 2], [3, 4]]).print();
* ```
* ```js
* // Pass a flat array and specify a shape.
* tf.tensor2d([1, 2, 3, 4], [2, 2]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`.
* @param shape The shape of the tensor. If not provided, it is inferred from
* `values`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor2d(values, shape, dtype) {
assertNonNull(values);
if (shape != null && shape.length !== 2) {
throw new Error('tensor2d() requires shape to have two numbers');
}
const inferredShape = inferShape(values, dtype);
if (inferredShape.length !== 2 && inferredShape.length !== 1) {
throw new Error('tensor2d() requires values to be number[][] or flat/TypedArray');
}
if (inferredShape.length === 1 && shape == null) {
throw new Error('tensor2d() requires shape to be provided when `values` ' +
'are a flat/TypedArray');
}
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates rank-3 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor3d` as it makes the code more readable.
*
* ```js
* // Pass a nested array.
* tf.tensor3d([[[1], [2]], [[3], [4]]]).print();
* ```
* ```js
* // Pass a flat array and specify a shape.
* tf.tensor3d([1, 2, 3, 4], [2, 2, 1]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`.
* @param shape The shape of the tensor. If not provided, it is inferred from
* `values`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor3d(values, shape, dtype) {
assertNonNull(values);
if (shape != null && shape.length !== 3) {
throw new Error('tensor3d() requires shape to have three numbers');
}
const inferredShape = inferShape(values, dtype);
if (inferredShape.length !== 3 && inferredShape.length !== 1) {
throw new Error('tensor3d() requires values to be number[][][] or flat/TypedArray');
}
if (inferredShape.length === 1 && shape == null) {
throw new Error('tensor3d() requires shape to be provided when `values` ' +
'are a flat array');
}
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates rank-4 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor4d` as it makes the code more readable.
*
* ```js
* // Pass a nested array.
* tf.tensor4d([[[[1], [2]], [[3], [4]]]]).print();
* ```
* ```js
* // Pass a flat array and specify a shape.
* tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`.
* @param shape The shape of the tensor. Optional. If not provided,
* it is inferred from `values`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor4d(values, shape, dtype) {
assertNonNull(values);
if (shape != null && shape.length !== 4) {
throw new Error('tensor4d() requires shape to have four numbers');
}
const inferredShape = inferShape(values, dtype);
if (inferredShape.length !== 4 && inferredShape.length !== 1) {
throw new Error('tensor4d() requires values to be number[][][][] or flat/TypedArray');
}
if (inferredShape.length === 1 && shape == null) {
throw new Error('tensor4d() requires shape to be provided when `values` ' +
'are a flat array');
}
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates rank-5 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor5d` as it makes the code more readable.
*
* ```js
* // Pass a nested array.
* tf.tensor5d([[[[[1],[2]],[[3],[4]]],[[[5],[6]],[[7],[8]]]]]).print();
* ```
* ```js
* // Pass a flat array and specify a shape.
* tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`.
* @param shape The shape of the tensor. Optional. If not provided,
* it is inferred from `values`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor5d(values, shape, dtype) {
assertNonNull(values);
if (shape != null && shape.length !== 5) {
throw new Error('tensor5d() requires shape to have five numbers');
}
const inferredShape = inferShape(values, dtype);
if (inferredShape.length !== 5 && inferredShape.length !== 1) {
throw new Error('tensor5d() requires values to be ' +
'number[][][][][] or flat/TypedArray');
}
if (inferredShape.length === 1 && shape == null) {
throw new Error('tensor5d() requires shape to be provided when `values` ' +
'are a flat array');
}
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates rank-6 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor6d` as it makes the code more readable.
*
* ```js
* // Pass a nested array.
* tf.tensor6d([[[[[[1],[2]],[[3],[4]]],[[[5],[6]],[[7],[8]]]]]]).print();
* ```
* ```js
* // Pass a flat array and specify a shape.
* tf.tensor6d([1, 2, 3, 4, 5, 6, 7, 8], [1, 1, 2, 2, 2, 1]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`.
* @param shape The shape of the tensor. Optional. If not provided,
* it is inferred from `values`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor6d(values, shape, dtype) {
assertNonNull(values);
if (shape != null && shape.length !== 6) {
throw new Error('tensor6d() requires shape to have six numbers');
}
const inferredShape = inferShape(values, dtype);
if (inferredShape.length !== 6 && inferredShape.length !== 1) {
throw new Error('tensor6d() requires values to be number[][][][][][] or ' +
'flat/TypedArray');
}
if (inferredShape.length === 1 && shape == null) {
throw new Error('tensor6d() requires shape to be provided when `values` ' +
'are a flat array');
}
shape = shape ||
inferredShape;
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Finds the values and indices of the `k` largest entries along the last
* dimension.
*
* If the input is a vector (rank=1), finds the k largest entries in the vector
* and outputs their values and indices as vectors. Thus values[j] is the j-th
* largest entry in input, and its index is indices[j].
* For higher rank inputs, computes the top k entries along the last dimension.
*
* If two elements are equal, the lower-index element appears first.
*
* ```js
* const a = tf.tensor2d([[1, 5], [4, 3]]);
* const {values, indices} = tf.topk(a);
* values.print();
* indices.print();
* ```
* @param x 1-D or higher `tf.Tensor` with last dimension being at least `k`.
* @param k Number of top elements to look for along the last dimension.
* @param sorted If true, the resulting `k` elements will be sorted by the
* values in descending order.
*
* @doc {heading: 'Operations', subheading: 'Evaluation'}
*/
function topk_(x, k = 1, sorted = true) {
const $x = convertToTensor(x, 'x', 'topk');
if ($x.rank === 0) {
throw new Error('topk() expects the input to be of rank 1 or higher');
}
const lastDim = $x.shape[$x.shape.length - 1];
if (k > lastDim) {
throw new Error(`'k' passed to topk() must be <= the last dimension (${lastDim}) ` +
`but got ${k}`);
}
const inputs = { x: $x };
const attrs = { k, sorted };
const [values, indices] = ENGINE.runKernel(TopK, inputs, attrs);
return { values, indices };
}
const topk = op({ topk_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a truncated normal
* distribution.
*
* ```js
* tf.truncatedNormal([2, 2]).print();
* ```
*
* The generated values follow a normal distribution with specified mean and
* standard deviation, except that values whose magnitude is more than 2
* standard deviations from the mean are dropped and re-picked.
*
* @param shape An array of integers defining the output tensor shape.
* @param mean The mean of the normal distribution.
* @param stdDev The standard deviation of the normal distribution.
* @param dtype The data type of the output tensor.
* @param seed The seed for the random number generator.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function truncatedNormal_(shape, mean = 0, stdDev = 1, dtype, seed) {
if (dtype != null && dtype === 'bool') {
throw new Error(`Unsupported data type $ { dtype }`);
}
const randGauss = new MPRandGauss(mean, stdDev, dtype, true /* truncated */, seed);
const res = buffer(shape, dtype);
for (let i = 0; i < res.values.length; i++) {
res.values[i] = randGauss.nextValue();
}
return res.toTensor();
}
const truncatedNormal = op({ truncatedNormal_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Finds unique elements along an axis of a tensor.
*
* It returns a tensor `values` containing all of the unique elements along the
* `axis` of the given tensor `x` in the same order that they occur along the
* `axis` in `x`; `x` does not need to be sorted. It also returns a tensor
* `indices` the same size as the number of the elements in `x` along the `axis`
* dimension. It contains the index in the unique output `values`.
*
* ```js
* // A 1-D tensor
* const a = tf.tensor1d([1, 1, 2, 4, 4, 4, 7, 8, 8]);
* const {values, indices} = tf.unique(a);
* values.print(); // [1, 2, 4, 7, 8,]
* indices.print(); // [0, 0, 1, 2, 2, 2, 3, 4, 4]
* ```
*
* ```js
* // A 2-D tensor with axis=0
* //
* // 'a' is: [[1, 0, 0],
* // [1, 0, 0],
* // [2, 0, 0]]
* const a = tf.tensor2d([[1, 0, 0], [1, 0, 0], [2, 0, 0]]);
* const {values, indices} = tf.unique(a, 0)
* values.print(); // [[1, 0, 0],
* // [2, 0, 0]]
* indices.print(); // [0, 0, 1]
* ```
*
* ```js
* // A 2-D tensor with axis=1
* //
* // 'a' is: [[1, 0, 0],
* // [1, 0, 0],
* // [2, 0, 0]]
* const a = tf.tensor2d([[1, 0, 0], [1, 0, 0], [2, 0, 0]]);
* const {values, indices} = tf.unique(a, 1)
* values.print(); // [[1, 0],
* // [1, 0],
* // [2, 0]]
* indices.print(); // [0, 1, 1]
* ```
* @param x A tensor (int32, string, bool).
* @param axis The axis of the tensor to find the unique elements.
* @returns [uniqueElements, indices] (see above for details)
*
* @doc {heading: 'Operations', subheading: 'Evaluation'}
*/
function unique_(x, axis = 0) {
const $x = convertToTensor(x, 'x', 'unique', 'string_or_numeric');
assert($x.rank > 0, () => 'The input tensor must be at least 1D');
const inputs = { x: $x };
const attrs = { axis };
const [values, indices] = ENGINE.runKernel(Unique, inputs, attrs);
return { values, indices };
}
const unique = op({ unique_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a new variable with the provided initial value.
* ```js
* const x = tf.variable(tf.tensor([1, 2, 3]));
* x.assign(tf.tensor([4, 5, 6]));
*
* x.print();
* ```
*
* @param initialValue Initial value for the tensor.
* @param trainable If true, optimizers are allowed to update it.
* @param name Name of the variable. Defaults to a unique id.
* @param dtype If set, initialValue will be converted to the given type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function variable(initialValue, trainable = true, name, dtype) {
return ENGINE.makeVariable(initialValue, trainable, name, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function whereImpl(condShape, condVals) {
const indices = [];
for (let i = 0; i < condVals.length; i++) {
if (condVals[i]) {
indices.push(i);
}
}
const inBuffer = buffer(condShape, 'int32');
const out = buffer([indices.length, condShape.length], 'int32');
for (let i = 0; i < indices.length; i++) {
const loc = inBuffer.indexToLoc(indices[i]);
const offset = i * condShape.length;
out.values.set(loc, offset);
}
return out.toTensor();
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns the coordinates of true elements of condition.
*
* The coordinates are returned in a 2-D tensor where the first dimension (rows)
* represents the number of true elements, and the second dimension (columns)
* represents the coordinates of the true elements. Keep in mind, the shape of
* the output tensor can vary depending on how many true values there are in
* input. Indices are output in row-major order. The resulting tensor has the
* shape `[numTrueElems, condition.rank]`.
*
* This is analogous to calling the python `tf.where(cond)` without an x or y.
*
* ```js
* const cond = tf.tensor1d([false, false, true], 'bool');
* const result = await tf.whereAsync(cond);
* result.print();
* ```
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
async function whereAsync_(condition) {
const $condition = convertToTensor(condition, 'condition', 'whereAsync', 'bool');
const vals = await $condition.data();
const res = whereImpl($condition.shape, vals);
if (condition !== $condition) {
$condition.dispose();
}
return res;
}
const whereAsync = whereAsync_;
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Apply boolean mask to tensor.
*
* ```js
* const tensor = tf.tensor2d([1, 2, 3, 4, 5, 6], [3, 2]);
* const mask = tf.tensor1d([1, 0, 1], 'bool');
* const result = await tf.booleanMaskAsync(tensor, mask);
* result.print();
* ```
*
* @param tensor N-D tensor.
* @param mask K-D boolean tensor, K <= N and K must be known statically.
* @param axis A 0-D int Tensor representing the axis in tensor to mask from.
* By default, axis is 0 which will mask from the first dimension.
* Otherwise K + axis <= N.
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
async function booleanMaskAsync_(tensor, mask, axis) {
const $tensor = convertToTensor(tensor, 'tensor', 'boolMask');
const $mask = convertToTensor(mask, 'mask', 'boolMask', 'bool');
const axisFrom = axis == null ? 0 : axis;
const maskDim = $mask.rank;
const tensorShape = $tensor.shape;
assert(maskDim > 0, () => 'mask cannot be scalar');
assertShapesMatch(tensorShape.slice(axisFrom, axisFrom + maskDim), $mask.shape, `mask's shape must match the first K dimensions of tensor's shape,`);
let leadingSize = 1;
for (let i = axisFrom; i < axisFrom + maskDim; i++) {
leadingSize *= tensorShape[i];
}
const targetTensorShape = tensorShape.slice(0, axisFrom)
.concat([leadingSize], tensorShape.slice(axisFrom + maskDim));
const reshapedTensor = reshape($tensor, targetTensorShape);
const reshapedMask = reshape($mask, [-1]);
const positivePositions = await whereAsync(reshapedMask);
const indices = squeeze(positivePositions, [1]);
const res = gather(reshapedTensor, indices, axisFrom);
// Ensure no memory leak.
if (tensor !== $tensor) {
$tensor.dispose();
}
if (mask !== $mask) {
$mask.dispose();
}
indices.dispose();
reshapedTensor.dispose();
reshapedMask.dispose();
positivePositions.dispose();
return res;
}
const booleanMaskAsync = booleanMaskAsync_;
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the norm of scalar, vectors, and matrices.
* This function can compute several different vector norms (the 1-norm, the
* Euclidean or 2-norm, the inf-norm, and in general the p-norm for p > 0)
* and matrix norms (Frobenius, 1-norm, and inf-norm).
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
*
* x.norm().print(); // or tf.norm(x)
* ```
*
* @param x The input array.
* @param ord Optional. Order of the norm. Supported norm types are
* following:
*
* | ord | norm for matrices | norm for vectors
* |------------|---------------------------|---------------------
* |'euclidean' |Frobenius norm |2-norm
* |'fro' |Frobenius norm |
* |Infinity |max(sum(abs(x), axis=1)) |max(abs(x))
* |-Infinity |min(sum(abs(x), axis=1)) |min(abs(x))
* |1 |max(sum(abs(x), axis=0)) |sum(abs(x))
* |2 | |sum(abs(x)^2)^1/2*
*
* @param axis Optional. If axis is null (the default), the input is
* considered a vector and a single vector norm is computed over the entire
* set of values in the Tensor, i.e. norm(x, ord) is equivalent
* to norm(x.reshape([-1]), ord). If axis is a integer, the input
* is considered a batch of vectors, and axis determines the axis in x
* over which to compute vector norms. If axis is a 2-tuple of integer it is
* considered a batch of matrices and axis determines the axes in NDArray
* over which to compute a matrix norm.
* @param keepDims Optional. If true, the norm have the same dimensionality
* as the input.
*
* @doc {heading: 'Operations', subheading: 'Matrices'}
*/
function norm_(x, ord = 'euclidean', axis = null, keepDims = false) {
x = convertToTensor(x, 'x', 'norm');
const norm = normImpl(x, ord, axis);
let keepDimsShape = norm.shape;
if (keepDims) {
const axes = parseAxisParam(axis, x.shape);
keepDimsShape = expandShapeToKeepDim(norm.shape, axes);
}
return reshape(norm, keepDimsShape);
}
function normImpl(x, p, axis = null) {
if (x.rank === 0) {
return abs(x);
}
// consider vector when no axis is specified
if (x.rank !== 1 && axis === null) {
return normImpl(reshape(x, [-1]), p, axis);
}
// vector
if (x.rank === 1 || typeof axis === 'number' ||
Array.isArray(axis) && axis.length === 1) {
if (p === 1) {
return sum$1(abs(x), axis);
}
if (p === Infinity) {
return max(abs(x), axis);
}
if (p === -Infinity) {
return min(abs(x), axis);
}
if (p === 'euclidean' || p === 2) {
// norm(x, 2) = sum(abs(xi) ^ 2) ^ 1/2
return sqrt(sum$1(pow(abs(x), scalar(2, 'int32')), axis));
}
throw new Error(`Error in norm: invalid ord value: ${p}`);
}
// matrix (assumption axis[0] < axis[1])
if (Array.isArray(axis) && axis.length === 2) {
if (p === 1) {
return max(sum$1(abs(x), axis[0]), axis[1] - 1);
}
if (p === Infinity) {
return max(sum$1(abs(x), axis[1]), axis[0]);
}
if (p === -Infinity) {
return min(sum$1(abs(x), axis[1]), axis[0]);
}
if (p === 'fro' || p === 'euclidean') {
// norm(x) = sqrt(sum(pow(x, 2)))
return sqrt(sum$1(square(x), axis));
}
throw new Error(`Error in norm: invalid ord value: ${p}`);
}
throw new Error(`Error in norm: invalid axis: ${axis}`);
}
const norm = op({ norm_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Compute the moving average of a variable.
*
* Without zeroDebias, the moving average operation is defined by:
* `v += delta`
* where
* `delta = (1 - decay) * (x - v)`
*
* With zeroDebias (default), the `delta` term is scaled to debias the
* effect of the (assumed) zero-initialization of `v`.
* `delta /= (1 - decay ^ step)`
*
* For more details on the zero-debiasing algorithm, see:
* https://arxiv.org/abs/1412.6980
*
* Note that this function is completely stateless and does not keep track of
* step count. The step count needs to be maintained by the caller and passed
* in as `step`.
*
* @param v The current moving average value.
* @param x New input value, must have the same shape and dtype as `v`.
* @param decay The decay factor. Typical values are 0.95 and 0.99.
* @param step Step count.
* @param zeroDebias: Whether zeroDebias is to be performed (default: `true`).
* @returns The new moving average value.
*
* @doc {heading: 'Operations', subheading: 'Moving Average'}
*/
function movingAverage_(v, x, decay, step, zeroDebias = true) {
const $v = convertToTensor(v, 'v', 'movingAverage');
const $x = convertToTensor(x, 'x', 'movingAverage');
const $decay = convertToTensor(decay, 'decay', 'movingAverage');
assertTypesMatch($v, $x);
assert(arraysEqual($v.shape, $x.shape), () => 'Shape mismatch in v and x');
const one = scalar(1);
const oneMinusDecay = sub(one, $decay);
let update = mul(sub($x, $v), oneMinusDecay);
if (zeroDebias) {
assert(step != null, () => 'When using zeroDebias: true, step is required.');
const $step = convertToTensor(step, 'step', 'movingAverage');
update = div(update, sub(one, pow($decay, $step)));
}
return add$1($v, update);
}
const movingAverage = op({ movingAverage_ });
/**
* Check whether updates.shape = indices.shape[:batchDim] +
* shape[sliceDim:]
*
* @param x The input tensor.
*/
function validateUpdateShape(shape, indices, updates) {
const sliceDim = (indices.rank > 1) ? indices.shape[indices.rank - 1] : 1;
const batchDim = (indices.rank > 1) ? indices.rank - 1 : 1;
const shapeError = 'Must have updates.shape = indices.shape[:batchDim] + ' +
`shape[sliceDim:], got updates.shape: ${updates.shape}` +
`, indices.shape: ${indices.shape}, shape: ${shape}` +
`, sliceDim: ${sliceDim}, and batchDim: ${batchDim}.`;
if (updates.rank < batchDim) {
throw new Error(shapeError + ` update.rank < ${batchDim}. `);
}
if (shape.length < sliceDim + (updates.rank - batchDim)) {
throw new Error(shapeError +
` Output shape length < ${sliceDim + (updates.rank - batchDim)}`);
}
if (updates.rank !== batchDim + shape.length - sliceDim) {
throw new Error(shapeError + ` update.rank != ${batchDim + shape.length - sliceDim}`);
}
for (let d = 0; d < batchDim; ++d) {
if (updates.shape[d] !== indices.shape[d]) {
throw new Error(shapeError +
` updates.shape[${d}] (${updates.shape[d]}) != indices.shape[${d}] (${indices.shape[d]}).`);
}
}
for (let d = 0; d < updates.rank - batchDim; ++d) {
if (updates.shape[d + batchDim] !== shape[d + sliceDim]) {
throw new Error(shapeError +
` updates.shape[${d + batchDim}] (${updates.shape[d + batchDim]}) != shape[${d + batchDim}] (${shape[d + batchDim]})`);
}
}
}
/**
* Validate scatter nd inputs.
*
* @param update The tensor contains the update values.
* @param indices The tensor contains the indices for the update values.
* @param shape The shape of the output tensor.
*/
function validateInput(updates, indices, shape) {
if (indices.rank < 1) {
throw new Error('tf.scatterND() expects the indices to be rank 1 or higher,' +
` but the rank was ${indices.rank}.`);
}
if (updates.rank < 1) {
throw new Error('tf.scatterND() expects the updates to be rank 1 or higher,' +
` but the rank was ${updates.rank}.`);
}
if (indices.dtype !== 'int32') {
throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${indices.dtype}`);
}
if (shape.length < 1) {
throw new Error(`Output rank must be greater or equal to 1, but got shape: ${shape}`);
}
if (shape.length === 0) {
if (indices.size === 0) {
throw new Error(`Indices specified for empty output. indices shape: ${indices.shape}`);
}
if (updates.size === 0) {
throw new Error(`Updates specified for empty output. updates shape: ${updates.shape}`);
}
}
validateUpdateShape(shape, indices, updates);
}
/**
* Calculate the shape information for the output.
*
* @param update The tensor contains the update values.
* @param indices The tensor contains the indices for the update values.
* @param shape The shape of the output tensor.
*
* @returns ScatterShapeInfo
*/
function calculateShapes(updates, indices, shape) {
// Calculate the number of dimensions in indices
const indicesRank = indices.shape.length;
const sliceRank = (indicesRank > 1) ? indices.shape[indicesRank - 1] : 1;
// Calculate the number of elements that make up each slice of our updated
// tensor. This allows us to work with flattened tensors and copy over whole
// slices at a time.
const totalNd = shape.length;
let sliceSize = 1;
for (let i = sliceRank; i < totalNd; ++i) {
sliceSize *= shape[i];
}
const safeSliceDim = (sliceRank < 1) ? 1 : sliceRank;
const numUpdates = sizeFromShape(indices.shape) / safeSliceDim;
const strides = [...computeStrides(shape.slice(0, sliceRank)), 1];
const outputSize = sizeFromShape(shape);
return { sliceRank, numUpdates, sliceSize, strides, outputSize };
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Creates a new tensor by applying sparse updates to individual
* values or slices within a zero tensor of the given shape tensor according to
* indices. This operator is the inverse of the `tf.gatherND` operator which
* extracts values or slices from a given tensor.
*
* ```js
* const indices = tf.tensor2d([4, 3, 1, 7], [4, 1], 'int32');
* const updates = tf.tensor1d([9, 10, 11, 12]);
* const shape = [8];
* tf.scatterND(indices, updates, shape).print() //[0, 11, 0, 10, 9, 0, 0, 12]
* ```
*
* @param indices The tensor contains the indices into the output tensor.
* @param updates The tensor contains the value for the indices.
* @param shape: The shape of the output tensor.
*
* @doc {heading: 'Operations', subheading: 'Slicing and Joining'}
*/
function scatterND_(indices, updates, shape) {
const $indices = convertToTensor(indices, 'indices', 'scatterND', 'int32');
const $updates = convertToTensor(updates, 'updates', 'scatterND');
validateInput($updates, $indices, shape);
const inputs = { indices: $indices, updates: $updates };
const attrs = { shape };
// tslint:disable-next-line: no-unnecessary-type-assertion
return ENGINE.runKernel(ScatterNd, inputs, attrs);
}
const scatterND = op({ scatterND_ });
/**
* Validate sparseToDense inputs.
*
* @param sparseIndices A 0-D, 1-D, or 2-D Tensor of type int32.
* sparseIndices[i] contains the complete index where sparseValues[i] will be
* placed.
* @param sparseValues A 0-D or 1-D Tensor. Values
* corresponding to each row of sparseIndices, or a scalar value to be used for
* all sparse indices.
* @param outputShape number[]. Shape of the dense output tensor.
* @param validateIndices boolean. indice validation is not supported, error
* will be thrown if it is set.
*/
function validateInput$1(sparseIndices, sparseValues, outputShape, defaultValues) {
if (sparseIndices.dtype !== 'int32') {
throw new Error('tf.sparseToDense() expects the indices to be int32 type,' +
` but the dtype was ${sparseIndices.dtype}.`);
}
if (sparseIndices.rank > 2) {
throw new Error('sparseIndices should be a scalar, vector, or matrix,' +
` but got shape ${sparseIndices.shape}.`);
}
const numElems = sparseIndices.rank > 0 ? sparseIndices.shape[0] : 1;
const numDims = sparseIndices.rank > 1 ? sparseIndices.shape[1] : 1;
if (outputShape.length !== numDims) {
throw new Error('outputShape has incorrect number of elements:,' +
` ${outputShape.length}, should be: ${numDims}.`);
}
const numValues = sparseValues.size;
if (!(sparseValues.rank === 0 ||
sparseValues.rank === 1 && numValues === numElems)) {
throw new Error('sparseValues has incorrect shape ' +
`${sparseValues.shape}, should be [] or [${numElems}]`);
}
if (sparseValues.dtype !== defaultValues.dtype) {
throw new Error('sparseValues.dtype must match defaultValues.dtype');
}
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Converts a sparse representation into a dense tensor.
*
* Builds an array dense with shape outputShape such that:
*
* // If sparseIndices is scalar
* dense[i] = (i == sparseIndices ? sparseValues : defaultValue)
*
* // If sparseIndices is a vector, then for each i
* dense[sparseIndices[i]] = sparseValues[i]
*
* // If sparseIndices is an n by d matrix, then for each i in [0, n)
* dense[sparseIndices[i][0], ..., sparseIndices[i][d-1]] = sparseValues[i]
* All other values in dense are set to defaultValue. If sparseValues is a
* scalar, all sparse indices are set to this single value.
*
* If indices are repeated the final value is summed over all values for those
* indices.
*
* ```js
* const indices = tf.tensor1d([4, 5, 6, 1, 2, 3], 'int32');
* const values = tf.tensor1d([10, 11, 12, 13, 14, 15], 'float32');
* const shape = [8];
* tf.sparseToDense(indices, values, shape).print();
* ```
*
* @param sparseIndices A 0-D, 1-D, or 2-D Tensor of type int32.
* sparseIndices[i] contains the complete index where sparseValues[i] will be
* placed.
* @param sparseValues A 0-D or 1-D Tensor. Values
* corresponding to each row of sparseIndices, or a scalar value to be used for
* all sparse indices.
* @param outputShape Shape of the dense output tensor. the type is inferred.
* @param defaultValue Scalar. Value to set for indices not specified in
* sparseIndices. Defaults to zero.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function sparseToDense_(sparseIndices, sparseValues, outputShape, defaultValue = 0) {
const $sparseIndices = convertToTensor(sparseIndices, 'sparseIndices', 'sparseToDense', 'int32');
const $sparseValues = convertToTensor(sparseValues, 'sparseValues', 'sparseToDense');
const $defaultValue = convertToTensor(defaultValue, 'defaultValue', 'sparseToDense', $sparseValues.dtype);
validateInput$1($sparseIndices, $sparseValues, outputShape, $defaultValue);
const inputs = {
sparseIndices: $sparseIndices,
sparseValues: $sparseValues,
defaultValue: $defaultValue
};
const attrs = { outputShape };
return ENGINE.runKernel(SparseToDense, inputs, attrs);
}
const sparseToDense = op({ sparseToDense_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Gather slices from input tensor into a Tensor with shape specified by
* `indices`.
*
* `indices` is an K-dimensional integer tensor, best thought of as a
* (K-1)-dimensional tensor of indices into input, where each element defines a
* slice of input:
* output[\\(i_0, ..., i_{K-2}\\)] = input[indices[\\(i_0, ..., i_{K-2}\\)]]
*
* Whereas in `tf.gather`, `indices` defines slices into the first dimension of
* input, in `tf.gatherND`, `indices` defines slices into the first N dimensions
* of input, where N = indices.shape[-1].
*
* The last dimension of indices can be at most the rank of input:
* indices.shape[-1] <= input.rank
*
* The last dimension of `indices` corresponds to elements
* (if indices.shape[-1] == input.rank) or slices
* (if indices.shape[-1] < input.rank) along dimension indices.shape[-1] of
* input.
* The output tensor has shape
* indices.shape[:-1] + input.shape[indices.shape[-1]:]
*
* Note that on CPU, if an out of bound index is found, an error is returned. On
* GPU, if an out of bound index is found, a 0 is stored in the corresponding
* output value.
*
* ```js
* const indices = tf.tensor2d([0, 1, 1, 0], [2,2], 'int32');
* const input = tf.tensor2d([9, 10, 11, 12], [2, 2]);
* tf.gatherND(input, indices).print() // [10, 11]
* ```
*
* @param x The tensor from which to gather values.
* @param indices Index tensor, must be of type int32.
*
* @doc {heading: 'Operations', subheading: 'Slicing and Joining'}
*/
function gatherND_(x, indices) {
const $indices = convertToTensor(indices, 'indices', 'gatherND', 'int32');
const $x = convertToTensor(x, 'x', 'gatherND');
const inputs = { params: $x, indices: $indices };
return ENGINE.runKernel(GatherNd, inputs);
}
const gatherND = op({ gatherND_ });
/**
* @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.
* =============================================================================
*/
/**
* Normalize noise shape based on provided tensor and noise shape.
*
* @param x Tensor.
* @param noiseShape The shape for the randomly generated keep/drop flags, as
* an array of numbers. Optional.
* @returns Normalized noise shape.
*/
function getNoiseShape(x, noiseShape) {
if (noiseShape == null) {
return x.shape.slice();
}
if (arraysEqual(x.shape, noiseShape)) {
return noiseShape;
}
if (x.shape.length === noiseShape.length) {
const newDimension = [];
for (let i = 0; i < x.shape.length; i++) {
if (noiseShape[i] == null && x.shape[i] != null) {
newDimension.push(x.shape[i]);
}
else {
newDimension.push(noiseShape[i]);
}
}
return newDimension;
}
return noiseShape;
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes dropout.
*
* ```js
* const x = tf.tensor1d([1, 2, 2, 1]);
* const rate = 0.75;
* const output = tf.dropout(x, rate);
* output.print();
* ```
*
* @param x A floating point Tensor or TensorLike.
* @param rate A float in the range [0, 1). The probability that each element
* of x is discarded.
* @param noiseShape An array of numbers of type int32, representing the
* shape for randomly generated keep/drop flags. If the noiseShape has null
* value, it will be automatically replaced with the x's relative dimension
* size. Optional.
* @param seed Used to create random seeds. Optional.
* @returns A Tensor of the same shape of x.
*
* @doc {heading: 'Operations', subheading: 'Dropout'}
*/
function dropout_(x, rate, noiseShape, seed) {
const $x = convertToTensor(x, 'x', 'dropout');
assert($x.dtype === 'float32', () => `x has to be a floating point tensor since it's going to be ` +
`scaled, but got a ${$x.dtype} tensor instead.`);
assert(rate >= 0 && rate < 1, () => `rate must be a float in the range [0, 1), but got ${rate}.`);
if (rate === 0) {
return x instanceof Tensor ? $x.clone() : $x;
}
const $noiseShape = getNoiseShape($x, noiseShape);
const keepProb = 1 - rate;
const multiplier = div(floor(add$1(randomUniform($noiseShape, 0, 1, 'float32', seed), keepProb)), keepProb);
return mul($x, multiplier);
}
const dropout = op({ dropout_ });
/**
* @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 enclosingPowerOfTwo(value) {
// Return 2**N for integer N such that 2**N >= value.
return Math.floor(Math.pow(2, Math.ceil(Math.log(value) / Math.log(2.0))));
}
function cosineWindow(windowLength, a, b) {
const even = 1 - windowLength % 2;
const newValues = new Float32Array(windowLength);
for (let i = 0; i < windowLength; ++i) {
const cosArg = (2.0 * Math.PI * i) / (windowLength + even - 1);
newValues[i] = a - b * Math.cos(cosArg);
}
return tensor1d(newValues, 'float32');
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns whether the targets are in the top K predictions.
*
* ```js
* const predictions = tf.tensor2d([[20, 10, 40, 30], [30, 50, -20, 10]]);
* const targets = tf.tensor1d([2, 0]);
* const precision = await tf.inTopKAsync(predictions, targets);
* precision.print();
* ```
* @param predictions 2-D or higher `tf.Tensor` with last dimension being
* at least `k`.
* @param targets 1-D or higher `tf.Tensor`.
* @param k Optional Number of top elements to look at for computing precision,
* default to 1.
*
* @doc {heading: 'Operations', subheading: 'Evaluation'}
*/
async function inTopKAsync_(predictions, targets, k = 1) {
const $predictions = convertToTensor(predictions, 'predictions', 'inTopK');
const $targets = convertToTensor(targets, 'targets', 'inTopK');
assert($predictions.rank > 1, () => 'inTopK() expects the predictions to be of rank 2 or higher, ' +
`but got ${$predictions.rank}`);
assert($predictions.rank - 1 === $targets.rank, () => `predictions rank should be 1 larger than ` +
`targets rank, but got predictions rank ` +
`${$predictions.rank} and targets rank ${$targets.rank}`);
assertShapesMatch($predictions.shape.slice(0, $predictions.shape.length - 1), $targets.shape, `predictions's shape should be align with the targets' shape, ` +
'except the last dimension.');
const lastDim = $predictions.shape[$predictions.shape.length - 1];
assert(k > 0 && k <= lastDim, () => `'k' passed to inTopK() must be > 0 && <= the predictions last ` +
`dimension (${lastDim}), but got ${k}`);
const predictionsVals = await $predictions.data();
const targetsVals = await $targets.data();
// Reshape predictionsVals into a 2d tensor [batch, lastDim]
// and look up topK along lastDim.
const [batch, size] = [predictionsVals.length / lastDim, lastDim];
const precision = getTypedArrayFromDType('bool', batch);
for (let b = 0; b < batch; b++) {
const offset = b * size;
const vals = predictionsVals.subarray(offset, offset + size);
const valAndInd = [];
for (let i = 0; i < vals.length; i++) {
valAndInd.push({ value: vals[i], index: i });
}
valAndInd.sort((a, b) => b.value - a.value);
precision[b] = 0;
for (let i = 0; i < k; i++) {
if (valAndInd[i].index === targetsVals[b]) {
precision[b] = 1;
break;
}
}
}
if (predictions !== $predictions) {
$predictions.dispose();
}
if (targets !== $targets) {
$targets.dispose();
}
// Output precision has the same shape as targets.
return tensor(precision, $targets.shape, 'bool');
}
const inTopKAsync = inTopKAsync_;
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Returns gradient for fused activation.
function getFusedDyActivation(dy, y, activation) {
if (activation == null || activation === 'linear') {
return dy;
}
if (activation === 'relu') {
return mul(dy, step(y));
}
throw new Error(`Cannot compute gradient for fused activation ${activation}.`);
}
// Returns gradient for fused bias.
function getFusedBiasGradient(bias, dyActivation) {
let res = dyActivation;
const reduceAxes = getReductionAxes(bias.shape, dyActivation.shape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, bias.shape);
}
function applyActivation(x, activation, preluActivationWeights, leakyreluAlpha) {
if (activation === 'linear') {
return x;
}
else if (activation === 'relu') {
return relu(x);
}
else if (activation === 'elu') {
return elu(x);
}
else if (activation === 'relu6') {
return relu6(x);
}
else if (activation === 'prelu') {
return prelu(x, preluActivationWeights);
}
else if (activation === 'leakyrelu') {
return leakyRelu(x, leakyreluAlpha);
}
else if (activation === 'sigmoid') {
return sigmoid(x);
}
throw new Error(`Unknown fused activation ${activation}.`);
}
// Whether we should call fused ops.
const shouldFuse = (gradientDepth, activation) => {
const gradientMode = gradientDepth > 0;
return !gradientMode || activation === '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.
* =============================================================================
*/
/**
* Computes a 2D convolution over the input x, optionally fused with adding a
* bias and applying an activation.
*
* ```js
* const inputDepth = 2;
* const inShape = [2, 2, 2, inputDepth];
* const outputDepth = 2;
* const fSize = 1;
* const pad = 0;
* const strides = 1;
*
* const x = tf.tensor4d( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
* 16], inShape);
* const w = tf.tensor4d([-1, 1, -2, 0.5], [fSize, fSize, inputDepth,
* outputDepth]);
*
* tf.fused.conv2d({ x, filter: w, strides, pad, dataFormat: 'NHWC',
* dilations: [1, 1], bias: tf.scalar(5), activation: 'relu' }).print();
* ```
*
* @param obj An object with the following properties:
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, inDepth, outDepth]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid` output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dataFormat An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels]. Only "NHWC" is currently supported.
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `dilations` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
* @param bias Tensor to be added to the result.
* @param activation Name of activation kernel (defaults to `linear`) to be
* applied
* after biasAdd.
* @param preluActivationWeights Tensor of prelu weights to be applied as part
* of a `prelu` activation, typically the same shape as `x`.
* @param leakyreluAlpha Optional. Alpha to be applied as part of a `leakyrelu`
* activation.
*/
function fusedConv2d_({ x, filter, strides, pad, dataFormat = 'NHWC', dilations = [1, 1], dimRoundingMode, bias, activation = 'linear', preluActivationWeights, leakyreluAlpha }) {
activation = activation || 'linear';
if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {
let result = conv2d(x, filter, strides, pad, dataFormat, dilations, dimRoundingMode);
if (bias != null) {
result = add$1(result, bias);
}
return applyActivation(result, activation, preluActivationWeights, leakyreluAlpha);
}
const $x = convertToTensor(x, 'x', 'conv2d');
const $filter = convertToTensor(filter, 'filter', 'conv2d');
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
assert(x4D.rank === 4, () => `Error in fused conv2d: input must be rank 4, but got rank ` +
`${x4D.rank}.`);
assert($filter.rank === 4, () => `Error in fused conv2d: filter must be rank 4, but got rank ` +
`${$filter.rank}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in fused conv2d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
assert(x4D.shape[3] === $filter.shape[2], () => `Error in conv2d: depth of input (${x4D.shape[3]}) must match ` +
`input depth for filter ${$filter.shape[2]}.`);
assert(eitherStridesOrDilationsAreOne(strides, dilations), () => 'Error in conv2D: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
assert(dataFormat === 'NHWC', () => `Error in conv2d: got dataFormat of ${dataFormat} but only NHWC is currently supported.`);
const convInfo = computeConv2DInfo(x4D.shape, $filter.shape, strides, dilations, pad, dimRoundingMode);
let $bias;
if (bias != null) {
$bias = convertToTensor(bias, 'bias', 'fused conv2d');
[$bias] = makeTypesMatch($bias, $x);
assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);
}
let $preluActivationWeights;
if (preluActivationWeights != null) {
$preluActivationWeights = convertToTensor(preluActivationWeights, 'prelu weights', 'fused conv2d');
}
const grad = (dy, saved) => {
const [$filter, x4D, y, $bias] = saved;
const dyActivation = getFusedDyActivation(dy, y, activation);
assert(tupleValuesAreOne(dilations), () => 'Error in gradient of fused conv2D: ' +
`dilation rates greater than 1 ` +
`are not yet supported in gradients. Got dilations '${dilations}'`);
const xDer = conv2DBackpropInput(x4D.shape, dyActivation, $filter, strides, pad);
const filterDer = conv2DBackpropFilter(x4D, dyActivation, $filter.shape, strides, pad);
const der = [xDer, filterDer];
if ($bias != null) {
const biasDer = getFusedBiasGradient($bias, dyActivation);
der.push(biasDer);
}
return der;
};
const inputs = {
x: x4D,
filter: $filter,
bias: $bias,
preluActivationWeights: $preluActivationWeights
};
const attrs = {
strides,
pad,
dataFormat,
dilations,
dimRoundingMode,
activation,
leakyreluAlpha
};
// Depending on the the params passed in we will have different number of
// inputs and thus a a different number of elements in the gradient.
if (bias == null) {
const customOp = customGrad((x4D, filter, save) => {
let res =
// tslint:disable-next-line: no-unnecessary-type-assertion
ENGINE.runKernel(FusedConv2D, inputs, attrs);
save([filter, x4D, res]);
if (reshapedTo4D) {
// tslint:disable-next-line: no-unnecessary-type-assertion
res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return { value: res, gradFunc: grad };
});
return customOp(x4D, $filter);
}
else {
const customOpWithBias = customGrad((x4D, filter, bias, save) => {
let res = ENGINE.runKernel(FusedConv2D, inputs, attrs);
save([filter, x4D, res, bias]);
if (reshapedTo4D) {
// tslint:disable-next-line: no-unnecessary-type-assertion
res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return { value: res, gradFunc: grad };
});
return customOpWithBias(x4D, $filter, $bias);
}
}
const conv2d$1 = op({ fusedConv2d_ });
/**
* @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.
* =============================================================================
*/
/**
* Computes depthwise 2D convolution, optionally fused with adding a
* bias and applying an activation.
*
* Given a 4D `input` array and a `filter` array of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]` containing
* `inChannels` convolutional filters of depth 1, this op applies a
* different filter to each input channel (expanding from 1 channel to
* `channelMultiplier` channels for each), then concatenates the results
* together. The output has `inChannels * channelMultiplier` channels.
*
* See
* [https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d](
* https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)
* for more details.
*
* @param obj An object with the following properties:
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter tensor, rank 4, of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`. If strides is a single number, then `strideHeight ==
* strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels]. Only "NHWC" is currently supported.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
* @param bias Tensor to be added to the result.
* @param activation Name of activation kernel (defaults to `linear`).
* @param preluActivationWeights Tensor of prelu weights to be applied as part
* of a `prelu` activation, typically the same shape as `x`.
* @param leakyreluAlpha Optional. Alpha to be applied as part of a `leakyrelu`
* activation.
*/
function fusedDepthwiseConv2d_({ x, filter, strides, pad, dataFormat = 'NHWC', dilations = [1, 1], dimRoundingMode, bias, activation = 'linear', preluActivationWeights, leakyreluAlpha }) {
if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {
let result = depthwiseConv2d(x, filter, strides, pad, dataFormat, dilations, dimRoundingMode);
if (bias != null) {
result = add$1(result, bias);
}
return applyActivation(result, activation, preluActivationWeights, leakyreluAlpha);
}
const $x = convertToTensor(x, 'x', 'depthwiseConv2d');
const $filter = convertToTensor(filter, 'filter', 'depthwiseConv2d');
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
assert(x4D.rank === 4, () => `Error in fused depthwiseConv2d: input must be rank 4, but got ` +
`rank ${x4D.rank}.`);
assert($filter.rank === 4, () => `Error in fused depthwiseConv2d: filter must be rank 4, ` +
`but got rank ${$filter.rank}.`);
assert(x4D.shape[3] === $filter.shape[2], () => `Error in fused depthwiseConv2d: number of input channels ` +
`(${x4D.shape[3]}) must match the inChannels dimension in ` +
`filter ${$filter.shape[2]}.`);
if (dilations == null) {
dilations = [1, 1];
}
assert(eitherStridesOrDilationsAreOne(strides, dilations), () => 'Error in fused depthwiseConv2d: Either strides or dilations must ' +
`be 1. Got strides ${strides} and dilations '${dilations}'`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in fused depthwiseConv2d: pad must be an integer when ` +
`using dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const convInfo = computeConv2DInfo(x4D.shape, $filter.shape, strides, dilations, pad, dimRoundingMode, true /* depthwise */);
let $bias;
if (bias != null) {
$bias = convertToTensor(bias, 'bias', 'fused conv2d');
[$bias] = makeTypesMatch($bias, $x);
assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);
}
let $preluActivationWeights;
if (preluActivationWeights != null) {
$preluActivationWeights = convertToTensor(preluActivationWeights, 'prelu weights', 'fused depthwiseConv2d');
}
const grad = (dy, saved) => {
assert(tupleValuesAreOne(dilations), () => 'Error in gradient of fused depthwiseConv2d: dilation rates ' +
`greater than 1 are not yet supported. Got dilations ` +
`'${dilations}'`);
const [$filter, x4D, y, bias] = saved;
const dyActivation = getFusedDyActivation(dy, y, activation);
const xDer = depthwiseConv2dNativeBackpropInput(x4D.shape, dyActivation, $filter, strides, pad, dilations, dimRoundingMode);
const filterDer = depthwiseConv2dNativeBackpropFilter(x4D, dyActivation, $filter.shape, strides, pad, dilations, dimRoundingMode);
if (bias != null) {
const biasDer = getFusedBiasGradient($bias, dyActivation);
return [xDer, filterDer, biasDer];
}
return [xDer, filterDer];
};
const inputs = {
x: x4D,
filter: $filter,
bias: $bias,
preluActivationWeights: $preluActivationWeights
};
const attrs = {
strides,
pad,
dataFormat,
dilations,
dimRoundingMode,
activation,
leakyreluAlpha
};
// Depending on the the params passed in we will have different number of
// inputs and thus a a different number of elements in the gradient.
if (bias == null) {
const customOp = customGrad((x4D, filter, save) => {
// tslint:disable-next-line: no-unnecessary-type-assertion
let res = ENGINE.runKernel(FusedDepthwiseConv2D, inputs, attrs);
save([filter, x4D, res]);
if (reshapedTo4D) {
// tslint:disable-next-line: no-unnecessary-type-assertion
res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return { value: res, gradFunc: grad };
});
return customOp(x4D, $filter);
}
else {
const customOpWithBias = customGrad((x4D, filter, bias, save) => {
// tslint:disable-next-line: no-unnecessary-type-assertion
let res = ENGINE.runKernel(FusedDepthwiseConv2D, inputs, attrs);
save([filter, x4D, res, bias]);
if (reshapedTo4D) {
// tslint:disable-next-line: no-unnecessary-type-assertion
res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return { value: res, gradFunc: grad };
});
return customOpWithBias(x4D, $filter, $bias);
}
}
const depthwiseConv2d$1 = op({ fusedDepthwiseConv2d_ });
/**
* @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.
* =============================================================================
*/
/**
* Computes the dot product of two matrices with optional activation and bias.
*
* ```js
* const a = tf.tensor2d([-1, -2], [1, 2]);
* const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);
* const bias = tf.tensor2d([1, 2], [1, 2]);
*
* tf.fused.matMul({a, b, bias, activation: 'relu'}).print();
* ```
*
* @param obj An object with the following properties:
* - `a` First matrix in dot product operation.
* - `b` Second matrix in dot product operation.
* - `transposeA` If true, `a` is transposed before multiplication.
* - `transposeB` If true, `b` is transposed before multiplication.
* - `bias` Matrix to be added to the result.
* - `activation` Name of activation kernel (defaults to `linear`).
* - `preluActivationWeights` Tensor of prelu weights.
* - `leakyreluAlpha` Alpha of leakyrelu.
*/
function fusedMatMul_({ a, b, transposeA = false, transposeB = false, bias, activation = 'linear', preluActivationWeights, leakyreluAlpha, }) {
if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {
let result = matMul(a, b, transposeA, transposeB);
if (bias != null) {
result = add$1(result, bias);
}
return applyActivation(result, activation, preluActivationWeights, leakyreluAlpha);
}
let $a = convertToTensor(a, 'a', 'fused matMul');
let $b = convertToTensor(b, 'b', 'fused matMul');
[$a, $b] = makeTypesMatch($a, $b);
const innerShapeA = transposeA ? $a.shape[$a.rank - 2] : $a.shape[$a.rank - 1];
const innerShapeB = transposeB ? $b.shape[$b.rank - 1] : $b.shape[$b.rank - 2];
const outerShapeA = transposeA ? $a.shape[$a.rank - 1] : $a.shape[$a.rank - 2];
const outerShapeB = transposeB ? $b.shape[$b.rank - 2] : $b.shape[$b.rank - 1];
const outerDimsA = $a.shape.slice(0, -2);
const outerDimsB = $b.shape.slice(0, -2);
const batchDimA = sizeFromShape(outerDimsA);
const batchDimB = sizeFromShape(outerDimsB);
assert($a.rank >= 2 && $b.rank >= 2 && $a.rank === $b.rank, () => `Error in fused matMul: inputs must have the same rank of at ` +
`least 2, got ranks ${$a.rank} and ${$b.rank}.`);
assert(arraysEqual(outerDimsA, outerDimsB), () => `Error in fused matMul: outer dimensions (${outerDimsA}) and (` +
`${outerDimsB}) of Tensors with shapes ${$a.shape} and ` +
`${$b.shape} must match.`);
assert(innerShapeA === innerShapeB, () => `Error in fused matMul: inner shapes (${innerShapeA}) and (` +
`${innerShapeB}) of Tensors with shapes ${$a.shape} and ` +
`${$b.shape} and transposeA=${transposeA}` +
` and transposeB=${transposeB} must match.`);
const outShape = $a.shape.slice(0, -2).concat([outerShapeA, outerShapeB]);
const a3D = transposeA ?
reshape($a, [batchDimA, innerShapeA, outerShapeA]) :
reshape($a, [batchDimA, outerShapeA, innerShapeA]);
const b3D = transposeB ?
reshape($b, [batchDimB, outerShapeB, innerShapeB]) :
reshape($b, [batchDimB, innerShapeB, outerShapeB]);
let $bias;
if (bias != null) {
$bias = convertToTensor(bias, 'bias', 'fused matMul');
[$bias] = makeTypesMatch($bias, $a);
assertAndGetBroadcastShape(outShape, $bias.shape);
}
let $preluActivationWeights;
if (preluActivationWeights != null) {
$preluActivationWeights = convertToTensor(preluActivationWeights, 'prelu weights', 'fused matMul');
}
const grad = (dy, saved) => {
const [a3D, b3D, y, $bias] = saved;
// we reshape dy because the result of the forward is not
// necessarily going to be a 3d tensor due to a reshape done at the end of
// the customOp.
const dyActivation = getFusedDyActivation(reshape(dy, y.shape), y, activation);
let aDer;
let bDer;
if (!transposeA && !transposeB) {
aDer = matMul(dyActivation, b3D, false, true);
bDer = matMul(a3D, dyActivation, true, false);
}
else if (!transposeA && transposeB) {
aDer = matMul(dyActivation, b3D, false, false);
bDer = matMul(dyActivation, a3D, true, false);
}
else if (transposeA && !transposeB) {
aDer = matMul(b3D, dyActivation, false, true);
bDer = matMul(a3D, dyActivation, false, false);
}
else {
aDer = matMul(b3D, dyActivation, true, true);
bDer = matMul(dyActivation, a3D, true, true);
}
if (bias != null) {
const biasDer = getFusedBiasGradient($bias, dyActivation);
return [aDer, bDer, biasDer];
}
else {
return [aDer, bDer];
}
};
const inputs = {
a: a3D,
b: b3D,
bias: $bias,
preluActivationWeights: $preluActivationWeights
};
const attrs = { transposeA, transposeB, activation, leakyreluAlpha };
// Depending on the the params passed in we will have different number of
// inputs and thus a a different number of elements in the gradient.
if (bias == null) {
const customOp = customGrad((a3D, b3D, save) => {
const res =
// tslint:disable-next-line: no-unnecessary-type-assertion
ENGINE.runKernel(_FusedMatMul, inputs, attrs);
save([a3D, b3D, res]);
return { value: reshape(res, outShape), gradFunc: grad };
});
return customOp(a3D, b3D);
}
else {
const customOpWithBias = customGrad((a3D, b3D, $bias, save) => {
const res =
// tslint:disable-next-line: no-unnecessary-type-assertion
ENGINE.runKernel(_FusedMatMul, inputs, attrs);
save([a3D, b3D, res, $bias]);
return { value: reshape(res, outShape), gradFunc: grad };
});
return customOpWithBias(a3D, b3D, $bias);
}
}
const matMul$1 = op({ fusedMatMul_ });
/**
* @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.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Generate a hamming window.
*
* See: https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows
*
* ```js
* tf.signal.hammingWindow(10).print();
* ```
* @param The length of window
*
* @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}
*/
function hammingWindow_(windowLength) {
return cosineWindow(windowLength, 0.54, 0.46);
}
const hammingWindow = op({ hammingWindow_ });
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Generate a Hann window.
*
* See: https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows
*
* ```js
* tf.signal.hannWindow(10).print();
* ```
* @param The length of window
*
* @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}
*/
function hannWindow_(windowLength) {
return cosineWindow(windowLength, 0.5, 0.5);
}
const hannWindow = op({ hannWindow_ });
/**
* @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.
* =============================================================================
*/
/**
* Expands input into frames of frameLength.
* Slides a window size with frameStep.
*
* ```js
* tf.signal.frame([1, 2, 3], 2, 1).print();
* ```
* @param signal The input tensor to be expanded
* @param frameLength Length of each frame
* @param frameStep The frame hop size in samples.
* @param padEnd Whether to pad the end of signal with padValue.
* @param padValue An number to use where the input signal does
* not exist when padEnd is True.
*
* @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}
*/
function frame_(signal, frameLength, frameStep, padEnd = false, padValue = 0) {
let start = 0;
const output = [];
while (start + frameLength <= signal.size) {
output.push(slice(signal, start, frameLength));
start += frameStep;
}
if (padEnd) {
while (start < signal.size) {
const padLen = (start + frameLength) - signal.size;
const pad = concat([
slice(signal, start, frameLength - padLen), fill([padLen], padValue)
]);
output.push(pad);
start += frameStep;
}
}
if (output.length === 0) {
return tensor2d([], [0, frameLength]);
}
return reshape(concat(output), [output.length, frameLength]);
}
const frame = op({ frame_ });
/**
* @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.
* =============================================================================
*/
/**
* Computes the Short-time Fourier Transform of signals
* See: https://en.wikipedia.org/wiki/Short-time_Fourier_transform
*
* ```js
* const input = tf.tensor1d([1, 1, 1, 1, 1])
* tf.signal.stft(input, 3, 1).print();
* ```
* @param signal 1-dimensional real value tensor.
* @param frameLength The window length of samples.
* @param frameStep The number of samples to step.
* @param fftLength The size of the FFT to apply.
* @param windowFn A callable that takes a window length and returns 1-d tensor.
*
* @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}
*/
function stft_(signal, frameLength, frameStep, fftLength, windowFn = hannWindow) {
if (fftLength == null) {
fftLength = enclosingPowerOfTwo(frameLength);
}
const framedSignal = frame(signal, frameLength, frameStep);
const windowedSignal = mul(framedSignal, windowFn(frameLength));
return rfft(windowedSignal, fftLength);
}
const stft = op({ stft_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Extracts crops from the input image tensor and resizes them using bilinear
* sampling or nearest neighbor sampling (possibly with aspect ratio change)
* to a common output size specified by cropSize.
*
* @param image 4d tensor of shape `[batch,imageHeight,imageWidth, depth]`,
* where imageHeight and imageWidth must be positive, specifying the
* batch of images from which to take crops
* @param boxes 2d float32 tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the normalized
* coordinates of the box in the boxInd[i]'th image in the batch
* @param boxInd 1d int32 tensor of shape `[numBoxes]` with values in range
* `[0, batch)` that specifies the image that the `i`-th box refers to.
* @param cropSize 1d int32 tensor of 2 elements `[cropHeigh, cropWidth]`
* specifying the size to which all crops are resized to.
* @param method Optional string from `'bilinear' | 'nearest'`,
* defaults to bilinear, which specifies the sampling method for resizing
* @param extrapolationValue A threshold for deciding when to remove boxes based
* on score. Defaults to 0.
* @return A 4D tensor of the shape `[numBoxes,cropHeight,cropWidth,depth]`
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function cropAndResize_(image, boxes, boxInd, cropSize, method = 'bilinear', extrapolationValue = 0) {
const $image = convertToTensor(image, 'image', 'cropAndResize');
const $boxes = convertToTensor(boxes, 'boxes', 'cropAndResize', 'float32');
const $boxInd = convertToTensor(boxInd, 'boxInd', 'cropAndResize', 'int32');
const numBoxes = $boxes.shape[0];
assert($image.rank === 4, () => 'Error in cropAndResize: image must be rank 4,' +
`but got rank ${$image.rank}.`);
assert($boxes.rank === 2 && $boxes.shape[1] === 4, () => `Error in cropAndResize: boxes must be have size [${numBoxes},4] ` +
`but had shape ${$boxes.shape}.`);
assert($boxInd.rank === 1 && $boxInd.shape[0] === numBoxes, () => `Error in cropAndResize: boxInd must be have size [${numBoxes}] ` +
`but had shape ${$boxes.shape}.`);
assert(cropSize.length === 2, () => `Error in cropAndResize: cropSize must be of length 2, but got ` +
`length ${cropSize.length}.`);
assert(cropSize[0] >= 1 && cropSize[1] >= 1, () => `cropSize must be atleast [1,1], but was ${cropSize}`);
assert(method === 'bilinear' || method === 'nearest', () => `method must be bilinear or nearest, but was ${method}`);
const inputs = { image: $image, boxes: $boxes, boxInd: $boxInd };
const attrs = { method, extrapolationValue, cropSize };
const res = ENGINE.runKernel(CropAndResize, inputs, attrs);
return res;
}
const cropAndResize = op({ cropAndResize_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Flips the image left to right. Currently available in the CPU, WebGL, and
* WASM backends.
*
* @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.
*/
/** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */
function flipLeftRight_(image) {
const $image = convertToTensor(image, 'image', 'flipLeftRight', 'float32');
assert($image.rank === 4, () => 'Error in flipLeftRight: image must be rank 4,' +
`but got rank ${$image.rank}.`);
const inputs = { image: $image };
const res = ENGINE.runKernel(FlipLeftRight, inputs, {});
return res;
}
const flipLeftRight = op({ flipLeftRight_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Rotates the input image tensor counter-clockwise with an optional offset
* center of rotation. Currently available in the CPU, WebGL, and WASM backends.
*
* @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.
* @param radians The amount of rotation.
* @param fillValue The value to fill in the empty space leftover
* after rotation. Can be either a single grayscale value (0-255), or an
* array of three numbers `[red, green, blue]` specifying the red, green,
* and blue channels. Defaults to `0` (black).
* @param center The center of rotation. Can be either a single value (0-1), or
* an array of two numbers `[centerX, centerY]`. Defaults to `0.5` (rotates
* the image around its center).
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function rotateWithOffset_(image, radians, fillValue = 0, center = 0.5) {
const $image = convertToTensor(image, 'image', 'rotateWithOffset', 'float32');
assert($image.rank === 4, () => 'Error in rotateWithOffset: image must be rank 4,' +
`but got rank ${$image.rank}.`);
const inputs = { image: $image };
const attrs = { radians, fillValue, center };
const res = ENGINE.runKernel(RotateWithOffset, inputs, attrs);
return res;
}
const rotateWithOffset = op({ rotateWithOffset_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function nonMaxSuppSanityCheck(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
if (iouThreshold == null) {
iouThreshold = 0.5;
}
if (scoreThreshold == null) {
scoreThreshold = Number.NEGATIVE_INFINITY;
}
if (softNmsSigma == null) {
softNmsSigma = 0.0;
}
const numBoxes = boxes.shape[0];
maxOutputSize = Math.min(maxOutputSize, numBoxes);
assert(0 <= iouThreshold && iouThreshold <= 1, () => `iouThreshold must be in [0, 1], but was '${iouThreshold}'`);
assert(boxes.rank === 2, () => `boxes must be a 2D tensor, but was of rank '${boxes.rank}'`);
assert(boxes.shape[1] === 4, () => `boxes must have 4 columns, but 2nd dimension was ${boxes.shape[1]}`);
assert(scores.rank === 1, () => 'scores must be a 1D tensor');
assert(scores.shape[0] === numBoxes, () => `scores has incompatible shape with boxes. Expected ${numBoxes}, ` +
`but was ${scores.shape[0]}`);
assert(0 <= softNmsSigma && softNmsSigma <= 1, () => `softNmsSigma must be in [0, 1], but was '${softNmsSigma}'`);
return { maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma };
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Performs non maximum suppression of bounding boxes based on
* iou (intersection over union).
*
* @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of
* the bounding box.
* @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.
* @param maxOutputSize The maximum number of boxes to be selected.
* @param iouThreshold A float representing the threshold for deciding whether
* boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @return A 1D tensor with the selected box indices.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function nonMaxSuppression_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY) {
const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppression');
const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppression');
const inputs = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);
maxOutputSize = inputs.maxOutputSize;
iouThreshold = inputs.iouThreshold;
scoreThreshold = inputs.scoreThreshold;
const attrs = { maxOutputSize, iouThreshold, scoreThreshold };
return ENGINE.runKernel(NonMaxSuppressionV3, { boxes: $boxes, scores: $scores }, attrs);
}
const nonMaxSuppression = op({ nonMaxSuppression_ });
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Inserts a value into a sorted array. This method allows duplicate, meaning it
* allows inserting duplicate value, in which case, the element will be inserted
* at the lowest index of the value.
* @param arr The array to modify.
* @param element The element to insert.
* @param comparator Optional. If no comparator is specified, elements are
* compared using array_util.defaultComparator, which is suitable for Strings
* and Numbers in ascending arrays. If the array contains multiple instances of
* the target value, the left-most instance will be returned. To provide a
* comparator, it should take 2 arguments to compare and return a negative,
* zero, or a positive number.
*/
function binaryInsert(arr, element, comparator) {
const index = binarySearch(arr, element, comparator);
const insertionPoint = index < 0 ? -(index + 1) : index;
arr.splice(insertionPoint, 0, element);
}
/**
* Searches the array for the target using binary search, returns the index
* of the found element, or position to insert if element not found. If no
* comparator is specified, elements are compared using array_
* util.defaultComparator, which is suitable for Strings and Numbers in
* ascending arrays. If the array contains multiple instances of the target
* value, the left-most instance will be returned.
* @param arr The array to be searched in.
* @param target The target to be searched for.
* @param comparator Should take 2 arguments to compare and return a negative,
* zero, or a positive number.
* @return Lowest index of the target value if found, otherwise the insertion
* point where the target should be inserted, in the form of
* (-insertionPoint - 1).
*/
function binarySearch(arr, target, comparator) {
return binarySearch_(arr, target, comparator || defaultComparator);
}
/**
* Compares its two arguments for order.
* @param a The first element to be compared.
* @param b The second element to be compared.
* @return A negative number, zero, or a positive number as the first
* argument is less than, equal to, or greater than the second.
*/
function defaultComparator(a, b) {
return a > b ? 1 : a < b ? -1 : 0;
}
function binarySearch_(arr, target, comparator) {
let left = 0;
let right = arr.length;
let middle = 0;
let found = false;
while (left < right) {
middle = left + ((right - left) >>> 1);
const compareResult = comparator(target, arr[middle]);
if (compareResult > 0) {
left = middle + 1;
}
else {
right = middle;
// If compareResult is 0, the value is found. We record it is found,
// and then keep looking because there may be duplicate.
found = !compareResult;
}
}
return found ? left : -left - 1;
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function nonMaxSuppressionV3Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) {
return nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, 0 /* softNmsSigma */);
}
function nonMaxSuppressionV4Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize) {
return nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, 0 /* softNmsSigma */, false /* returnScoresTensor */, padToMaxOutputSize /* padToMaxOutputSize */, true
/* returnValidOutputs */ );
}
function nonMaxSuppressionV5Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
return nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma, true /* returnScoresTensor */);
}
function nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma, returnScoresTensor = false, padToMaxOutputSize = false, returnValidOutputs = false) {
// The list is sorted in ascending order, so that we can always pop the
// candidate with the largest score in O(1) time.
const candidates = [];
for (let i = 0; i < scores.length; i++) {
if (scores[i] > scoreThreshold) {
candidates.push({ score: scores[i], boxIndex: i, suppressBeginIndex: 0 });
}
}
candidates.sort(ascendingComparator);
// If softNmsSigma is 0, the outcome of this algorithm is exactly same as
// before.
const scale = softNmsSigma > 0 ? (-0.5 / softNmsSigma) : 0.0;
const selectedIndices = [];
const selectedScores = [];
while (selectedIndices.length < maxOutputSize && candidates.length > 0) {
const candidate = candidates.pop();
const { score: originalScore, boxIndex, suppressBeginIndex } = candidate;
if (originalScore < scoreThreshold) {
break;
}
// Overlapping boxes are likely to have similar scores, therefore we
// iterate through the previously selected boxes backwards in order to
// see if candidate's score should be suppressed. We use
// suppressBeginIndex to track and ensure a candidate can be suppressed
// by a selected box no more than once. Also, if the overlap exceeds
// iouThreshold, we simply ignore the candidate.
let ignoreCandidate = false;
for (let j = selectedIndices.length - 1; j >= suppressBeginIndex; --j) {
const iou = intersectionOverUnion(boxes, boxIndex, selectedIndices[j]);
if (iou >= iouThreshold) {
ignoreCandidate = true;
break;
}
candidate.score =
candidate.score * suppressWeight(iouThreshold, scale, iou);
if (candidate.score <= scoreThreshold) {
break;
}
}
// At this point, if `candidate.score` has not dropped below
// `scoreThreshold`, then we know that we went through all of the
// previous selections and can safely update `suppressBeginIndex` to the
// end of the selected array. Then we can re-insert the candidate with
// the updated score and suppressBeginIndex back in the candidate list.
// If on the other hand, `candidate.score` has dropped below the score
// threshold, we will not add it back to the candidates list.
candidate.suppressBeginIndex = selectedIndices.length;
if (!ignoreCandidate) {
// Candidate has passed all the tests, and is not suppressed, so
// select the candidate.
if (candidate.score === originalScore) {
selectedIndices.push(boxIndex);
selectedScores.push(candidate.score);
}
else if (candidate.score > scoreThreshold) {
// Candidate's score is suppressed but is still high enough to be
// considered, so add back to the candidates list.
binaryInsert(candidates, candidate, ascendingComparator);
}
}
}
// NonMaxSuppressionV4 feature: padding output to maxOutputSize.
const validOutputs = selectedIndices.length;
const elemsToPad = maxOutputSize - validOutputs;
if (padToMaxOutputSize && elemsToPad > 0) {
selectedIndices.push(...new Array(elemsToPad).fill(0));
selectedScores.push(...new Array(elemsToPad).fill(0.0));
}
const result = { selectedIndices };
if (returnScoresTensor) {
result['selectedScores'] = selectedScores;
}
if (returnValidOutputs) {
result['validOutputs'] = validOutputs;
}
return result;
}
function intersectionOverUnion(boxes, i, j) {
const iCoord = boxes.subarray(i * 4, i * 4 + 4);
const jCoord = boxes.subarray(j * 4, j * 4 + 4);
const yminI = Math.min(iCoord[0], iCoord[2]);
const xminI = Math.min(iCoord[1], iCoord[3]);
const ymaxI = Math.max(iCoord[0], iCoord[2]);
const xmaxI = Math.max(iCoord[1], iCoord[3]);
const yminJ = Math.min(jCoord[0], jCoord[2]);
const xminJ = Math.min(jCoord[1], jCoord[3]);
const ymaxJ = Math.max(jCoord[0], jCoord[2]);
const xmaxJ = Math.max(jCoord[1], jCoord[3]);
const areaI = (ymaxI - yminI) * (xmaxI - xminI);
const areaJ = (ymaxJ - yminJ) * (xmaxJ - xminJ);
if (areaI <= 0 || areaJ <= 0) {
return 0.0;
}
const intersectionYmin = Math.max(yminI, yminJ);
const intersectionXmin = Math.max(xminI, xminJ);
const intersectionYmax = Math.min(ymaxI, ymaxJ);
const intersectionXmax = Math.min(xmaxI, xmaxJ);
const intersectionArea = Math.max(intersectionYmax - intersectionYmin, 0.0) *
Math.max(intersectionXmax - intersectionXmin, 0.0);
return intersectionArea / (areaI + areaJ - intersectionArea);
}
// A Gaussian penalty function, this method always returns values in [0, 1].
// The weight is a function of similarity, the more overlap two boxes are, the
// smaller the weight is, meaning highly overlapping boxe will be significantly
// penalized. On the other hand, a non-overlapping box will not be penalized.
function suppressWeight(iouThreshold, scale, iou) {
const weight = Math.exp(scale * iou * iou);
return iou <= iouThreshold ? weight : 0.0;
}
function ascendingComparator(c1, c2) {
// For objects with same scores, we make the object with the larger index go
// first. In an array that pops from the end, this means that the object with
// the smaller index will be popped first. This ensures the same output as
// the TensorFlow python version.
return (c1.score - c2.score) ||
((c1.score === c2.score) && (c2.boxIndex - c1.boxIndex));
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Performs non maximum suppression of bounding boxes based on
* iou (intersection over union).
*
* This is the async version of `nonMaxSuppression`
*
* @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of
* the bounding box.
* @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.
* @param maxOutputSize The maximum number of boxes to be selected.
* @param iouThreshold A float representing the threshold for deciding whether
* boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @return A 1D tensor with the selected box indices.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
async function nonMaxSuppressionAsync_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY) {
const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');
const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');
const inputs = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);
maxOutputSize = inputs.maxOutputSize;
iouThreshold = inputs.iouThreshold;
scoreThreshold = inputs.scoreThreshold;
const boxesAndScores = await Promise.all([$boxes.data(), $scores.data()]);
const boxesVals = boxesAndScores[0];
const scoresVals = boxesAndScores[1];
// We call a cpu based impl directly with the typedarray data here rather
// than a kernel because all kernels are synchronous (and thus cannot await
// .data()).
const { selectedIndices } = nonMaxSuppressionV3Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold);
if ($boxes !== boxes) {
$boxes.dispose();
}
if ($scores !== scores) {
$scores.dispose();
}
return tensor1d(selectedIndices, 'int32');
}
const nonMaxSuppressionAsync = nonMaxSuppressionAsync_;
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Performs non maximum suppression of bounding boxes based on
* iou (intersection over union).
*
* This op also supports a Soft-NMS mode (c.f.
* Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score
* of other overlapping boxes, therefore favoring different regions of the image
* with high scores. To enable this Soft-NMS mode, set the `softNmsSigma`
* parameter to be larger than 0.
*
* @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of
* the bounding box.
* @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.
* @param maxOutputSize The maximum number of boxes to be selected.
* @param iouThreshold A float representing the threshold for deciding whether
* boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @param softNmsSigma A float representing the sigma parameter for Soft NMS.
* When sigma is 0, it falls back to nonMaxSuppression.
* @return A map with the following properties:
* - selectedIndices: A 1D tensor with the selected box indices.
* - selectedScores: A 1D tensor with the corresponding scores for each
* selected box.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function nonMaxSuppressionWithScore_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY, softNmsSigma = 0.0) {
const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppression');
const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppression');
const params = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
maxOutputSize = params.maxOutputSize;
iouThreshold = params.iouThreshold;
scoreThreshold = params.scoreThreshold;
softNmsSigma = params.softNmsSigma;
const inputs = { boxes: $boxes, scores: $scores };
const attrs = { maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma };
// tslint:disable-next-line: no-unnecessary-type-assertion
const result = ENGINE.runKernel(NonMaxSuppressionV5, inputs, attrs);
return { selectedIndices: result[0], selectedScores: result[1] };
}
const nonMaxSuppressionWithScore = op({ nonMaxSuppressionWithScore_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Asynchronously performs non maximum suppression of bounding boxes based on
* iou (intersection over union).
*
* This op also supports a Soft-NMS mode (c.f.
* Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score
* of other overlapping boxes, therefore favoring different regions of the image
* with high scores. To enable this Soft-NMS mode, set the `softNmsSigma`
* parameter to be larger than 0.
*
* @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of
* the bounding box.
* @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.
* @param maxOutputSize The maximum number of boxes to be selected.
* @param iouThreshold A float representing the threshold for deciding whether
* boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @param softNmsSigma A float representing the sigma parameter for Soft NMS.
* When sigma is 0, it falls back to nonMaxSuppression.
* @return A map with the following properties:
* - selectedIndices: A 1D tensor with the selected box indices.
* - selectedScores: A 1D tensor with the corresponding scores for each
* selected box.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
async function nonMaxSuppressionWithScoreAsync_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY, softNmsSigma = 0.0) {
const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');
const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');
const params = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
maxOutputSize = params.maxOutputSize;
iouThreshold = params.iouThreshold;
scoreThreshold = params.scoreThreshold;
softNmsSigma = params.softNmsSigma;
const boxesAndScores = await Promise.all([$boxes.data(), $scores.data()]);
const boxesVals = boxesAndScores[0];
const scoresVals = boxesAndScores[1];
// We call a cpu based impl directly with the typedarray data here rather
// than a kernel because all kernels are synchronous (and thus cannot await
// .data()).
const { selectedIndices, selectedScores } = nonMaxSuppressionV5Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
if ($boxes !== boxes) {
$boxes.dispose();
}
if ($scores !== scores) {
$scores.dispose();
}
return {
selectedIndices: tensor1d(selectedIndices, 'int32'),
selectedScores: tensor1d(selectedScores)
};
}
const nonMaxSuppressionWithScoreAsync = nonMaxSuppressionWithScoreAsync_;
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Asynchronously performs non maximum suppression of bounding boxes based on
* iou (intersection over union), with an option to pad results.
*
* @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of
* the bounding box.
* @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.
* @param maxOutputSize The maximum number of boxes to be selected.
* @param iouThreshold A float representing the threshold for deciding whether
* boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @param padToMaxOutputSize Defalts to false. If true, size of output
* `selectedIndices` is padded to maxOutputSize.
* @return A map with the following properties:
* - selectedIndices: A 1D tensor with the selected box indices.
* - validOutputs: A scalar denoting how many elements in `selectedIndices`
* are valid. Valid elements occur first, then padding.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function nonMaxSuppressionPadded_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY, padToMaxOutputSize = false) {
const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppression');
const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppression');
const params = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, null /* softNmsSigma */);
const $maxOutputSize = params.maxOutputSize;
const $iouThreshold = params.iouThreshold;
const $scoreThreshold = params.scoreThreshold;
const inputs = { boxes: $boxes, scores: $scores };
const attrs = {
maxOutputSize: $maxOutputSize,
iouThreshold: $iouThreshold,
scoreThreshold: $scoreThreshold,
padToMaxOutputSize
};
// tslint:disable-next-line: no-unnecessary-type-assertion
const result = ENGINE.runKernel(NonMaxSuppressionV4, inputs, attrs);
return { selectedIndices: result[0], validOutputs: result[1] };
}
const nonMaxSuppressionPadded = op({ nonMaxSuppressionPadded_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Asynchronously performs non maximum suppression of bounding boxes based on
* iou (intersection over union), with an option to pad results.
*
* @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of
* the bounding box.
* @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.
* @param maxOutputSize The maximum number of boxes to be selected.
* @param iouThreshold A float representing the threshold for deciding whether
* boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @param padToMaxOutputSize Defalts to false. If true, size of output
* `selectedIndices` is padded to maxOutputSize.
* @return A map with the following properties:
* - selectedIndices: A 1D tensor with the selected box indices.
* - validOutputs: A scalar denoting how many elements in `selectedIndices`
* are valid. Valid elements occur first, then padding.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
async function nonMaxSuppressionPaddedAsync_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY, padToMaxOutputSize = false) {
const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');
const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');
const params = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, null /* softNmsSigma */);
const $maxOutputSize = params.maxOutputSize;
const $iouThreshold = params.iouThreshold;
const $scoreThreshold = params.scoreThreshold;
const [boxesVals, scoresVals] = await Promise.all([$boxes.data(), $scores.data()]);
// We call a cpu based impl directly with the typedarray data here rather
// than a kernel because all kernels are synchronous (and thus cannot await
// .data()).
const { selectedIndices, validOutputs } = nonMaxSuppressionV4Impl(boxesVals, scoresVals, $maxOutputSize, $iouThreshold, $scoreThreshold, padToMaxOutputSize);
if ($boxes !== boxes) {
$boxes.dispose();
}
if ($scores !== scores) {
$scores.dispose();
}
return {
selectedIndices: tensor1d(selectedIndices, 'int32'),
validOutputs: scalar(validOutputs, 'int32')
};
}
const nonMaxSuppressionPaddedAsync = nonMaxSuppressionPaddedAsync_;
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Bilinear resize a single 3D image or a batch of 3D images to a new shape.
*
* @param images The images, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param size The new shape `[newHeight, newWidth]` to resize the
* images to. Each channel is resized individually.
* @param alignCorners Defaults to `false`. If true, rescale
* input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4
* corners of images and resized images. If false, rescale by
* `new_height / height`. Treat similarly the width dimension.
* @param halfPixelCenters Defaults to `false`. Whether to assume pixel centers
* are at 0.5, which would make the floating point coordinates of the top
* left pixel 0.5, 0.5.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function resizeBilinear_(images, size, alignCorners = false, halfPixelCenters = false) {
const $images = convertToTensor(images, 'images', 'resizeBilinear');
assert($images.rank === 3 || $images.rank === 4, () => `Error in resizeBilinear: x must be rank 3 or 4, but got ` +
`rank ${$images.rank}.`);
assert(size.length === 2, () => `Error in resizeBilinear: new shape must 2D, but got shape ` +
`${size}.`);
assert(halfPixelCenters === false || alignCorners === false, () => `Error in resizeBilinear: If halfPixelCenters is true, ` +
`alignCorners must be false.`);
let batchImages = $images;
let reshapedTo4D = false;
if ($images.rank === 3) {
reshapedTo4D = true;
batchImages = reshape($images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);
}
const [] = size;
const inputs = { images: batchImages };
const attrs = { alignCorners, halfPixelCenters, size };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(ResizeBilinear, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const resizeBilinear = op({ resizeBilinear_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* NearestNeighbor resize a batch of 3D images to a new shape.
*
* @param images The images, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param size The new shape `[newHeight, newWidth]` to resize the
* images to. Each channel is resized individually.
* @param alignCorners Defaults to False. If true, rescale
* input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4
* corners of images and resized images. If false, rescale by
* `new_height / height`. Treat similarly the width dimension.
* @param halfPixelCenters Defaults to `false`. Whether to assumes pixels are of
* half the actual dimensions, and yields more accurate resizes. This flag
* would also make the floating point coordinates of the top left pixel
* 0.5, 0.5.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function resizeNearestNeighbor_(images, size, alignCorners = false, halfPixelCenters = false) {
const $images = convertToTensor(images, 'images', 'resizeNearestNeighbor');
assert($images.rank === 3 || $images.rank === 4, () => `Error in resizeNearestNeighbor: x must be rank 3 or 4, but got ` +
`rank ${$images.rank}.`);
assert(size.length === 2, () => `Error in resizeNearestNeighbor: new shape must 2D, but got shape ` +
`${size}.`);
assert($images.dtype === 'float32' || $images.dtype === 'int32', () => '`images` must have `int32` or `float32` as dtype');
assert(halfPixelCenters === false || alignCorners === false, () => `Error in resizeNearestNeighbor: If halfPixelCenters is true, ` +
`alignCorners must be false.`);
let batchImages = $images;
let reshapedTo4D = false;
if ($images.rank === 3) {
reshapedTo4D = true;
batchImages = reshape($images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);
}
const [] = size;
const inputs = { images: batchImages };
const attrs = { alignCorners, halfPixelCenters, size };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(ResizeNearestNeighbor, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const resizeNearestNeighbor = op({ resizeNearestNeighbor_ });
/**
* @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.
* =============================================================================
*/
/**
* Applies the given transform(s) to the image(s).
*
* @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.
* @param transforms Projective transform matrix/matrices. A tensor1d of length
* 8 or tensor of size N x 8. If one row of transforms is [a0, a1, a2, b0
* b1, b2, c0, c1], then it maps the output point (x, y) to a transformed
* input point (x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k),
* where k = c0 x + c1 y + 1. The transforms are inverted compared to the
* transform mapping input points to output points.
* @param interpolation Interpolation mode.
* Supported values: 'nearest', 'bilinear'. Default to 'nearest'.
* @param fillMode Points outside the boundaries of the input are filled
* according to the given mode, one of 'constant', 'reflect', 'wrap',
* 'nearest'. Default to 'constant'.
* 'reflect': (d c b a | a b c d | d c b a ) The input is extended by
* reflecting about the edge of the last pixel.
* 'constant': (k k k k | a b c d | k k k k) The input is extended by
* filling all values beyond the edge with the same constant value k.
* 'wrap': (a b c d | a b c d | a b c d) The input is extended by
* wrapping around to the opposite edge.
* 'nearest': (a a a a | a b c d | d d d d) The input is extended by
* the nearest pixel.
* @param fillValue A float represents the value to be filled outside the
* boundaries when fillMode is 'constant'.
* @param Output dimension after the transform, [height, width]. If undefined,
* output is the same size as input image.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function transform_(image, transforms, interpolation = 'nearest', fillMode = 'constant', fillValue = 0, outputShape) {
const $image = convertToTensor(image, 'image', 'transform', 'float32');
const $transforms = convertToTensor(transforms, 'transforms', 'transform', 'float32');
assert($image.rank === 4, () => 'Error in transform: image must be rank 4,' +
`but got rank ${$image.rank}.`);
assert($transforms.rank === 2 &&
($transforms.shape[0] === $image.shape[0] ||
$transforms.shape[0] === 1) &&
$transforms.shape[1] === 8, () => `Error in transform: Input transform should be batch x 8 or 1 x 8`);
assert(outputShape == null || outputShape.length === 2, () => 'Error in transform: outputShape must be [height, width] or null, ' +
`but got ${outputShape}.`);
const inputs = { image: $image, transforms: $transforms };
const attrs = { interpolation, fillMode, fillValue, outputShape };
return ENGINE.runKernel(Transform, inputs, attrs);
}
const transform = op({ transform_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Copy a tensor setting everything outside a central band in each innermost
* matrix to zero.
*
* The band part is computed as follows: Assume input has `k` dimensions
* `[I, J, K, ..., M, N]`, then the output is a tensor with the same shape where
* `band[i, j, k, ..., m, n] = in_band(m, n) * input[i, j, k, ..., m, n]`.
* The indicator function
* `in_band(m, n) = (num_lower < 0 || (m-n) <= num_lower))`
* `&& (num_upper < 0 || (n-m) <= num_upper)`
*
* ```js
* const x = tf.tensor2d([[ 0, 1, 2, 3],
* [-1, 0, 1, 2],
* [-2, -1, 0, 1],
* [-3, -2, -1, 0]]);
* let y = tf.linalg.bandPart(x, 1, -1);
* y.print(); // [[ 0, 1, 2, 3],
* // [-1, 0, 1, 2],
* // [ 0, -1, 0, 1],
* // [ 0, 0 , -1, 0]]
* let z = tf.linalg.bandPart(x, 2, 1);
* z.print(); // [[ 0, 1, 0, 0],
* // [-1, 0, 1, 0],
* // [-2, -1, 0, 1],
* // [ 0, -2, -1, 0]]
* ```
*
* @param x Rank `k` tensor
* @param numLower Number of subdiagonals to keep.
* If negative, keep entire lower triangle.
* @param numUpper Number of subdiagonals to keep.
* If negative, keep entire upper triangle.
* @returns Rank `k` tensor of the same shape as input.
* The extracted banded tensor.
*
* @doc {heading:'Operations', subheading:'Linear Algebra', namespace:'linalg'}
*/
function bandPart_(a, numLower, numUpper) {
assert(numLower % 1 === 0, () => `bandPart(): numLower must be an integer, got ${numLower}.`);
assert(numUpper % 1 === 0, () => `bandPart(): numUpper must be an integer, got ${numUpper}.`);
const $a = convertToTensor(a, 'a', 'bandPart');
assert($a.rank >= 2, () => `bandPart(): Rank must be at least 2, got ${$a.rank}.`);
const shape = $a.shape;
const [M, N] = $a.shape.slice(-2);
if (!(numLower <= M)) {
throw new Error(`bandPart(): numLower (${numLower})` +
` must not be greater than the number of rows (${M}).`);
}
if (!(numUpper <= N)) {
throw new Error(`bandPart(): numUpper (${numUpper})` +
` must not be greater than the number of columns (${N}).`);
}
if (numLower < 0) {
numLower = M;
}
if (numUpper < 0) {
numUpper = N;
}
const i = reshape(range(0, M, 1, 'int32'), [-1, 1]);
const j = range(0, N, 1, 'int32');
const ij = sub(i, j);
const inBand = logicalAnd(lessEqual(ij, scalar(+numLower, 'int32')), greaterEqual(ij, scalar(-numUpper, 'int32')));
const zero = zeros([M, N], $a.dtype);
return reshape(stack(unstack(reshape($a, [-1, M, N]))
.map(mat => where(inBand, mat, zero))), shape);
}
const bandPart = op({ bandPart_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Gram-Schmidt orthogonalization.
*
* ```js
* const x = tf.tensor2d([[1, 2], [3, 4]]);
* let y = tf.linalg.gramSchmidt(x);
* y.print();
* console.log('Othogonalized:');
* y.dot(y.transpose()).print(); // should be nearly the identity matrix.
* console.log('First row direction maintained:');
* const data = await y.array();
* console.log(data[0][1] / data[0][0]); // should be nearly 2.
* ```
*
* @param xs The vectors to be orthogonalized, in one of the two following
* formats:
* - An Array of `tf.Tensor1D`.
* - A `tf.Tensor2D`, i.e., a matrix, in which case the vectors are the rows
* of `xs`.
* In each case, all the vectors must have the same length and the length
* must be greater than or equal to the number of vectors.
* @returns The orthogonalized and normalized vectors or matrix.
* Orthogonalization means that the vectors or the rows of the matrix
* are orthogonal (zero inner products). Normalization means that each
* vector or each row of the matrix has an L2 norm that equals `1`.
*
* @doc {heading:'Operations', subheading:'Linear Algebra', namespace:'linalg'}
*/
function gramSchmidt_(xs) {
let inputIsTensor2D;
if (Array.isArray(xs)) {
inputIsTensor2D = false;
assert(xs != null && xs.length > 0, () => 'Gram-Schmidt process: input must not be null, undefined, or ' +
'empty');
const dim = xs[0].shape[0];
for (let i = 1; i < xs.length; ++i) {
assert(xs[i].shape[0] === dim, () => 'Gram-Schmidt: Non-unique lengths found in the input vectors: ' +
`(${xs[i].shape[0]} vs. ${dim})`);
}
}
else {
inputIsTensor2D = true;
xs = split(xs, xs.shape[0], 0).map(x => squeeze(x, [0]));
}
assert(xs.length <= xs[0].shape[0], () => `Gram-Schmidt: Number of vectors (${xs.length}) exceeds ` +
`number of dimensions (${xs[0].shape[0]}).`);
const ys = [];
const xs1d = xs;
for (let i = 0; i < xs.length; ++i) {
ys.push(ENGINE.tidy(() => {
let x = xs1d[i];
if (i > 0) {
for (let j = 0; j < i; ++j) {
const proj = mul(sum$1(mul(ys[j], x)), ys[j]);
x = sub(x, proj);
}
}
return div(x, norm(x, 'euclidean'));
}));
}
if (inputIsTensor2D) {
return stack(ys, 0);
}
else {
return ys;
}
}
const gramSchmidt = op({ gramSchmidt_ });
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Enables production mode which disables correctness checks in favor of
* performance.
*
* @doc {heading: 'Environment'}
*/
function enableProdMode() {
env().set('PROD', true);
}
/**
* Enables debug mode which will log information about all executed kernels:
* the elapsed time of the kernel execution, as well as the rank, shape, and
* size of the output tensor.
*
* Debug mode will significantly slow down your application as it will
* download the result of every operation to the CPU. This should not be used in
* production. Debug mode does not affect the timing information of the kernel
* execution as we do not measure download time in the kernel execution time.
*
* See also: `tf.profile`, `tf.memory`.
*
* @doc {heading: 'Environment'}
*/
function enableDebugMode() {
env().set('DEBUG', true);
}
/** Globally disables deprecation warnings */
function disableDeprecationWarnings() {
env().set('DEPRECATION_WARNINGS_ENABLED', false);
console.warn(`TensorFlow.js deprecation warnings have been disabled.`);
}
/** Warn users about deprecated functionality. */
function deprecationWarn(msg) {
if (env().getBool('DEPRECATION_WARNINGS_ENABLED')) {
console.warn(msg + ' You can disable deprecation warnings with ' +
'tf.disableDeprecationWarnings().');
}
}
setDeprecationWarningFn(deprecationWarn);
/**
* Dispose all variables kept in backend engine.
*
* @doc {heading: 'Environment'}
*/
function disposeVariables() {
ENGINE.disposeVariables();
}
/**
* It returns the global engine that keeps track of all tensors and backends.
*
* @doc {heading: 'Environment'}
*/
function engine() {
return ENGINE;
}
/**
* Returns memory info at the current time in the program. The result is an
* object with the following properties:
*
* - `numBytes`: Number of bytes allocated (undisposed) at this time.
* - `numTensors`: Number of unique tensors allocated.
* - `numDataBuffers`: Number of unique data buffers allocated
* (undisposed) at this time, which is ≤ the number of tensors
* (e.g. `a.reshape(newShape)` makes a new Tensor that shares the same
* data buffer with `a`).
* - `unreliable`: True if the memory usage is unreliable. See `reasons` when
* `unreliable` is true.
* - `reasons`: `string[]`, reasons why the memory is unreliable, present if
* `unreliable` is true.
*
* WebGL Properties:
* - `numBytesInGPU`: Number of bytes allocated (undisposed) in the GPU only at
* this time.
*
* @doc {heading: 'Performance', subheading: 'Memory'}
*/
function memory() {
return ENGINE.memory();
}
/**
* Executes the provided function `f()` and returns a promise that resolves
* with information about the function's memory use:
* - `newBytes`: the number of new bytes allocated
* - `newTensors`: the number of new tensors created
* - `peakBytes`: the peak number of bytes allocated
* - `kernels`: an array of objects for each kernel involved that reports
* their input and output shapes, number of bytes used, and number of new
* tensors created.
* - `kernelNames`: an array of unique strings with just the names of the
* kernels in the `kernels` array.
*
* ```js
* const profile = await tf.profile(() => {
* const x = tf.tensor1d([1, 2, 3]);
* let x2 = x.square();
* x2.dispose();
* x2 = x.square();
* x2.dispose();
* return x;
* });
*
* console.log(`newBytes: ${profile.newBytes}`);
* console.log(`newTensors: ${profile.newTensors}`);
* console.log(`byte usage over all kernels: ${profile.kernels.map(k =>
* k.totalBytesSnapshot)}`);
* ```
*
*
* @doc {heading: 'Performance', subheading: 'Profile'}
*/
function profile(f) {
return ENGINE.profile(f);
}
/**
* Executes the provided function `fn` and after it is executed, cleans up all
* intermediate tensors allocated by `fn` except those returned by `fn`.
* `fn` must not return a Promise (async functions not allowed). The returned
* result can be a complex object.
*
* Using this method helps avoid memory leaks. In general, wrap calls to
* operations in `tf.tidy` for automatic memory cleanup.
*
* NOTE: Variables do *not* get cleaned up when inside a tidy(). If you want to
* dispose variables, please use `tf.disposeVariables` or call dispose()
* directly on variables.
*
* ```js
* // y = 2 ^ 2 + 1
* const y = tf.tidy(() => {
* // a, b, and one will be cleaned up when the tidy ends.
* const one = tf.scalar(1);
* const a = tf.scalar(2);
* const b = a.square();
*
* console.log('numTensors (in tidy): ' + tf.memory().numTensors);
*
* // The value returned inside the tidy function will return
* // through the tidy, in this case to the variable y.
* return b.add(one);
* });
*
* console.log('numTensors (outside tidy): ' + tf.memory().numTensors);
* y.print();
* ```
*
* @param nameOrFn The name of the closure, or the function to execute.
* If a name is provided, the 2nd argument should be the function.
* If debug mode is on, the timing and the memory usage of the function
* will be tracked and displayed on the console using the provided name.
* @param fn The function to execute.
*
* @doc {heading: 'Performance', subheading: 'Memory'}
*/
function tidy(nameOrFn, fn) {
return ENGINE.tidy(nameOrFn, fn);
}
/**
* Disposes any `tf.Tensor`s found within the provided object.
*
* @param container an object that may be a `tf.Tensor` or may directly
* contain `tf.Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. If
* the object is not a `tf.Tensor` or does not contain `Tensors`, nothing
* happens. In general it is safe to pass any object here, except that
* `Promise`s are not supported.
*
* @doc {heading: 'Performance', subheading: 'Memory'}
*/
function dispose(container) {
const tensors = getTensorsInContainer(container);
tensors.forEach(tensor => tensor.dispose());
}
/**
* Keeps a `tf.Tensor` generated inside a `tf.tidy` from being disposed
* automatically.
*
* ```js
* let b;
* const y = tf.tidy(() => {
* const one = tf.scalar(1);
* const a = tf.scalar(2);
*
* // b will not be cleaned up by the tidy. a and one will be cleaned up
* // when the tidy ends.
* b = tf.keep(a.square());
*
* console.log('numTensors (in tidy): ' + tf.memory().numTensors);
*
* // The value returned inside the tidy function will return
* // through the tidy, in this case to the variable y.
* return b.add(one);
* });
*
* console.log('numTensors (outside tidy): ' + tf.memory().numTensors);
* console.log('y:');
* y.print();
* console.log('b:');
* b.print();
* ```
*
* @param result The tensor to keep from being disposed.
*
* @doc {heading: 'Performance', subheading: 'Memory'}
*/
function keep(result) {
return ENGINE.keep(result);
}
/**
* Executes `f()` and returns a promise that resolves with timing
* information.
*
* The result is an object with the following properties:
*
* - `wallMs`: Wall execution time.
* - `kernelMs`: Kernel execution time, ignoring data transfer. If using the
* WebGL backend and the query timer extension is not available, this will
* return an error object.
* - On `WebGL` The following additional properties exist:
* - `uploadWaitMs`: CPU blocking time on texture uploads.
* - `downloadWaitMs`: CPU blocking time on texture downloads (readPixels).
*
* ```js
* const x = tf.randomNormal([20, 20]);
* const time = await tf.time(() => x.matMul(x));
*
* console.log(`kernelMs: ${time.kernelMs}, wallTimeMs: ${time.wallMs}`);
* ```
*
* @param f The function to execute and time.
*
* @doc {heading: 'Performance', subheading: 'Timing'}
*/
function time(f) {
return ENGINE.time(f);
}
/**
* Sets the backend (cpu, webgl, wasm, etc) responsible for creating tensors and
* executing operations on those tensors. Returns a promise that resolves
* to a boolean if the backend initialization was successful.
*
* Note this disposes the current backend, if any, as well as any tensors
* associated with it. A new backend is initialized, even if it is of the
* same type as the previous one.
*
* @param backendName The name of the backend. Currently supports
* `'webgl'|'cpu'` in the browser, `'tensorflow'` under node.js
* (requires tfjs-node), and `'wasm'` (requires tfjs-backend-wasm).
*
* @doc {heading: 'Backends'}
*/
function setBackend(backendName) {
return ENGINE.setBackend(backendName);
}
/**
* Returns a promise that resolves when the currently selected backend (or the
* highest priority one) has initialized. Await this promise when you are using
* a backend that has async initialization.
*
* @doc {heading: 'Backends'}
*/
function ready() {
return ENGINE.ready();
}
/**
* Returns the current backend name (cpu, webgl, etc). The backend is
* responsible for creating tensors and executing operations on those tensors.
*
* @doc {heading: 'Backends'}
*/
function getBackend() {
return ENGINE.backendName;
}
/**
* Removes a backend and the registered factory.
*
* @doc {heading: 'Backends'}
*/
function removeBackend(name) {
ENGINE.removeBackend(name);
}
/**
* Finds the backend registered under the provided name. Returns null if the
* name is not in the registry, or the registration hasn't finished yet.
*/
function findBackend(name) {
return ENGINE.findBackend(name);
}
/**
* Finds the backend factory registered under the provided name. Returns a
* function that produces a new backend when called. Returns null if the name
* is not in the registry.
*/
function findBackendFactory(name) {
return ENGINE.findBackendFactory(name);
}
/**
* Registers a global backend. The registration should happen when importing
* a module file (e.g. when importing `backend_webgl.ts`), and is used for
* modular builds (e.g. custom tfjs bundle with only webgl support).
*
* @param factory The backend factory function. When called, it should
* return a backend instance, or a promise of an instance.
* @param priority The priority of the backend (higher = more important).
* In case multiple backends are registered, the priority is used to find
* the best backend. Defaults to 1.
* @return False if there is already a registered backend under this name, true
* if not.
*
* @doc {heading: 'Backends'}
*/
function registerBackend(name, factory, priority = 1) {
return ENGINE.registerBackend(name, factory, priority);
}
/**
* Gets the current backend. If no backends have been initialized, this will
* attempt to initialize the best backend. Will throw an error if the highest
* priority backend has async initialization, in which case, you should call
* 'await tf.ready()' before running other code.
*
* @doc {heading: 'Backends'}
*/
function backend() {
return ENGINE.backend;
}
/**
* Sets the global platform.
*
* @param platformName The name of this platform.
* @param platform A platform implementation.
*/
function setPlatform(platformName, platform) {
env().setPlatform(platformName, platform);
}
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Compute QR decomposition of m-by-n matrix using Householder transformation.
*
* Implementation based on
* [http://www.cs.cornell.edu/~bindel/class/cs6210-f09/lec18.pdf]
* (http://www.cs.cornell.edu/~bindel/class/cs6210-f09/lec18.pdf)
*
* ```js
* const a = tf.tensor2d([[1, 2], [3, 4]]);
* let [q, r] = tf.linalg.qr(a);
* console.log('Q');
* q.print();
* console.log('R');
* r.print();
* console.log('Orthogonalized');
* q.dot(q.transpose()).print() // should be nearly the identity matrix.
* console.log('Reconstructed');
* q.dot(r).print(); // should be nearly [[1, 2], [3, 4]];
* ```
*
* @param x The `tf.Tensor` to be QR-decomposed. Must have rank >= 2. Suppose
* it has the shape `[..., M, N]`.
* @param fullMatrices An optional boolean parameter. Defaults to `false`.
* If `true`, compute full-sized `Q`. If `false` (the default),
* compute only the leading N columns of `Q` and `R`.
* @returns An `Array` of two `tf.Tensor`s: `[Q, R]`. `Q` is a unitary matrix,
* i.e., its columns all have unit norm and are mutually orthogonal.
* If `M >= N`,
* If `fullMatrices` is `false` (default),
* - `Q` has a shape of `[..., M, N]`,
* - `R` has a shape of `[..., N, N]`.
* If `fullMatrices` is `true` (default),
* - `Q` has a shape of `[..., M, M]`,
* - `R` has a shape of `[..., M, N]`.
* If `M < N`,
* - `Q` has a shape of `[..., M, M]`,
* - `R` has a shape of `[..., M, N]`.
* @throws If the rank of `x` is less than 2.
*
* @doc {heading:'Operations',
* subheading:'Linear Algebra',
* namespace:'linalg'}
*/
function qr_(x, fullMatrices = false) {
assert(x.rank >= 2, () => `qr() requires input tensor to have a rank >= 2, but got rank ${x.rank}`);
if (x.rank === 2) {
return qr2d(x, fullMatrices);
}
else {
// Rank > 2.
// TODO(cais): Below we split the input into individual 2D tensors,
// perform QR decomposition on them and then stack the results back
// together. We should explore whether this can be parallelized.
const outerDimsProd = x.shape.slice(0, x.shape.length - 2)
.reduce((value, prev) => value * prev);
const x2ds = unstack(reshape(x, [
outerDimsProd, x.shape[x.shape.length - 2],
x.shape[x.shape.length - 1]
]), 0);
const q2ds = [];
const r2ds = [];
x2ds.forEach(x2d => {
const [q2d, r2d] = qr2d(x2d, fullMatrices);
q2ds.push(q2d);
r2ds.push(r2d);
});
const q = reshape(stack(q2ds, 0), x.shape);
const r = reshape(stack(r2ds, 0), x.shape);
return [q, r];
}
}
function qr2d(x, fullMatrices = false) {
return ENGINE.tidy(() => {
assert(x.shape.length === 2, () => `qr2d() requires a 2D Tensor, but got a ${x.shape.length}D Tensor.`);
const m = x.shape[0];
const n = x.shape[1];
let q = eye(m); // Orthogonal transform so far.
let r = clone(x); // Transformed matrix so far.
const one2D = tensor2d([[1]], [1, 1]);
let w = clone(one2D);
const iters = m >= n ? n : m;
for (let j = 0; j < iters; ++j) {
// This tidy within the for-loop ensures we clean up temporary
// tensors as soon as they are no longer needed.
const rTemp = r;
const wTemp = w;
const qTemp = q;
[w, r, q] = ENGINE.tidy(() => {
// Find H = I - tau * w * w', to put zeros below R(j, j).
const rjEnd1 = slice(r, [j, j], [m - j, 1]);
const normX = norm(rjEnd1);
const rjj = slice(r, [j, j], [1, 1]);
// The sign() function returns 0 on 0, which causes division by zero.
const s = where(greater(rjj, 0), tensor2d([[-1]]), tensor2d([[1]]));
const u1 = sub(rjj, mul(s, normX));
const wPre = div(rjEnd1, u1);
if (wPre.shape[0] === 1) {
w = clone(one2D);
}
else {
w = concat([
one2D,
slice(wPre, [1, 0], [wPre.shape[0] - 1, wPre.shape[1]])
], 0);
}
const tau = neg(div(matMul(s, u1), normX));
// -- R := HR, Q := QH.
const rjEndAll = slice(r, [j, 0], [m - j, n]);
const tauTimesW = mul(tau, w);
const wT = transpose(w);
if (j === 0) {
r = sub(rjEndAll, matMul(tauTimesW, matMul(wT, rjEndAll)));
}
else {
const rTimesTau = sub(rjEndAll, matMul(tauTimesW, matMul(wT, rjEndAll)));
r = concat([slice(r, [0, 0], [j, n]), rTimesTau], 0);
}
const tawTimesWT = transpose(tauTimesW);
const qAllJEnd = slice(q, [0, j], [m, q.shape[1] - j]);
if (j === 0) {
q = sub(qAllJEnd, matMul(matMul(qAllJEnd, w), tawTimesWT));
}
else {
const qTimesTau = sub(qAllJEnd, matMul(matMul(qAllJEnd, w), tawTimesWT));
q = concat([slice(q, [0, 0], [m, j]), qTimesTau], 1);
}
return [w, r, q];
});
dispose([rTemp, wTemp, qTemp]);
}
if (!fullMatrices && m > n) {
q = slice(q, [0, 0], [m, n]);
r = slice(r, [0, 0], [n, n]);
}
return [q, r];
});
}
const qr = op({ qr_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
var Reduction;
(function (Reduction) {
Reduction[Reduction["NONE"] = 0] = "NONE";
Reduction[Reduction["MEAN"] = 1] = "MEAN";
Reduction[Reduction["SUM"] = 2] = "SUM";
Reduction[Reduction["SUM_BY_NONZERO_WEIGHTS"] = 3] = "SUM_BY_NONZERO_WEIGHTS";
})(Reduction || (Reduction = {}));
/**
* Computes the weighted loss between two tensors.
*
* @param losses Tensor of shape `[batch_size, d1, ... dN]`.
* @param weights Tensor whose rank is either 0, or the same rank as
* `losses`, and must be broadcastable to `losses` (i.e., all
* dimensions must be either `1`, or the same as the corresponding
* `losses` dimension).
*
* @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}
*/
function computeWeightedLoss_(losses, weights, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
const $losses = convertToTensor(losses, 'losses', 'computeWeightedLoss');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'computeWeightedLoss');
}
const weightedLoss = ($weights == null) ? $losses : mul($losses, $weights);
if (reduction === Reduction.NONE) {
return weightedLoss;
}
if (reduction === Reduction.SUM) {
return sum$1(weightedLoss);
}
if (reduction === Reduction.MEAN) {
if ($weights == null) {
return mean(weightedLoss);
}
else {
const broadcastFactor = $losses.size / $weights.size;
const result = div(sum$1(weightedLoss), sum$1($weights));
return broadcastFactor > 1 ? div(result, scalar(broadcastFactor)) :
result;
}
}
if (reduction === Reduction.SUM_BY_NONZERO_WEIGHTS) {
if ($weights == null) {
return div(sum$1(weightedLoss), scalar($losses.size));
}
else {
const broadcastedWeights = mul($weights, ones$1($losses.shape));
const numNonZeros = cast(sum$1(notEqual(broadcastedWeights, scalar(0))), 'float32');
return div(sum$1(weightedLoss), numNonZeros);
}
}
throw Error(`Unknown reduction: ${reduction}`);
}
const computeWeightedLoss = op({ computeWeightedLoss_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the absolute difference loss between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*
* @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}
*/
function absoluteDifference_(labels, predictions, weights, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
const $labels = convertToTensor(labels, 'labels', 'absoluteDifference');
const $predictions = convertToTensor(predictions, 'predictions', 'absoluteDifference');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'absoluteDifference');
}
assertShapesMatch($labels.shape, $predictions.shape, 'Error in absoluteDifference: ');
const losses = abs(sub($labels, $predictions));
return computeWeightedLoss(losses, $weights, reduction);
}
const absoluteDifference = op({ absoluteDifference_ });
/**
* Computes the cosine distance loss between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param axis The dimension along which the cosine distance is computed.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*
* @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}
*/
function cosineDistance_(labels, predictions, axis, weights, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
const $labels = convertToTensor(labels, 'labels', 'cosineDistance');
const $predictions = convertToTensor(predictions, 'predictions', 'cosineDistance');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'cosineDistance');
}
assertShapesMatch($labels.shape, $predictions.shape, 'Error in cosineDistance: ');
const one = scalar(1);
const losses = sub(one, sum$1(mul($labels, $predictions), axis, true));
return computeWeightedLoss(losses, $weights, reduction);
}
const cosineDistance = op({ cosineDistance_ });
/**
* Computes the Hinge loss between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*
* @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}
*/
function hingeLoss_(labels, predictions, weights, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
let $labels = convertToTensor(labels, 'labels', 'hingeLoss');
const $predictions = convertToTensor(predictions, 'predictions', 'hingeLoss');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'hingeLoss');
}
assertShapesMatch($labels.shape, $predictions.shape, 'Error in hingeLoss: ');
const one = scalar(1);
// Convert binary labels to (-1, 1)
$labels = sub(mul(scalar(2), $labels), one);
const losses = relu(sub(one, mul($labels, $predictions)));
return computeWeightedLoss(losses, $weights, reduction);
}
const hingeLoss = op({ hingeLoss_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the huber loss between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param delta Point where huber loss changes from quadratic to linear.
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`.
*
* @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}
*/
function huberLoss_(labels, predictions, weights, delta = 1.0, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
const $labels = convertToTensor(labels, 'labels', 'huberLoss');
const $predictions = convertToTensor(predictions, 'predictions', 'huberLoss');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'huberLoss');
}
assertShapesMatch($labels.shape, $predictions.shape, 'Error in huberLoss: ');
const deltaScalar = scalar(delta);
const error = abs(sub($predictions, $labels));
const quadratic = minimum(error, deltaScalar);
const linear = sub(error, quadratic);
const losses = add$1(mul(scalar(0.5), square(quadratic)), mul(deltaScalar, linear));
return computeWeightedLoss(losses, $weights, reduction);
}
const huberLoss = op({ huberLoss_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the log loss between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param epsilon A small increment to avoid taking log of zero
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*
* @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}
*/
function logLoss_(labels, predictions, weights, epsilon = 1e-7, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
const $labels = convertToTensor(labels, 'labels', 'logLoss');
const $predictions = convertToTensor(predictions, 'predictions', 'logLoss');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'logLoss');
}
assertShapesMatch($labels.shape, $predictions.shape, 'Error in logLoss: ');
const one = scalar(1);
const epsilonScalar = scalar(epsilon);
const l1 = neg(mul($labels, log(add$1($predictions, epsilonScalar))));
const l2 = mul(sub(one, $labels), log(add$1(sub(one, $predictions), epsilonScalar)));
const losses = sub(l1, l2);
return computeWeightedLoss(losses, $weights, reduction);
}
const logLoss = op({ logLoss_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes the mean squared error between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*
* @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}
*/
function meanSquaredError_(labels, predictions, weights, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
const $labels = convertToTensor(labels, 'labels', 'meanSquaredError');
const $predictions = convertToTensor(predictions, 'predictions', 'meanSquaredError');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'meanSquaredError');
}
assertShapesMatch($labels.shape, $predictions.shape, 'Error in meanSquaredError: ');
const losses = squaredDifference($labels, $predictions);
return computeWeightedLoss(losses, $weights, reduction);
}
const meanSquaredError = op({ meanSquaredError_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
function sigmoidCrossEntropyWithLogits_(labels, logits) {
const $labels = convertToTensor(labels, 'labels', 'sigmoidCrossEntropyWithLogits');
const $logits = convertToTensor(logits, 'logits', 'sigmoidCrossEntropyWithLogits');
assertShapesMatch($labels.shape, $logits.shape, 'Error in sigmoidCrossEntropyWithLogits: ');
/**
* Implementation Details:
*
* For brevity, let `x = logits`, `z = labels`. The logistic loss is
* z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))
* = z * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x)))
* = z * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))
* = z * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x))
* = (1 - z) * x + log(1 + exp(-x))
* = x - x * z + log(1 + exp(-x))
*
* For x < 0, to avoid overflow in exp(-x), we reformulate the above
* x - x * z + log(1 + exp(-x))
* = log(exp(x)) - x * z + log(1 + exp(-x))
* = - x * z + log(1 + exp(x))
*
* Hence, to ensure stability and avoid overflow, the implementation uses
* this equivalent formulation:
* max(x, 0) - x * z + log(1 + exp(-abs(x)))
*/
const maxOutput = relu($logits);
const outputXTarget = mul($logits, $labels);
const sigmoidOutput = log1p(exp(neg(abs($logits))));
return add$1(sub(maxOutput, outputXTarget), sigmoidOutput);
}
/**
* Computes the sigmoid cross entropy loss between two tensors.
*
* If labelSmoothing is nonzero, smooth the labels towards 1/2:
*
* newMulticlassLabels = multiclassLabels * (1 - labelSmoothing)
* + 0.5 * labelSmoothing
*
* @param multiClassLabels The ground truth output tensor of shape
* [batch_size, num_classes], same dimensions as 'predictions'.
* @param logits The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param labelSmoothing If greater than 0, then smooth the labels.
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*
* @doc { heading: 'Training', subheading: 'Losses', namespace: 'losses' }
*/
function sigmoidCrossEntropy_(multiClassLabels, logits, weights, labelSmoothing = 0, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
let $multiClassLabels = convertToTensor(multiClassLabels, 'multiClassLabels', 'sigmoidCrossEntropy');
const $logits = convertToTensor(logits, 'logits', 'sigmoidCrossEntropy');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'sigmoidCrossEntropy');
}
assertShapesMatch($multiClassLabels.shape, $logits.shape, 'Error in sigmoidCrossEntropy: ');
if (labelSmoothing > 0) {
const labelSmoothingScalar = scalar(labelSmoothing);
const one = scalar(1);
const half = scalar(0.5);
$multiClassLabels =
add$1(mul($multiClassLabels, sub(one, labelSmoothingScalar)), mul(half, labelSmoothingScalar));
}
const losses = sigmoidCrossEntropyWithLogits_($multiClassLabels, $logits);
return computeWeightedLoss(losses, $weights, reduction);
}
const sigmoidCrossEntropy = op({ sigmoidCrossEntropy_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Computes softmax cross entropy between logits and labels.
*
* Measures the probability error in discrete classification tasks in which
* the classes are mutually exclusive (each entry is in exactly one class).
* For example, each CIFAR-10 image is labeled with one and only one label: an
* image can be a dog or a truck, but not both.
*
* `NOTE`: While the classes are mutually exclusive, their probabilities need
* not be. All that is required is that each row of labels is a valid
* probability distribution. If they are not, the computation of the gradient
* will be incorrect.
*
* `WARNING`: This op expects unscaled logits, since it performs a softmax on
* logits internally for efficiency. Do not call this op with the output of
* softmax, as it will produce incorrect results.
*
* logits and labels must have the same shape, e.g. [batch_size, num_classes]
* and the same dtype.
* @param labels The labels array.
* @param logits The logits array.
* @param dim The dimension softmax would be performed on. Defaults to `-1`
* which indicates the last dimension.
*/
function softmaxCrossEntropyWithLogits_(labels, logits, dim = -1) {
if (dim === -1) {
dim = logits.rank - 1;
}
if (dim !== logits.rank - 1) {
throw Error(`Softmax cross entropy along a non-last dimension is not yet ` +
`supported. Labels / logits was rank ${logits.rank} ` +
`and dim was ${dim}`);
}
// Use a custom gradient for numerical stability.
const customOp = customGrad((labels, logits, save) => {
// Reference:
// 1. http://cs231n.github.io/linear-classify/#softmax
// 2. https://blog.feedly.com/tricks-of-the-trade-logsumexp/
const keepDims = true;
const lse = logSumExp(logits, [dim], keepDims);
const logResult = sub(cast(logits, 'float32'), lse);
save([labels, logResult]);
const costVector = neg(mul(logResult, labels));
const value = sum$1(costVector, [dim]);
const gradFunc = (dy, saved) => {
const [labels, logResult] = saved;
const dyShape = expandShapeToKeepDim(dy.shape, [dim]);
return [
mul(reshape(dy, dyShape), sub(cast(labels, 'float32'), exp(logResult))),
mul(reshape(dy, dyShape), sub(exp(logResult), cast(labels, 'float32'))),
];
};
return { value, gradFunc };
});
return customOp(labels, logits);
}
/**
* Computes the softmax cross entropy loss between two tensors.
*
* If labelSmoothing is nonzero, smooth the labels towards 1/2:
*
* newOnehotLabels = onehotLabels * (1 - labelSmoothing)
* + labelSmoothing / numClasses
*
* @param onehotLabels One hot encoded labels
* [batch_size, num_classes], same dimensions as 'predictions'.
* @param logits The predicted outputs.
* @param weights Tensor whose rank is either 0, or 1, and must be
* broadcastable to `loss` of shape [batch_size]
* @param labelSmoothing If greater than 0, then smooth the labels.
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*
* @doc { heading: 'Training', subheading: 'Losses', namespace: 'losses' }
*/
function softmaxCrossEntropy_(onehotLabels, logits, weights, labelSmoothing = 0, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
let $onehotLabels = convertToTensor(onehotLabels, 'onehotLabels', 'softmaxCrossEntropy');
const $logits = convertToTensor(logits, 'logits', 'softmaxCrossEntropy');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'softmaxCrossEntropy');
}
assertShapesMatch($onehotLabels.shape, $logits.shape, 'Error in softmaxCrossEntropy: ');
if (labelSmoothing > 0) {
const labelSmoothingScalar = scalar(labelSmoothing);
const one = scalar(1);
const numClasses = scalar($onehotLabels.shape[1]);
$onehotLabels =
add$1(mul($onehotLabels, sub(one, labelSmoothingScalar)), div(labelSmoothingScalar, numClasses));
}
const losses = softmaxCrossEntropyWithLogits_($onehotLabels, $logits);
return computeWeightedLoss(losses, $weights, reduction);
}
const softmaxCrossEntropy = op({ softmaxCrossEntropy_ });
/**
* @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.
* =============================================================================
*/
/**
* This operation has the same semantics as reshape on the represented dense
* tensor. The `inputIndices` are recomputed based on the requested `newShape`.
* If one component of `newShape` is the special value -1, the size of that
* dimension is computed so that the total dense size remains constant. At most
* one component of `newShape` can be -1. The number of dense elements implied
* by `newShape` must be the same as the number of dense elements originally
* implied by `inputShape`. Reshaping does not affect the order of values in the
* SparseTensor. If the input tensor has rank R_in and N non-empty values, and
* `newShape` has length R_out, then `inputIndices` has shape [N, R_in],
* `inputShape` has length R_in, `outputIndices` has shape [N, R_out], and
* `outputShape` has length R_out.
*
* ```js
* const result = tf.sparse.sparseReshape(
* [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 2, 3]],
* [2, 3, 6], [9, -1]);
* console.log(result);
* result['outputIndices'].print(); //[[0, 0], [0, 1], [1, 2], [4, 2], [8, 1]]
* result['outputShape'].print(); // [9, 4]
* ```
* @param inputIndices: 2-D. N x R_in matrix with the indices of non-empty
* values in a SparseTensor.
* @param inputShape: 1-D. R_in Tensor1D with the input SparseTensor's dense
* shape.
* @param newShape: 1-D. R_out Tensor1D with the requested new dense shape.
* @return A map with the following properties:
* - outputIndices: 2-D. N x R_out matrix with the updated indices of
* non-empty values in the output SparseTensor.
* - outputShape: 1-D. R_out vector with the full dense shape of the output
* SparseTensor. This is the same as newShape but with any -1 dimensions
* filled in.
* @doc {heading: 'Operations', subheading: 'Sparse'}
*/
function sparseReshape_(inputIndices, inputShape, newShape) {
const $inputIndices = convertToTensor(inputIndices, 'inputIndices', 'sparseReshape');
const $inputShape = convertToTensor(inputShape, 'inputShape', 'sparseReshape');
const $newShape = convertToTensor(newShape, 'newShape', 'sparseReshape');
if ($inputIndices.rank !== 2) {
throw new Error(`Input indices should be Tensor2D but received shape
${$inputIndices.shape}`);
}
if ($inputShape.rank !== 1) {
throw new Error(`Input shape should be Tensor1D but received shape ${$inputShape.shape}`);
}
if ($newShape.rank !== 1) {
throw new Error(`New shape should be Tensor1D but received shape ${$newShape.shape}`);
}
const inputs = {
inputIndices: $inputIndices,
inputShape: $inputShape,
newShape: $newShape
};
const result = ENGINE.runKernel(SparseReshape, inputs);
return { outputIndices: result[0], outputShape: result[1] };
}
const sparseReshape = op({ sparseReshape_ });
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
const spectral = {
fft,
ifft,
rfft,
irfft
};
const signal = {
hammingWindow,
hannWindow,
frame,
stft,
};
const image = {
flipLeftRight,
resizeNearestNeighbor,
resizeBilinear,
rotateWithOffset,
cropAndResize,
nonMaxSuppression,
nonMaxSuppressionAsync,
nonMaxSuppressionWithScore,
nonMaxSuppressionWithScoreAsync,
nonMaxSuppressionPadded,
nonMaxSuppressionPaddedAsync,
transform
};
const linalg = {
bandPart,
gramSchmidt,
qr
};
const losses = {
absoluteDifference,
computeWeightedLoss,
cosineDistance,
hingeLoss,
huberLoss,
logLoss,
meanSquaredError,
sigmoidCrossEntropy,
softmaxCrossEntropy
};
const sparse = { sparseReshape };
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.abs = function () {
this.throwIfDisposed();
return abs(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.acos = function () {
this.throwIfDisposed();
return acos(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.acosh = function () {
this.throwIfDisposed();
return acosh(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.add = function (b) {
this.throwIfDisposed();
return add$1(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.all = function (axis, keepDims) {
this.throwIfDisposed();
return all(this, axis, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.any = function (axis, keepDims) {
this.throwIfDisposed();
return any(this, axis, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.argMax = function (axis) {
this.throwIfDisposed();
return argMax(this, axis);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.argMin = function (axis) {
this.throwIfDisposed();
return argMin(this, axis);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Converts a size-1 `tf.Tensor` to a `tf.Scalar`.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.asScalar = function () {
this.throwIfDisposed();
assert(this.size === 1, () => 'The array must have only 1 element.');
return reshape(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.
* =============================================================================
*/
/**
* Casts a `tf.Tensor` to a specified dtype.
*
* @param dtype Data-type to cast the tensor to.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.asType = function (dtype) {
this.throwIfDisposed();
return cast(this, 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.
* =============================================================================
*/
/**
* Converts a `tf.Tensor` to a `tf.Tensor1D`.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.as1D = function () {
this.throwIfDisposed();
return reshape(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.
* =============================================================================
*/
/**
* Converts a `tf.Tensor` to a `tf.Tensor2D`.
*
* @param rows Number of rows in `tf.Tensor2D`.
* @param columns Number of columns in `tf.Tensor2D`.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.as2D = function (rows, columns) {
this.throwIfDisposed();
return reshape(this, [rows, columns]);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Converts a `tf.Tensor` to a `tf.Tensor3D`.
*
* @param rows Number of rows in `tf.Tensor3D`.
* @param columns Number of columns in `tf.Tensor3D`.
* @param depth Depth of `tf.Tensor3D`.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.as3D = function (rows, columns, depth) {
this.throwIfDisposed();
return reshape(this, [rows, columns, depth]);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Converts a `tf.Tensor` to a `tf.Tensor4D`.
*
* @param rows Number of rows in `tf.Tensor4D`.
* @param columns Number of columns in `tf.Tensor4D`.
* @param depth Depth of `tf.Tensor4D`.
* @param depth2 4th dimension of `tf.Tensor4D`.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.as4D = function (rows, columns, depth, depth2) {
this.throwIfDisposed();
return reshape(this, [rows, columns, depth, depth2]);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Converts a `tf.Tensor` to a `tf.Tensor5D`.
*
* @param rows Number of rows in `tf.Tensor5D`.
* @param columns Number of columns in `tf.Tensor5D`.
* @param depth Depth of `tf.Tensor5D`.
* @param depth2 4th dimension of `tf.Tensor5D`.
* @param depth3 5th dimension of 'tf.Tensor5D'
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.as5D = function (rows, columns, depth, depth2, depth3) {
this.throwIfDisposed();
return reshape(this, [rows, columns, depth, depth2, depth3]);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.asin = function () {
this.throwIfDisposed();
return asin(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.asinh = function () {
this.throwIfDisposed();
return asinh(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.atan = function () {
this.throwIfDisposed();
return atan(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.atan2 = function (b) {
this.throwIfDisposed();
return atan2(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.atanh = function () {
this.throwIfDisposed();
return atanh(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.avgPool =
function (filterSize, strides, pad, dimRoundingMode) {
this.throwIfDisposed();
return avgPool(this, filterSize, strides, pad, dimRoundingMode);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.batchToSpaceND = function (blockShape, crops) {
this.throwIfDisposed();
return batchToSpaceND(this, blockShape, crops);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.batchNorm = function (mean, variance, offset, scale, varianceEpsilon) {
this.throwIfDisposed();
return batchNorm(this, mean, variance, offset, scale, varianceEpsilon);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.broadcastTo = function (shape) {
this.throwIfDisposed();
return broadcastTo(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.cast = function (dtype) {
this.throwIfDisposed();
return cast(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.ceil = function () {
this.throwIfDisposed();
return ceil(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.clipByValue = function (min, max) {
this.throwIfDisposed();
return clipByValue(this, min, max);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.concat = function (x, axis) {
this.throwIfDisposed();
if (x instanceof Tensor) {
x = [x];
}
return concat([this, ...x], axis);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.conv1d = function (filter, stride, pad, dataFormat, dilation, dimRoundingMode) {
this.throwIfDisposed();
return conv1d(this, filter, stride, pad, dataFormat, dilation, dimRoundingMode);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.conv2dTranspose =
function (filter, outputShape, strides, pad, dimRoundingMode) {
this.throwIfDisposed();
return conv2dTranspose(this, filter, outputShape, strides, pad, dimRoundingMode);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.conv2d = function (filter, strides, pad, dataFormat, dilations, dimRoundingMode) {
this.throwIfDisposed();
return conv2d(this, filter, strides, pad, dataFormat, dilations, dimRoundingMode);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.cos = function () {
this.throwIfDisposed();
return cos(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.cosh = function () {
this.throwIfDisposed();
return cosh(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.cumsum = function (axis, exclusive, reverse) {
this.throwIfDisposed();
return cumsum(this, axis, exclusive, reverse);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.depthToSpace = function (blockSize, dataFormat) {
this.throwIfDisposed();
return depthToSpace(this, blockSize, dataFormat);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.depthwiseConv2d =
function (filter, strides, pad, dataFormat, dilations, dimRoundingMode) {
this.throwIfDisposed();
return depthwiseConv2d(this, filter, strides, pad, dataFormat, dilations, dimRoundingMode);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.dilation2d =
function (filter, strides, pad, dilations, dataFormat) {
this.throwIfDisposed();
return dilation2d(this, filter, strides, pad, dilations, dataFormat);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.divNoNan = function (b) {
this.throwIfDisposed();
return divNoNan(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.div = function (b) {
this.throwIfDisposed();
return div(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.dot = function (b) {
this.throwIfDisposed();
return dot(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.elu = function () {
this.throwIfDisposed();
return elu(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.equal = function (b) {
this.throwIfDisposed();
return equal(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.erf = function () {
this.throwIfDisposed();
return erf(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.exp = function () {
this.throwIfDisposed();
return exp(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.expandDims = function (axis) {
this.throwIfDisposed();
return expandDims(this, axis);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.expm1 = function () {
this.throwIfDisposed();
return expm1(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.fft = function () {
this.throwIfDisposed();
return fft(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.
* =============================================================================
*/
/**
* Flatten a Tensor to a 1D array.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.flatten = function () {
this.throwIfDisposed();
return reshape(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.floor = function () {
this.throwIfDisposed();
return floor(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.floorDiv = function (b) {
this.throwIfDisposed();
return floorDiv(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.gather = function (indices, axis) {
this.throwIfDisposed();
return gather(this, indices, axis);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.greaterEqual = function (b) {
this.throwIfDisposed();
return greaterEqual(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.greater = function (b) {
this.throwIfDisposed();
return greater(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.ifft = function () {
this.throwIfDisposed();
return ifft(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.irfft = function () {
this.throwIfDisposed();
return irfft(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.isFinite = function () {
this.throwIfDisposed();
return isFinite$1(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.isInf = function () {
this.throwIfDisposed();
return isInf(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.isNaN = function () {
this.throwIfDisposed();
return isNaN$1(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.leakyRelu = function (alpha) {
this.throwIfDisposed();
return leakyRelu(this, alpha);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.lessEqual = function (b) {
this.throwIfDisposed();
return lessEqual(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.less = function (b) {
this.throwIfDisposed();
return less(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.localResponseNormalization =
function (depthRadius, bias, alpha, beta) {
this.throwIfDisposed();
return localResponseNormalization(this, depthRadius, bias, alpha, beta);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.logSigmoid = function () {
this.throwIfDisposed();
return logSigmoid(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.logSoftmax = function (axis) {
this.throwIfDisposed();
return logSoftmax(this, axis);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.logSumExp = function (axis, keepDims) {
this.throwIfDisposed();
return logSumExp(this, axis, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.log = function () {
this.throwIfDisposed();
return log(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.log1p = function () {
this.throwIfDisposed();
return log1p(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.logicalAnd = function (b) {
this.throwIfDisposed();
return logicalAnd(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.logicalNot = function () {
this.throwIfDisposed();
return logicalNot(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.logicalOr = function (b) {
this.throwIfDisposed();
return logicalOr(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.logicalXor = function (b) {
this.throwIfDisposed();
return logicalXor(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.matMul = function (b, transposeA, transposeB) {
this.throwIfDisposed();
return matMul(this, b, transposeA, transposeB);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.maxPool =
function (filterSize, strides, pad, dimRoundingMode) {
this.throwIfDisposed();
return maxPool(this, filterSize, strides, pad, dimRoundingMode);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.max = function (axis, keepDims) {
this.throwIfDisposed();
return max(this, axis, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.maximum = function (b) {
this.throwIfDisposed();
return maximum(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.mean = function (axis, keepDims) {
this.throwIfDisposed();
return mean(this, axis, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.min = function (axis, keepDims) {
this.throwIfDisposed();
return min(this, axis, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.minimum = function (b) {
this.throwIfDisposed();
return minimum(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.mirrorPad = function (paddings, mode) {
this.throwIfDisposed();
return mirrorPad(this, paddings, mode);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.mod = function (b) {
this.throwIfDisposed();
return mod(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.mul = function (b) {
this.throwIfDisposed();
return mul(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.neg = function () {
this.throwIfDisposed();
return neg(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.norm = function (ord, axis, keepDims) {
this.throwIfDisposed();
return norm(this, ord, axis, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.notEqual = function (b) {
this.throwIfDisposed();
return notEqual(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.oneHot = function (depth, onValue = 1, offValue = 0) {
this.throwIfDisposed();
return oneHot(this, depth, onValue, offValue);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.onesLike = function () {
this.throwIfDisposed();
return onesLike(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.pad = function (paddings, constantValue) {
this.throwIfDisposed();
return pad(this, paddings, constantValue);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.pool = function (windowShape, poolingType, padding, dilationRate, strides) {
this.throwIfDisposed();
return pool(this, windowShape, poolingType, padding, dilationRate, strides);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.pow = function (exp) {
this.throwIfDisposed();
return pow(this, exp);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.prelu = function (alpha) {
this.throwIfDisposed();
return prelu(this, alpha);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.prod = function (axis, keepDims) {
this.throwIfDisposed();
return prod(this, axis, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.reciprocal = function () {
this.throwIfDisposed();
return reciprocal(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.relu = function () {
this.throwIfDisposed();
return relu(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.relu6 = function () {
this.throwIfDisposed();
return relu6(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.
* =============================================================================
*/
/**
* Reshapes the tensor into the shape of the provided tensor.
*
* @param x The tensor of required shape.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.reshapeAs = function (x) {
this.throwIfDisposed();
return reshape(this, x.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.
* =============================================================================
*/
getGlobalTensorClass().prototype.reshape = function (shape) {
this.throwIfDisposed();
return reshape(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.resizeBilinear =
function (newShape2D, alignCorners, halfPixelCenters) {
this.throwIfDisposed();
return resizeBilinear(this, newShape2D, alignCorners, halfPixelCenters);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.resizeNearestNeighbor =
function (newShape2D, alignCorners, halfFloatCenters) {
this.throwIfDisposed();
return resizeNearestNeighbor(this, newShape2D, alignCorners, halfFloatCenters);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.reverse = function (axis) {
this.throwIfDisposed();
return reverse(this, axis);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.rfft = function () {
this.throwIfDisposed();
return rfft(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.round = function () {
this.throwIfDisposed();
return round$1(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.rsqrt = function () {
this.throwIfDisposed();
return rsqrt(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.selu = function () {
this.throwIfDisposed();
return selu(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.separableConv2d =
function (depthwiseFilter, pointwiseFilter, strides, pad, dilation, dataFormat) {
this.throwIfDisposed();
return separableConv2d(this, depthwiseFilter, pointwiseFilter, strides, pad, dilation, dataFormat);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.sigmoid = function () {
this.throwIfDisposed();
return sigmoid(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.sign = function () {
this.throwIfDisposed();
return sign(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.sin = function () {
this.throwIfDisposed();
return sin(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.sinh = function () {
this.throwIfDisposed();
return sinh(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.slice = function (begin, size) {
this.throwIfDisposed();
return slice(this, begin, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.softmax = function (dim) {
this.throwIfDisposed();
return softmax(this, dim);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.softplus = function () {
this.throwIfDisposed();
return softplus(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.spaceToBatchND = function (blockShape, paddings) {
this.throwIfDisposed();
return spaceToBatchND(this, blockShape, paddings);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.split = function (numOrSizeSplits, axis) {
this.throwIfDisposed();
return split(this, numOrSizeSplits, axis);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.sqrt = function () {
this.throwIfDisposed();
return sqrt(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.square = function () {
this.throwIfDisposed();
return square(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.squaredDifference = function (b) {
this.throwIfDisposed();
return squaredDifference(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.squeeze = function (axis) {
this.throwIfDisposed();
return squeeze(this, axis);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.stack = function (x, axis) {
this.throwIfDisposed();
const tensorsToBeStacked = x instanceof Tensor ? [this, x] : [this, ...x];
return stack(tensorsToBeStacked, axis);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.step = function (alpha) {
this.throwIfDisposed();
return step(this, alpha);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.stridedSlice = function (begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask) {
this.throwIfDisposed();
return stridedSlice(this, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.sub = function (b) {
this.throwIfDisposed();
return sub(this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.sum = function (axis, keepDims) {
this.throwIfDisposed();
return sum$1(this, axis, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.tan = function () {
this.throwIfDisposed();
return tan(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.tanh = function () {
this.throwIfDisposed();
return tanh$1(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.tile = function (reps) {
this.throwIfDisposed();
return tile(this, reps);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Casts the array to type `bool`
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.toBool = function () {
this.throwIfDisposed();
return cast(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.
* =============================================================================
*/
/**
* Casts the array to type `float32`
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.toFloat = function () {
this.throwIfDisposed();
return cast(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.
* =============================================================================
*/
/**
* Casts the array to type `int32`
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.toInt = function () {
this.throwIfDisposed();
return cast(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.
* =============================================================================
*/
getGlobalTensorClass().prototype.topk = function (k, sorted) {
this.throwIfDisposed();
return topk(this, k, sorted);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.transpose = function (perm) {
this.throwIfDisposed();
return transpose(this, perm);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.unique = function (axis) {
this.throwIfDisposed();
return unique(this, axis);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.unsortedSegmentSum =
function (segmentIds, numSegments) {
this.throwIfDisposed();
return unsortedSegmentSum(this, segmentIds, numSegments);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.unstack = function (axis) {
this.throwIfDisposed();
return unstack(this, axis);
};
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
getGlobalTensorClass().prototype.where = function (condition, x) {
this.throwIfDisposed();
return where(condition, this, 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.zerosLike = function () {
this.throwIfDisposed();
return zerosLike(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.
* =============================================================================
*/
/** @license See the LICENSE file. */
// This code is auto-generated, do not modify this file!
var version = '3.5.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.
* =============================================================================
*/
var version$1 = {
'tfjs-core': tfjsCore.version_core,
'tfjs-backend-cpu': tfjsBackendCpu.version_cpu,
'tfjs-backend-webgl': tfjsBackendWebgl.version_webgl,
'tfjs-data': tfjsData.version_data,
'tfjs-layers': tfjsLayers.version_layers,
'tfjs-converter': tfjsConverter.version_converter,
'tfjs': version
};
Object.keys(tfjsCore).forEach(function (k) {
if (k !== 'default') Object.defineProperty(exports, k, {
enumerable: true,
get: function () {
return tfjsCore[k];
}
});
});
Object.keys(tfjsLayers).forEach(function (k) {
if (k !== 'default') Object.defineProperty(exports, k, {
enumerable: true,
get: function () {
return tfjsLayers[k];
}
});
});
Object.keys(tfjsConverter).forEach(function (k) {
if (k !== 'default') Object.defineProperty(exports, k, {
enumerable: true,
get: function () {
return tfjsConverter[k];
}
});
});
exports.data = tfjsData;
exports.version = version$1;
//# sourceMappingURL=tf.node.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(103), __webpack_require__(142)))
/***/ }),
/* 275 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
var i
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)]
arr[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(
uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}
/***/ }),
/* 276 */
/***/ (function(module, exports) {
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = ((value * c) - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
/***/ }),
/* 277 */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
/***/ }),
/* 278 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {/* unused harmony export getNodeFetch */
/* unused harmony export resetSystemFetch */
/* unused harmony export setSystemFetch */
/* unused harmony export getSystemFetch */
/* unused harmony export PlatformNode */
/* harmony import */ var _environment__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(22);
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// We are wrapping this within an object so it can be stubbed by Jasmine.
const getNodeFetch = {
// tslint:disable-next-line:no-require-imports
importFetch: () => __webpack_require__(279)
};
let systemFetch;
// These getters and setters are for testing so we don't export a mutable
// variable.
function resetSystemFetch() {
systemFetch = null;
}
function setSystemFetch(fetchFn) {
systemFetch = fetchFn;
}
function getSystemFetch() {
return systemFetch;
}
class PlatformNode {
constructor() {
// tslint:disable-next-line:no-require-imports
this.util = __webpack_require__(280);
// According to the spec, the built-in encoder can do only UTF-8 encoding.
// https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder
this.textEncoder = new this.util.TextEncoder();
}
fetch(path, requestInits) {
if (Object(_environment__WEBPACK_IMPORTED_MODULE_0__[/* env */ "c"])().global.fetch != null) {
return Object(_environment__WEBPACK_IMPORTED_MODULE_0__[/* env */ "c"])().global.fetch(path, requestInits);
}
if (systemFetch == null) {
systemFetch = getNodeFetch.importFetch();
}
return systemFetch(path, requestInits);
}
now() {
const time = process.hrtime();
return time[0] * 1000 + time[1] / 1000000;
}
encode(text, encoding) {
if (encoding !== 'utf-8' && encoding !== 'utf8') {
throw new Error(`Node built-in encoder only supports utf-8, but got ${encoding}`);
}
return this.textEncoder.encode(text);
}
decode(bytes, encoding) {
if (bytes.length === 0) {
return '';
}
return new this.util.TextDecoder(encoding).decode(bytes);
}
}
if (Object(_environment__WEBPACK_IMPORTED_MODULE_0__[/* env */ "c"])().get('IS_NODE')) {
Object(_environment__WEBPACK_IMPORTED_MODULE_0__[/* env */ "c"])().setPlatform('node', new PlatformNode());
}
//# sourceMappingURL=platform_node.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(142)))
/***/ }),
/* 279 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 280 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 281 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;// A port of an algorithm by Johannes Baagøe , 2010
// http://baagoe.com/en/RandomMusings/javascript/
// https://github.com/nquinlan/better-random-numbers-for-javascript-mirror
// Original work is under MIT license -
// Copyright (C) 2010 by Johannes Baagøe
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
(function(global, module, define) {
function Alea(seed) {
var me = this, mash = Mash();
me.next = function() {
var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32
me.s0 = me.s1;
me.s1 = me.s2;
return me.s2 = t - (me.c = t | 0);
};
// Apply the seeding algorithm from Baagoe.
me.c = 1;
me.s0 = mash(' ');
me.s1 = mash(' ');
me.s2 = mash(' ');
me.s0 -= mash(seed);
if (me.s0 < 0) { me.s0 += 1; }
me.s1 -= mash(seed);
if (me.s1 < 0) { me.s1 += 1; }
me.s2 -= mash(seed);
if (me.s2 < 0) { me.s2 += 1; }
mash = null;
}
function copy(f, t) {
t.c = f.c;
t.s0 = f.s0;
t.s1 = f.s1;
t.s2 = f.s2;
return t;
}
function impl(seed, opts) {
var xg = new Alea(seed),
state = opts && opts.state,
prng = xg.next;
prng.int32 = function() { return (xg.next() * 0x100000000) | 0; }
prng.double = function() {
return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
};
prng.quick = prng;
if (state) {
if (typeof(state) == 'object') copy(state, xg);
prng.state = function() { return copy(xg, {}); }
}
return prng;
}
function Mash() {
var n = 0xefc8249d;
var mash = function(data) {
data = data.toString();
for (var i = 0; i < data.length; i++) {
n += data.charCodeAt(i);
var h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000; // 2^32
}
return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
};
return mash;
}
if (module && module.exports) {
module.exports = impl;
} else if (__webpack_require__(64) && __webpack_require__(111)) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return impl; }).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
this.alea = impl;
}
})(
this,
true && module, // present in node.js
__webpack_require__(64) // present with an AMD loader
);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(110)(module)))
/***/ }),
/* 282 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;// A Javascript implementaion of the "xor128" prng algorithm by
// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper
(function(global, module, define) {
function XorGen(seed) {
var me = this, strseed = '';
me.x = 0;
me.y = 0;
me.z = 0;
me.w = 0;
// Set up generator function.
me.next = function() {
var t = me.x ^ (me.x << 11);
me.x = me.y;
me.y = me.z;
me.z = me.w;
return me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8);
};
if (seed === (seed | 0)) {
// Integer seed.
me.x = seed;
} else {
// String seed.
strseed += seed;
}
// Mix in string seed, then discard an initial batch of 64 values.
for (var k = 0; k < strseed.length + 64; k++) {
me.x ^= strseed.charCodeAt(k) | 0;
me.next();
}
}
function copy(f, t) {
t.x = f.x;
t.y = f.y;
t.z = f.z;
t.w = f.w;
return t;
}
function impl(seed, opts) {
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function() { return (xg.next() >>> 0) / 0x100000000; };
prng.double = function() {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (typeof(state) == 'object') copy(state, xg);
prng.state = function() { return copy(xg, {}); }
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (__webpack_require__(64) && __webpack_require__(111)) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return impl; }).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
this.xor128 = impl;
}
})(
this,
true && module, // present in node.js
__webpack_require__(64) // present with an AMD loader
);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(110)(module)))
/***/ }),
/* 283 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;// A Javascript implementaion of the "xorwow" prng algorithm by
// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper
(function(global, module, define) {
function XorGen(seed) {
var me = this, strseed = '';
// Set up generator function.
me.next = function() {
var t = (me.x ^ (me.x >>> 2));
me.x = me.y; me.y = me.z; me.z = me.w; me.w = me.v;
return (me.d = (me.d + 362437 | 0)) +
(me.v = (me.v ^ (me.v << 4)) ^ (t ^ (t << 1))) | 0;
};
me.x = 0;
me.y = 0;
me.z = 0;
me.w = 0;
me.v = 0;
if (seed === (seed | 0)) {
// Integer seed.
me.x = seed;
} else {
// String seed.
strseed += seed;
}
// Mix in string seed, then discard an initial batch of 64 values.
for (var k = 0; k < strseed.length + 64; k++) {
me.x ^= strseed.charCodeAt(k) | 0;
if (k == strseed.length) {
me.d = me.x << 10 ^ me.x >>> 4;
}
me.next();
}
}
function copy(f, t) {
t.x = f.x;
t.y = f.y;
t.z = f.z;
t.w = f.w;
t.v = f.v;
t.d = f.d;
return t;
}
function impl(seed, opts) {
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function() { return (xg.next() >>> 0) / 0x100000000; };
prng.double = function() {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (typeof(state) == 'object') copy(state, xg);
prng.state = function() { return copy(xg, {}); }
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (__webpack_require__(64) && __webpack_require__(111)) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return impl; }).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
this.xorwow = impl;
}
})(
this,
true && module, // present in node.js
__webpack_require__(64) // present with an AMD loader
);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(110)(module)))
/***/ }),
/* 284 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;// A Javascript implementaion of the "xorshift7" algorithm by
// François Panneton and Pierre L'ecuyer:
// "On the Xorgshift Random Number Generators"
// http://saluc.engr.uconn.edu/refs/crypto/rng/panneton05onthexorshift.pdf
(function(global, module, define) {
function XorGen(seed) {
var me = this;
// Set up generator function.
me.next = function() {
// Update xor generator.
var X = me.x, i = me.i, t, v, w;
t = X[i]; t ^= (t >>> 7); v = t ^ (t << 24);
t = X[(i + 1) & 7]; v ^= t ^ (t >>> 10);
t = X[(i + 3) & 7]; v ^= t ^ (t >>> 3);
t = X[(i + 4) & 7]; v ^= t ^ (t << 7);
t = X[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);
X[i] = v;
me.i = (i + 1) & 7;
return v;
};
function init(me, seed) {
var j, w, X = [];
if (seed === (seed | 0)) {
// Seed state array using a 32-bit integer.
w = X[0] = seed;
} else {
// Seed state using a string.
seed = '' + seed;
for (j = 0; j < seed.length; ++j) {
X[j & 7] = (X[j & 7] << 15) ^
(seed.charCodeAt(j) + X[(j + 1) & 7] << 13);
}
}
// Enforce an array length of 8, not all zeroes.
while (X.length < 8) X.push(0);
for (j = 0; j < 8 && X[j] === 0; ++j);
if (j == 8) w = X[7] = -1; else w = X[j];
me.x = X;
me.i = 0;
// Discard an initial 256 values.
for (j = 256; j > 0; --j) {
me.next();
}
}
init(me, seed);
}
function copy(f, t) {
t.x = f.x.slice();
t.i = f.i;
return t;
}
function impl(seed, opts) {
if (seed == null) seed = +(new Date);
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function() { return (xg.next() >>> 0) / 0x100000000; };
prng.double = function() {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (state.x) copy(state, xg);
prng.state = function() { return copy(xg, {}); }
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (__webpack_require__(64) && __webpack_require__(111)) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return impl; }).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
this.xorshift7 = impl;
}
})(
this,
true && module, // present in node.js
__webpack_require__(64) // present with an AMD loader
);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(110)(module)))
/***/ }),
/* 285 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.
//
// This fast non-cryptographic random number generator is designed for
// use in Monte-Carlo algorithms. It combines a long-period xorshift
// generator with a Weyl generator, and it passes all common batteries
// of stasticial tests for randomness while consuming only a few nanoseconds
// for each prng generated. For background on the generator, see Brent's
// paper: "Some long-period random number generators using shifts and xors."
// http://arxiv.org/pdf/1004.3115v1.pdf
//
// Usage:
//
// var xor4096 = require('xor4096');
// random = xor4096(1); // Seed with int32 or string.
// assert.equal(random(), 0.1520436450538547); // (0, 1) range, 53 bits.
// assert.equal(random.int32(), 1806534897); // signed int32, 32 bits.
//
// For nonzero numeric keys, this impelementation provides a sequence
// identical to that by Brent's xorgens 3 implementaion in C. This
// implementation also provides for initalizing the generator with
// string seeds, or for saving and restoring the state of the generator.
//
// On Chrome, this prng benchmarks about 2.1 times slower than
// Javascript's built-in Math.random().
(function(global, module, define) {
function XorGen(seed) {
var me = this;
// Set up generator function.
me.next = function() {
var w = me.w,
X = me.X, i = me.i, t, v;
// Update Weyl generator.
me.w = w = (w + 0x61c88647) | 0;
// Update xor generator.
v = X[(i + 34) & 127];
t = X[i = ((i + 1) & 127)];
v ^= v << 13;
t ^= t << 17;
v ^= v >>> 15;
t ^= t >>> 12;
// Update Xor generator array state.
v = X[i] = v ^ t;
me.i = i;
// Result is the combination.
return (v + (w ^ (w >>> 16))) | 0;
};
function init(me, seed) {
var t, v, i, j, w, X = [], limit = 128;
if (seed === (seed | 0)) {
// Numeric seeds initialize v, which is used to generates X.
v = seed;
seed = null;
} else {
// String seeds are mixed into v and X one character at a time.
seed = seed + '\0';
v = 0;
limit = Math.max(limit, seed.length);
}
// Initialize circular array and weyl value.
for (i = 0, j = -32; j < limit; ++j) {
// Put the unicode characters into the array, and shuffle them.
if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);
// After 32 shuffles, take v as the starting w value.
if (j === 0) w = v;
v ^= v << 10;
v ^= v >>> 15;
v ^= v << 4;
v ^= v >>> 13;
if (j >= 0) {
w = (w + 0x61c88647) | 0; // Weyl.
t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.
i = (0 == t) ? i + 1 : 0; // Count zeroes.
}
}
// We have detected all zeroes; make the key nonzero.
if (i >= 128) {
X[(seed && seed.length || 0) & 127] = -1;
}
// Run the generator 512 times to further mix the state before using it.
// Factoring this as a function slows the main generator, so it is just
// unrolled here. The weyl generator is not advanced while warming up.
i = 127;
for (j = 4 * 128; j > 0; --j) {
v = X[(i + 34) & 127];
t = X[i = ((i + 1) & 127)];
v ^= v << 13;
t ^= t << 17;
v ^= v >>> 15;
t ^= t >>> 12;
X[i] = v ^ t;
}
// Storing state as object members is faster than using closure variables.
me.w = w;
me.X = X;
me.i = i;
}
init(me, seed);
}
function copy(f, t) {
t.i = f.i;
t.w = f.w;
t.X = f.X.slice();
return t;
};
function impl(seed, opts) {
if (seed == null) seed = +(new Date);
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function() { return (xg.next() >>> 0) / 0x100000000; };
prng.double = function() {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (state.X) copy(state, xg);
prng.state = function() { return copy(xg, {}); }
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (__webpack_require__(64) && __webpack_require__(111)) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return impl; }).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
this.xor4096 = impl;
}
})(
this, // window object or global
true && module, // present in node.js
__webpack_require__(64) // present with an AMD loader
);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(110)(module)))
/***/ }),
/* 286 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;// A Javascript implementaion of the "Tyche-i" prng algorithm by
// Samuel Neves and Filipe Araujo.
// See https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf
(function(global, module, define) {
function XorGen(seed) {
var me = this, strseed = '';
// Set up generator function.
me.next = function() {
var b = me.b, c = me.c, d = me.d, a = me.a;
b = (b << 25) ^ (b >>> 7) ^ c;
c = (c - d) | 0;
d = (d << 24) ^ (d >>> 8) ^ a;
a = (a - b) | 0;
me.b = b = (b << 20) ^ (b >>> 12) ^ c;
me.c = c = (c - d) | 0;
me.d = (d << 16) ^ (c >>> 16) ^ a;
return me.a = (a - b) | 0;
};
/* The following is non-inverted tyche, which has better internal
* bit diffusion, but which is about 25% slower than tyche-i in JS.
me.next = function() {
var a = me.a, b = me.b, c = me.c, d = me.d;
a = (me.a + me.b | 0) >>> 0;
d = me.d ^ a; d = d << 16 ^ d >>> 16;
c = me.c + d | 0;
b = me.b ^ c; b = b << 12 ^ d >>> 20;
me.a = a = a + b | 0;
d = d ^ a; me.d = d = d << 8 ^ d >>> 24;
me.c = c = c + d | 0;
b = b ^ c;
return me.b = (b << 7 ^ b >>> 25);
}
*/
me.a = 0;
me.b = 0;
me.c = 2654435769 | 0;
me.d = 1367130551;
if (seed === Math.floor(seed)) {
// Integer seed.
me.a = (seed / 0x100000000) | 0;
me.b = seed | 0;
} else {
// String seed.
strseed += seed;
}
// Mix in string seed, then discard an initial batch of 64 values.
for (var k = 0; k < strseed.length + 20; k++) {
me.b ^= strseed.charCodeAt(k) | 0;
me.next();
}
}
function copy(f, t) {
t.a = f.a;
t.b = f.b;
t.c = f.c;
t.d = f.d;
return t;
};
function impl(seed, opts) {
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function() { return (xg.next() >>> 0) / 0x100000000; };
prng.double = function() {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (typeof(state) == 'object') copy(state, xg);
prng.state = function() { return copy(xg, {}); }
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (__webpack_require__(64) && __webpack_require__(111)) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return impl; }).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
this.tychei = impl;
}
})(
this,
true && module, // present in node.js
__webpack_require__(64) // present with an AMD loader
);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(110)(module)))
/***/ }),
/* 287 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/*
Copyright 2014 David Bau.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function (pool, math) {
//
// The following constants are related to IEEE 754 limits.
//
var global = this,
width = 256, // each RC4 output is 0 <= x < 256
chunks = 6, // at least six RC4 outputs for each double
digits = 52, // there are 52 significant digits in a double
rngname = 'random', // rngname: name for Math.random and Math.seedrandom
startdenom = math.pow(width, chunks),
significance = math.pow(2, digits),
overflow = significance * 2,
mask = width - 1,
nodecrypto; // node.js crypto module, initialized at the bottom.
//
// seedrandom()
// This is the seedrandom function described above.
//
function seedrandom(seed, options, callback) {
var key = [];
options = (options == true) ? { entropy: true } : (options || {});
// Flatten the seed string or build one from local entropy if needed.
var shortseed = mixkey(flatten(
options.entropy ? [seed, tostring(pool)] :
(seed == null) ? autoseed() : seed, 3), key);
// Use the seed to initialize an ARC4 generator.
var arc4 = new ARC4(key);
// This function returns a random double in [0, 1) that contains
// randomness in every bit of the mantissa of the IEEE 754 value.
var prng = function() {
var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
d = startdenom, // and denominator d = 2 ^ 48.
x = 0; // and no 'extra last byte'.
while (n < significance) { // Fill up all significant digits by
n = (n + x) * width; // shifting numerator and
d *= width; // denominator and generating a
x = arc4.g(1); // new least-significant-byte.
}
while (n >= overflow) { // To avoid rounding up, before adding
n /= 2; // last byte, shift everything
d /= 2; // right using integer math until
x >>>= 1; // we have exactly the desired bits.
}
return (n + x) / d; // Form the number within [0, 1).
};
prng.int32 = function() { return arc4.g(4) | 0; }
prng.quick = function() { return arc4.g(4) / 0x100000000; }
prng.double = prng;
// Mix the randomness into accumulated entropy.
mixkey(tostring(arc4.S), pool);
// Calling convention: what to return as a function of prng, seed, is_math.
return (options.pass || callback ||
function(prng, seed, is_math_call, state) {
if (state) {
// Load the arc4 state from the given state if it has an S array.
if (state.S) { copy(state, arc4); }
// Only provide the .state method if requested via options.state.
prng.state = function() { return copy(arc4, {}); }
}
// If called as a method of Math (Math.seedrandom()), mutate
// Math.random because that is how seedrandom.js has worked since v1.0.
if (is_math_call) { math[rngname] = prng; return seed; }
// Otherwise, it is a newer calling convention, so return the
// prng directly.
else return prng;
})(
prng,
shortseed,
'global' in options ? options.global : (this == math),
options.state);
}
math['seed' + rngname] = seedrandom;
//
// ARC4
//
// An ARC4 implementation. The constructor takes a key in the form of
// an array of at most (width) integers that should be 0 <= x < (width).
//
// The g(count) method returns a pseudorandom integer that concatenates
// the next (count) outputs from ARC4. Its return value is a number x
// that is in the range 0 <= x < (width ^ count).
//
function ARC4(key) {
var t, keylen = key.length,
me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
// The empty key [] is treated as [0].
if (!keylen) { key = [keylen++]; }
// Set up S using the standard key scheduling algorithm.
while (i < width) {
s[i] = i++;
}
for (i = 0; i < width; i++) {
s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
s[j] = t;
}
// The "g" method returns the next (count) outputs as one number.
(me.g = function(count) {
// Using instance members instead of closure state nearly doubles speed.
var t, r = 0,
i = me.i, j = me.j, s = me.S;
while (count--) {
t = s[i = mask & (i + 1)];
r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
}
me.i = i; me.j = j;
return r;
// For robust unpredictability, the function call below automatically
// discards an initial batch of values. This is called RC4-drop[256].
// See http://google.com/search?q=rsa+fluhrer+response&btnI
})(width);
}
//
// copy()
// Copies internal state of ARC4 to or from a plain object.
//
function copy(f, t) {
t.i = f.i;
t.j = f.j;
t.S = f.S.slice();
return t;
};
//
// flatten()
// Converts an object tree to nested arrays of strings.
//
function flatten(obj, depth) {
var result = [], typ = (typeof obj), prop;
if (depth && typ == 'object') {
for (prop in obj) {
try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
}
}
return (result.length ? result : typ == 'string' ? obj : obj + '\0');
}
//
// mixkey()
// Mixes a string seed into a key that is an array of integers, and
// returns a shortened string seed that is equivalent to the result key.
//
function mixkey(seed, key) {
var stringseed = seed + '', smear, j = 0;
while (j < stringseed.length) {
key[mask & j] =
mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
}
return tostring(key);
}
//
// autoseed()
// Returns an object for autoseeding, using window.crypto and Node crypto
// module if available.
//
function autoseed() {
try {
var out;
if (nodecrypto && (out = nodecrypto.randomBytes)) {
// The use of 'out' to remember randomBytes makes tight minified code.
out = out(width);
} else {
out = new Uint8Array(width);
(global.crypto || global.msCrypto).getRandomValues(out);
}
return tostring(out);
} catch (e) {
var browser = global.navigator,
plugins = browser && browser.plugins;
return [+new Date, global, plugins, global.screen, tostring(pool)];
}
}
//
// tostring()
// Converts an array of charcodes to a string
//
function tostring(a) {
return String.fromCharCode.apply(0, a);
}
//
// When seedrandom.js is loaded, we immediately mix a few bits
// from the built-in RNG into the entropy pool. Because we do
// not want to interfere with deterministic PRNG state later,
// seedrandom will not call math.random on its own again after
// initialization.
//
mixkey(math.random(), pool);
//
// Nodejs and AMD support: export the implementation as a module using
// either convention.
//
if ( true && module.exports) {
module.exports = seedrandom;
// When in node.js, try using crypto package for autoseeding.
try {
nodecrypto = __webpack_require__(288);
} catch (ex) {}
} else if (true) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return seedrandom; }).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
// End anonymous scope, and pass initial values.
})(
[], // pool: entropy pool starts empty
Math // math: package containing random, pow, and seedrandom
);
/***/ }),
/* 288 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 289 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
(typeof self !== "undefined" && self) ||
window;
var apply = Function.prototype.apply;
// DOM APIs, for completeness
exports.setTimeout = function() {
return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
};
exports.setInterval = function() {
return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) {
if (timeout) {
timeout.close();
}
};
function Timeout(id, clearFn) {
this._id = id;
this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
this._clearFn.call(scope, this._id);
};
// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = msecs;
};
exports.unenroll = function(item) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = -1;
};
exports._unrefActive = exports.active = function(item) {
clearTimeout(item._idleTimeoutId);
var msecs = item._idleTimeout;
if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout)
item._onTimeout();
}, msecs);
}
};
// setimmediate attaches itself to the global object
__webpack_require__(290);
// On some exotic environments, it's not clear which object `setimmediate` was
// able to install onto. Search each possibility in the same order as the
// `setimmediate` library.
exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
(typeof global !== "undefined" && global.setImmediate) ||
(this && this.setImmediate);
exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
(typeof global !== "undefined" && global.clearImmediate) ||
(this && this.clearImmediate);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(103)))
/***/ }),
/* 290 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
"use strict";
if (global.setImmediate) {
return;
}
var nextHandle = 1; // Spec says greater than zero
var tasksByHandle = {};
var currentlyRunningATask = false;
var doc = global.document;
var registerImmediate;
function setImmediate(callback) {
// Callback can either be a function or a string
if (typeof callback !== "function") {
callback = new Function("" + callback);
}
// Copy function arguments
var args = new Array(arguments.length - 1);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i + 1];
}
// Store and register the task
var task = { callback: callback, args: args };
tasksByHandle[nextHandle] = task;
registerImmediate(nextHandle);
return nextHandle++;
}
function clearImmediate(handle) {
delete tasksByHandle[handle];
}
function run(task) {
var callback = task.callback;
var args = task.args;
switch (args.length) {
case 0:
callback();
break;
case 1:
callback(args[0]);
break;
case 2:
callback(args[0], args[1]);
break;
case 3:
callback(args[0], args[1], args[2]);
break;
default:
callback.apply(undefined, args);
break;
}
}
function runIfPresent(handle) {
// From the spec: "Wait until any invocations of this algorithm started before this one have completed."
// So if we're currently running a task, we'll need to delay this invocation.
if (currentlyRunningATask) {
// Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
// "too much recursion" error.
setTimeout(runIfPresent, 0, handle);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunningATask = true;
try {
run(task);
} finally {
clearImmediate(handle);
currentlyRunningATask = false;
}
}
}
}
function installNextTickImplementation() {
registerImmediate = function(handle) {
process.nextTick(function () { runIfPresent(handle); });
};
}
function canUsePostMessage() {
// The test against `importScripts` prevents this implementation from being installed inside a web worker,
// where `global.postMessage` means something completely different and can't be used for this purpose.
if (global.postMessage && !global.importScripts) {
var postMessageIsAsynchronous = true;
var oldOnMessage = global.onmessage;
global.onmessage = function() {
postMessageIsAsynchronous = false;
};
global.postMessage("", "*");
global.onmessage = oldOnMessage;
return postMessageIsAsynchronous;
}
}
function installPostMessageImplementation() {
// Installs an event handler on `global` for the `message` event: see
// * https://developer.mozilla.org/en/DOM/window.postMessage
// * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
var messagePrefix = "setImmediate$" + Math.random() + "$";
var onGlobalMessage = function(event) {
if (event.source === global &&
typeof event.data === "string" &&
event.data.indexOf(messagePrefix) === 0) {
runIfPresent(+event.data.slice(messagePrefix.length));
}
};
if (global.addEventListener) {
global.addEventListener("message", onGlobalMessage, false);
} else {
global.attachEvent("onmessage", onGlobalMessage);
}
registerImmediate = function(handle) {
global.postMessage(messagePrefix + handle, "*");
};
}
function installMessageChannelImplementation() {
var channel = new MessageChannel();
channel.port1.onmessage = function(event) {
var handle = event.data;
runIfPresent(handle);
};
registerImmediate = function(handle) {
channel.port2.postMessage(handle);
};
}
function installReadyStateChangeImplementation() {
var html = doc.documentElement;
registerImmediate = function(handle) {
// Create a