human/dist/human.esm.js

52390 lines
2.0 MiB

/*
Human
homepage: <https://github.com/vladmandic/human>
author: <https://github.com/vladmandic>'
*/
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __export = (target, all2) => {
for (var name in all2)
__defProp(target, name, { get: all2[name], enumerable: true });
};
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
__accessCheck(obj, member, "write to private field");
setter ? setter.call(obj, value) : member.set(obj, value);
return value;
};
// src/util/util.ts
function log(...msg) {
const dt2 = new Date();
const ts2 = `${dt2.getHours().toString().padStart(2, "0")}:${dt2.getMinutes().toString().padStart(2, "0")}:${dt2.getSeconds().toString().padStart(2, "0")}.${dt2.getMilliseconds().toString().padStart(3, "0")}`;
if (msg)
console.log(ts2, "Human:", ...msg);
}
function join(folder, file) {
const separator = folder.endsWith("/") ? "" : "/";
const skipJoin = file.startsWith(".") || file.startsWith("/") || file.startsWith("http:") || file.startsWith("https:") || file.startsWith("file:");
const path = skipJoin ? `${file}` : `${folder}${separator}${file}`;
if (!path.toLocaleLowerCase().includes(".json"))
throw new Error(`modelpath error: expecting json file: ${path}`);
return path;
}
var now = () => {
if (typeof performance !== "undefined")
return performance.now();
return parseInt((Number(process.hrtime.bigint()) / 1e3 / 1e3).toString());
};
function validate(defaults, config3, parent = "config", msgs = []) {
for (const key of Object.keys(config3)) {
if (typeof config3[key] === "object") {
validate(defaults[key], config3[key], key, msgs);
} else {
const defined = defaults && typeof defaults[key] !== "undefined";
if (!defined)
msgs.push({ reason: "unknown property", where: `${parent}.${key} = ${config3[key]}` });
const same = defaults && typeof defaults[key] === typeof config3[key];
if (defined && !same)
msgs.push({ reason: "property type mismatch", where: `${parent}.${key} = ${config3[key]}`, expected: typeof defaults[key] });
}
}
if (config3.debug && parent === "config" && msgs.length > 0)
log("invalid configuration", msgs);
return msgs;
}
function mergeDeep(...objects) {
const isObject = (obj) => obj && typeof obj === "object";
return objects.reduce((prev, obj) => {
Object.keys(obj || {}).forEach((key) => {
const pVal = prev[key];
const oVal = obj[key];
if (Array.isArray(pVal) && Array.isArray(oVal))
prev[key] = pVal.concat(...oVal);
else if (isObject(pVal) && isObject(oVal))
prev[key] = mergeDeep(pVal, oVal);
else
prev[key] = oVal;
});
return prev;
}, {});
}
// src/config.ts
var config = {
backend: "",
modelBasePath: "",
cacheModels: true,
wasmPath: "",
wasmPlatformFetch: false,
debug: true,
async: true,
warmup: "full",
cacheSensitivity: 0.7,
skipAllowed: false,
deallocate: false,
filter: {
enabled: true,
equalization: false,
width: 0,
height: 0,
flip: false,
return: true,
brightness: 0,
contrast: 0,
sharpness: 0,
blur: 0,
saturation: 0,
hue: 0,
negative: false,
sepia: false,
vintage: false,
kodachrome: false,
technicolor: false,
polaroid: false,
pixelate: 0
},
gesture: {
enabled: true
},
face: {
enabled: true,
detector: {
modelPath: "blazeface.json",
rotation: true,
maxDetected: 1,
skipFrames: 99,
skipTime: 2500,
minConfidence: 0.2,
iouThreshold: 0.1,
mask: false,
return: false
},
mesh: {
enabled: true,
modelPath: "facemesh.json",
keepInvalid: false
},
attention: {
enabled: false,
modelPath: "facemesh-attention.json"
},
iris: {
enabled: true,
modelPath: "iris.json"
},
emotion: {
enabled: true,
minConfidence: 0.1,
skipFrames: 99,
skipTime: 1500,
modelPath: "emotion.json"
},
description: {
enabled: true,
modelPath: "faceres.json",
skipFrames: 99,
skipTime: 3e3,
minConfidence: 0.1
},
antispoof: {
enabled: false,
skipFrames: 99,
skipTime: 4e3,
modelPath: "antispoof.json"
},
liveness: {
enabled: false,
skipFrames: 99,
skipTime: 4e3,
modelPath: "liveness.json"
}
},
body: {
enabled: true,
modelPath: "movenet-lightning.json",
maxDetected: -1,
minConfidence: 0.3,
skipFrames: 1,
skipTime: 200
},
hand: {
enabled: true,
rotation: true,
skipFrames: 99,
skipTime: 1e3,
minConfidence: 0.5,
iouThreshold: 0.2,
maxDetected: -1,
landmarks: true,
detector: {
modelPath: "handtrack.json"
},
skeleton: {
modelPath: "handlandmark-full.json"
}
},
object: {
enabled: false,
modelPath: "mb3-centernet.json",
minConfidence: 0.2,
iouThreshold: 0.4,
maxDetected: 10,
skipFrames: 99,
skipTime: 2e3
},
segmentation: {
enabled: false,
modelPath: "selfie.json",
blur: 8
}
};
// dist/tfjs.esm.js
var tfjs_esm_exports = {};
__export(tfjs_esm_exports, {
Abs: () => di,
Acos: () => ul,
Acosh: () => ll,
AdadeltaOptimizer: () => Nb,
AdagradOptimizer: () => Tb,
AdamOptimizer: () => $b,
AdamaxOptimizer: () => _b,
Add: () => Cr,
AddN: () => Sa,
All: () => cl,
Any: () => dl,
ArgMax: () => Ia,
ArgMin: () => pl,
Asin: () => hl,
Asinh: () => fl,
Atan: () => ml,
Atan2: () => bl,
Atanh: () => gl,
AvgPool: () => Ca,
AvgPool3D: () => tp,
AvgPool3DGrad: () => yg,
AvgPoolGrad: () => bg,
BackendWasm: () => vpe,
BatchMatMul: () => Na,
BatchToSpaceND: () => pi,
Bincount: () => vg,
BroadcastArgs: () => xg,
BroadcastTo: () => j$,
Callback: () => JW,
CallbackList: () => mB,
Cast: () => Ta,
Ceil: () => $a,
ClipByValue: () => Nr,
Complex: () => np,
ComplexAbs: () => sp,
Concat: () => hi,
Conv2D: () => _a,
Conv2DBackpropFilter: () => wg,
Conv2DBackpropInput: () => Aa,
Conv3D: () => rp,
Conv3DBackpropFilterV2: () => kg,
Conv3DBackpropInputV2: () => Sg,
Cos: () => Ea,
Cosh: () => Ra,
CropAndResize: () => mi,
Cumprod: () => fi,
Cumsum: () => Da,
CustomCallback: () => yB,
DataStorage: () => Zd,
DenseBincount: () => Ig,
DepthToSpace: () => gi,
DepthwiseConv2dNative: () => Fa,
DepthwiseConv2dNativeBackpropFilter: () => Cg,
DepthwiseConv2dNativeBackpropInput: () => Ng,
Diag: () => Tg,
Dilation2D: () => ap,
Dilation2DBackpropFilter: () => um,
Dilation2DBackpropInput: () => im,
ENV: () => fk,
EarlyStopping: () => e4,
Einsum: () => op,
Elu: () => Pa,
EluGrad: () => $g,
Environment: () => V$,
Equal: () => bi,
Erf: () => yl,
Exp: () => za,
ExpandDims: () => yi,
Expm1: () => vi,
FFT: () => _g,
Fill: () => vl,
FlipLeftRight: () => xi,
Floor: () => La,
FloorDiv: () => Ma,
FromPixels: () => xd,
FusedBatchNorm: () => Ba,
FusedConv2D: () => ia,
FusedDepthwiseConv2D: () => ua,
GPGPUContext: () => am,
GatherNd: () => ki,
GatherV2: () => wi,
GraphModel: () => P0,
Greater: () => Si,
GreaterEqual: () => Va,
History: () => bB,
IFFT: () => Ag,
Identity: () => Wa,
Imag: () => ip,
InputSpec: () => Dt,
IsFinite: () => xl,
IsInf: () => wl,
IsNan: () => kl,
KernelBackend: () => il,
LRN: () => up,
LRNGrad: () => Rg,
LayerVariable: () => Az,
LayersModel: () => pr,
LeakyRelu: () => Ua,
Less: () => Ii,
LessEqual: () => Ci,
LinSpace: () => Eg,
Log: () => Ga,
Log1p: () => Sl,
LogSoftmax: () => X$,
LogicalAnd: () => Ni,
LogicalNot: () => Ti,
LogicalOr: () => Il,
LogicalXor: () => K$,
LowerBound: () => Cpe,
MathBackendCPU: () => rC,
MathBackendWebGL: () => n2,
Max: () => Ha,
MaxPool: () => ja,
MaxPool3D: () => lp,
MaxPool3DGrad: () => Fg,
MaxPoolGrad: () => Dg,
MaxPoolWithArgmax: () => Og,
Maximum: () => qa,
Mean: () => Ka,
Min: () => Xa,
Minimum: () => Ya,
MirrorPad: () => Qa,
Mod: () => Cl,
MomentumOptimizer: () => Ab,
Multinomial: () => Pg,
Multiply: () => Za,
Neg: () => $i,
NonMaxSuppressionV3: () => Ai,
NonMaxSuppressionV4: () => Nl,
NonMaxSuppressionV5: () => Ei,
NotEqual: () => _i,
OP_SCOPE_SUFFIX: () => T_,
OneHot: () => Di,
OnesLike: () => Ri,
Optimizer: () => Er,
OptimizerConstructors: () => Gr,
Pack: () => Fi,
PadV2: () => Ja,
Pool: () => Npe,
Pow: () => eo,
Prelu: () => to,
Prod: () => no,
RMSPropOptimizer: () => Eb,
RNN: () => Rr,
Range: () => Tl,
Rank: () => y_,
Real: () => cp,
RealDiv: () => Oa,
Reciprocal: () => $l,
Reduction: () => AO,
Relu: () => so,
Relu6: () => ao,
Reshape: () => Oi,
ResizeBilinear: () => ro,
ResizeBilinearGrad: () => Lg,
ResizeNearestNeighbor: () => _l,
ResizeNearestNeighborGrad: () => zg,
Reverse: () => Pi,
RotateWithOffset: () => Yi,
Round: () => zi,
Rsqrt: () => oo,
SGDOptimizer: () => Rp,
ScatterNd: () => Li,
SearchSorted: () => Mg,
Select: () => Mi,
Selu: () => Al,
Sequential: () => ty,
Sigmoid: () => uo,
Sign: () => El,
Sin: () => io,
Sinh: () => Vi,
Slice: () => Bi,
Softmax: () => po,
Softplus: () => Rl,
SpaceToBatchND: () => Wi,
SparseFillEmptyRows: () => dp,
SparseReshape: () => Dl,
SparseSegmentMean: () => pp,
SparseSegmentSum: () => hp,
SparseToDense: () => fp,
SplitV: () => Ui,
Sqrt: () => lo,
Square: () => Fl,
SquaredDifference: () => ho,
Step: () => go,
StridedSlice: () => Gi,
StringNGrams: () => mp,
StringSplit: () => Bg,
StringToHashBucketFast: () => Vg,
Sub: () => fo,
Sum: () => co,
SymbolicTensor: () => $s,
Tan: () => Hi,
Tanh: () => mo,
Tensor: () => et,
TensorBuffer: () => Vt,
Tile: () => Tr,
TopK: () => qi,
Transform: () => ji,
Transpose: () => Hs,
Unique: () => Wg,
Unpack: () => Ki,
UnsortedSegmentSum: () => gp,
UpperBound: () => Tpe,
Variable: () => kd,
ZerosLike: () => Xi,
_FusedMatMul: () => oa,
abs: () => Lt,
acos: () => pE,
acosh: () => fE,
add: () => oe,
addN: () => gE,
all: () => lS,
any: () => Sm,
argMax: () => Yu,
argMin: () => wE,
asin: () => SE,
asinh: () => CE,
atan: () => TE,
atan2: () => _E,
atanh: () => EE,
avgPool: () => nb,
avgPool3d: () => hS,
backend: () => $A,
backend_util: () => C,
basicLSTMCell: () => Hpe,
batchNorm: () => Zu,
batchNorm2d: () => YE,
batchNorm3d: () => ZE,
batchNorm4d: () => eR,
batchToSpaceND: () => sb,
bincount: () => fS,
booleanMaskAsync: () => vhe,
broadcastArgs: () => sR,
broadcastTo: () => id,
broadcast_util: () => Qi,
browser: () => Gk,
buffer: () => Ae,
callbacks: () => _he,
cast: () => le,
ceil: () => oR,
clipByValue: () => Wn,
clone: () => lr,
complex: () => mr,
concat: () => Ft,
concat1d: () => lR,
concat2d: () => dR,
concat3d: () => hR,
concat4d: () => mR,
constraints: () => qM,
conv1d: () => mS,
conv2d: () => da,
conv2dTranspose: () => gS,
conv3d: () => bS,
conv3dTranspose: () => SR,
copyRegisteredKernels: () => Ape,
cos: () => ab,
cosh: () => vS,
cosineWindow: () => GS,
cumprod: () => Cm,
cumsum: () => xS,
customGrad: () => js,
data: () => oU,
denseBincount: () => _R,
deprecationWarn: () => Wk,
depthToSpace: () => ER,
depthwiseConv2d: () => kp,
deregisterOp: () => Ehe,
device_util: () => vp,
diag: () => qpe,
dilation2d: () => OR,
disableDeprecationWarnings: () => Dpe,
dispose: () => De,
disposeVariables: () => Fpe,
div: () => xe,
divNoNan: () => BR,
dot: () => jpe,
dropout: () => CF,
einsum: () => UR,
elu: () => Sp,
enableDebugMode: () => Rpe,
enableProdMode: () => Epe,
enclosingPowerOfTwo: () => NF,
engine: () => ds,
env: () => K,
equal: () => Xn,
erf: () => qR,
euclideanNorm: () => sD,
exp: () => Yn,
expandDims: () => Pn,
expm1: () => iD,
eye: () => CS,
fft: () => wb,
fill: () => Bl,
findBackend: () => Vpe,
findBackendFactory: () => Wpe,
floor: () => Ip,
floorDiv: () => uS,
forceHalfFloat: () => I8,
fused: () => fa,
gather: () => Ju,
gatherND: () => kF,
gather_util: () => qk,
getBackend: () => Mpe,
getGradient: () => hx,
getKernel: () => lm,
getKernelsForBackend: () => cm,
getThreadsCount: () => Whe,
gpgpu_util: () => dX,
grad: () => Ype,
grads: () => Qpe,
greater: () => Gn,
greaterEqual: () => Zi,
ifft: () => $d,
imag: () => wp,
image: () => Kn,
inTopKAsync: () => whe,
initializers: () => QM,
input: () => lV,
io: () => An,
irfft: () => MS,
isFinite: () => Kpe,
isInf: () => Xpe,
isNaN: () => bD,
keep: () => qt,
kernel_impls: () => ws,
layers: () => hB,
leakyRelu: () => lb,
less: () => NS,
lessEqual: () => Ji,
linalg: () => cP,
linspace: () => wD,
loadGraphModel: () => Rhe,
loadGraphModelSync: () => Dhe,
loadLayersModel: () => The,
localResponseNormalization: () => SD,
log: () => Qn,
log1p: () => cb,
logSigmoid: () => ehe,
logSoftmax: () => TS,
logSumExp: () => RD,
logicalAnd: () => Ds,
logicalNot: () => db,
logicalOr: () => $S,
logicalXor: () => the,
losses: () => Ihe,
lowerBound: () => LD,
matMul: () => We,
math: () => CA,
max: () => As,
maxPool: () => pb,
maxPool3d: () => AS,
maxPoolWithArgmax: () => WD,
maximum: () => Ar,
mean: () => It,
memory: () => xm,
meshgrid: () => nhe,
metrics: () => RW,
min: () => Nm,
minimum: () => Np,
mirrorPad: () => jD,
mod: () => XD,
model: () => Che,
models: () => KW,
moments: () => hb,
movingAverage: () => xhe,
mul: () => V,
multiRNNCell: () => she,
multinomial: () => JD,
neg: () => vt,
nextFrame: () => ZS,
norm: () => ub,
notEqual: () => el,
oneHot: () => Cd,
ones: () => Ln,
onesLike: () => Zn,
op: () => M,
outerProduct: () => rhe,
pad: () => bo,
pad1d: () => ahe,
pad2d: () => ohe,
pad3d: () => ihe,
pad4d: () => uhe,
pool: () => lhe,
pow: () => ha,
prelu: () => mb,
print: () => iA,
prod: () => ES,
profile: () => Ope,
rand: () => che,
randomGamma: () => dhe,
randomNormal: () => v3,
randomUniform: () => Wl,
range: () => tl,
ready: () => Lpe,
real: () => Xu,
reciprocal: () => k3,
registerBackend: () => xp,
registerCallbackConstructor: () => $he,
registerGradient: () => Q$,
registerKernel: () => Ol,
registerOp: () => Ahe,
regularizers: () => XW,
relu: () => Xs,
relu6: () => RS,
removeBackend: () => Bpe,
reshape: () => U,
reverse: () => Jn,
reverse1d: () => phe,
reverse2d: () => hhe,
reverse3d: () => fhe,
reverse4d: () => mhe,
rfft: () => kb,
round: () => DS,
rsqrt: () => FS,
scalar: () => we,
scatterND: () => yF,
scatter_util: () => Kk,
searchSorted: () => _S,
selu: () => OS,
separableConv2d: () => F3,
sequential: () => Nhe,
serialization: () => re,
setBackend: () => zpe,
setPlatform: () => Upe,
setThreadsCount: () => Vhe,
setWasmPath: () => Mhe,
setWasmPaths: () => Bhe,
setWebGLContext: () => sK,
setdiff1dAsync: () => P3,
shared: () => cv,
sigmoid: () => qs,
sign: () => L3,
signal: () => She,
sin: () => PS,
sinh: () => zS,
slice: () => qe,
slice1d: () => yb,
slice2d: () => LS,
slice3d: () => vb,
slice4d: () => Td,
slice_util: () => kt,
softmax: () => xb,
softplus: () => Vl,
spaceToBatchND: () => fb,
sparse: () => jc,
sparseToDense: () => US,
spectral: () => khe,
split: () => Bn,
sqrt: () => dn,
square: () => ct,
squaredDifference: () => BS,
squeeze: () => br,
stack: () => es,
step: () => Tp,
stridedSlice: () => nF,
string: () => Yf,
sub: () => ge,
sum: () => ve,
sumOutType: () => yp,
tan: () => rF,
tanh: () => Qu,
tensor: () => ms,
tensor1d: () => Zt,
tensor2d: () => Zo,
tensor3d: () => OA,
tensor4d: () => ghe,
tensor5d: () => bhe,
tensor6d: () => yhe,
tensor_util: () => _s,
test_util: () => ZA,
tidy: () => q,
tile: () => hs,
time: () => Ppe,
topk: () => oF,
train: () => Mo,
transpose: () => Ge,
truncatedNormal: () => Sb,
unique: () => Ix,
unregisterGradient: () => _pe,
unregisterKernel: () => $pe,
unsortedSegmentSum: () => cF,
unstack: () => Fs,
upcastType: () => cn,
upperBound: () => pF,
util: () => w,
valueAndGrad: () => Zpe,
valueAndGrads: () => Jpe,
variable: () => hF,
variableGrads: () => ND,
version: () => Ghe,
version_converter: () => Fhe,
version_core: () => Gpe,
version_cpu: () => Ohe,
version_layers: () => NI,
version_wasm: () => Uhe,
version_webgl: () => Phe,
webgl: () => zhe,
webgl_util: () => nK,
webgpu: () => Yie,
where: () => vn,
whereAsync: () => WS,
zeros: () => $t,
zerosLike: () => je
});
var n$ = Object.create;
var Yd = Object.defineProperty;
var s$ = Object.getOwnPropertyDescriptor;
var nk = Object.getOwnPropertyNames;
var r$ = Object.getPrototypeOf;
var a$ = Object.prototype.hasOwnProperty;
var o$ = (e) => Yd(e, "__esModule", { value: true });
var zt = (e, t) => function() {
return t || (0, e[nk(e)[0]])((t = { exports: {} }).exports, t), t.exports;
};
var Ee = (e, t) => {
for (var n in t)
Yd(e, n, { get: t[n], enumerable: true });
};
var i$ = (e, t, n, s) => {
if (t && typeof t == "object" || typeof t == "function")
for (let r of nk(t))
!a$.call(e, r) && (n || r !== "default") && Yd(e, r, { get: () => t[r], enumerable: !(s = s$(t, r)) || s.enumerable });
return e;
};
var wa = (e, t) => i$(o$(Yd(e != null ? n$(r$(e)) : {}, "default", !t && e && e.__esModule ? { get: () => e.default, enumerable: true } : { value: e, enumerable: true })), e);
var u$ = zt({ "src/node_modules/long/src/long.js"(e, t) {
t.exports = s;
var n = null;
try {
n = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports;
} catch (D) {
}
function s(D, T, L) {
this.low = D | 0, this.high = T | 0, this.unsigned = !!L;
}
s.prototype.__isLong__, Object.defineProperty(s.prototype, "__isLong__", { value: true });
function r(D) {
return (D && D.__isLong__) === true;
}
s.isLong = r;
var a = {}, o = {};
function i(D, T) {
var L, W, j;
return T ? (D >>>= 0, (j = 0 <= D && D < 256) && (W = o[D], W) ? W : (L = l(D, (D | 0) < 0 ? -1 : 0, true), j && (o[D] = L), L)) : (D |= 0, (j = -128 <= D && D < 128) && (W = a[D], W) ? W : (L = l(D, D < 0 ? -1 : 0, false), j && (a[D] = L), L));
}
s.fromInt = i;
function u(D, T) {
if (isNaN(D))
return T ? x : v;
if (T) {
if (D < 0)
return x;
if (D >= g)
return E;
} else {
if (D <= -b)
return P;
if (D + 1 >= b)
return R;
}
return D < 0 ? u(-D, T).neg() : l(D % m | 0, D / m | 0, T);
}
s.fromNumber = u;
function l(D, T, L) {
return new s(D, T, L);
}
s.fromBits = l;
var c = Math.pow;
function p(D, T, L) {
if (D.length === 0)
throw Error("empty string");
if (D === "NaN" || D === "Infinity" || D === "+Infinity" || D === "-Infinity")
return v;
if (typeof T == "number" ? (L = T, T = false) : T = !!T, L = L || 10, L < 2 || 36 < L)
throw RangeError("radix");
var W;
if ((W = D.indexOf("-")) > 0)
throw Error("interior hyphen");
if (W === 0)
return p(D.substring(1), T, L).neg();
for (var j = u(c(L, 8)), Y = v, X = 0; X < D.length; X += 8) {
var Z = Math.min(8, D.length - X), ne = parseInt(D.substring(X, X + Z), L);
if (Z < 8) {
var ee = u(c(L, Z));
Y = Y.mul(ee).add(u(ne));
} else
Y = Y.mul(j), Y = Y.add(u(ne));
}
return Y.unsigned = T, Y;
}
s.fromString = p;
function d(D, T) {
return typeof D == "number" ? u(D, T) : typeof D == "string" ? p(D, T) : l(D.low, D.high, typeof T == "boolean" ? T : D.unsigned);
}
s.fromValue = d;
var h = 1 << 16, f = 1 << 24, m = h * h, g = m * m, b = g / 2, y = i(f), v = i(0);
s.ZERO = v;
var x = i(0, true);
s.UZERO = x;
var k = i(1);
s.ONE = k;
var I = i(1, true);
s.UONE = I;
var $ = i(-1);
s.NEG_ONE = $;
var R = l(-1, 2147483647, false);
s.MAX_VALUE = R;
var E = l(-1, -1, true);
s.MAX_UNSIGNED_VALUE = E;
var P = l(0, -2147483648, false);
s.MIN_VALUE = P;
var A = s.prototype;
A.toInt = function() {
return this.unsigned ? this.low >>> 0 : this.low;
}, A.toNumber = function() {
return this.unsigned ? (this.high >>> 0) * m + (this.low >>> 0) : this.high * m + (this.low >>> 0);
}, A.toString = function(T) {
if (T = T || 10, T < 2 || 36 < T)
throw RangeError("radix");
if (this.isZero())
return "0";
if (this.isNegative())
if (this.eq(P)) {
var L = u(T), W = this.div(L), j = W.mul(L).sub(this);
return W.toString(T) + j.toInt().toString(T);
} else
return "-" + this.neg().toString(T);
for (var Y = u(c(T, 6), this.unsigned), X = this, Z = ""; ; ) {
var ne = X.div(Y), ee = X.sub(ne.mul(Y)).toInt() >>> 0, se = ee.toString(T);
if (X = ne, X.isZero())
return se + Z;
for (; se.length < 6; )
se = "0" + se;
Z = "" + se + Z;
}
}, A.getHighBits = function() {
return this.high;
}, A.getHighBitsUnsigned = function() {
return this.high >>> 0;
}, A.getLowBits = function() {
return this.low;
}, A.getLowBitsUnsigned = function() {
return this.low >>> 0;
}, A.getNumBitsAbs = function() {
if (this.isNegative())
return this.eq(P) ? 64 : this.neg().getNumBitsAbs();
for (var T = this.high != 0 ? this.high : this.low, L = 31; L > 0 && (T & 1 << L) == 0; L--)
;
return this.high != 0 ? L + 33 : L + 1;
}, A.isZero = function() {
return this.high === 0 && this.low === 0;
}, A.eqz = A.isZero, A.isNegative = function() {
return !this.unsigned && this.high < 0;
}, A.isPositive = function() {
return this.unsigned || this.high >= 0;
}, A.isOdd = function() {
return (this.low & 1) === 1;
}, A.isEven = function() {
return (this.low & 1) === 0;
}, A.equals = function(T) {
return r(T) || (T = d(T)), this.unsigned !== T.unsigned && this.high >>> 31 === 1 && T.high >>> 31 === 1 ? false : this.high === T.high && this.low === T.low;
}, A.eq = A.equals, A.notEquals = function(T) {
return !this.eq(T);
}, A.neq = A.notEquals, A.ne = A.notEquals, A.lessThan = function(T) {
return this.comp(T) < 0;
}, A.lt = A.lessThan, A.lessThanOrEqual = function(T) {
return this.comp(T) <= 0;
}, A.lte = A.lessThanOrEqual, A.le = A.lessThanOrEqual, A.greaterThan = function(T) {
return this.comp(T) > 0;
}, A.gt = A.greaterThan, A.greaterThanOrEqual = function(T) {
return this.comp(T) >= 0;
}, A.gte = A.greaterThanOrEqual, A.ge = A.greaterThanOrEqual, A.compare = function(T) {
if (r(T) || (T = d(T)), this.eq(T))
return 0;
var L = this.isNegative(), W = T.isNegative();
return L && !W ? -1 : !L && W ? 1 : this.unsigned ? T.high >>> 0 > this.high >>> 0 || T.high === this.high && T.low >>> 0 > this.low >>> 0 ? -1 : 1 : this.sub(T).isNegative() ? -1 : 1;
}, A.comp = A.compare, A.negate = function() {
return !this.unsigned && this.eq(P) ? P : this.not().add(k);
}, A.neg = A.negate, A.add = function(T) {
r(T) || (T = d(T));
var L = this.high >>> 16, W = this.high & 65535, j = this.low >>> 16, Y = this.low & 65535, X = T.high >>> 16, Z = T.high & 65535, ne = T.low >>> 16, ee = T.low & 65535, se = 0, te = 0, ie = 0, ae = 0;
return ae += Y + ee, ie += ae >>> 16, ae &= 65535, ie += j + ne, te += ie >>> 16, ie &= 65535, te += W + Z, se += te >>> 16, te &= 65535, se += L + X, se &= 65535, l(ie << 16 | ae, se << 16 | te, this.unsigned);
}, A.subtract = function(T) {
return r(T) || (T = d(T)), this.add(T.neg());
}, A.sub = A.subtract, A.multiply = function(T) {
if (this.isZero())
return v;
if (r(T) || (T = d(T)), n) {
var L = n.mul(this.low, this.high, T.low, T.high);
return l(L, n.get_high(), this.unsigned);
}
if (T.isZero())
return v;
if (this.eq(P))
return T.isOdd() ? P : v;
if (T.eq(P))
return this.isOdd() ? P : v;
if (this.isNegative())
return T.isNegative() ? this.neg().mul(T.neg()) : this.neg().mul(T).neg();
if (T.isNegative())
return this.mul(T.neg()).neg();
if (this.lt(y) && T.lt(y))
return u(this.toNumber() * T.toNumber(), this.unsigned);
var W = this.high >>> 16, j = this.high & 65535, Y = this.low >>> 16, X = this.low & 65535, Z = T.high >>> 16, ne = T.high & 65535, ee = T.low >>> 16, se = T.low & 65535, te = 0, ie = 0, ae = 0, de = 0;
return de += X * se, ae += de >>> 16, de &= 65535, ae += Y * se, ie += ae >>> 16, ae &= 65535, ae += X * ee, ie += ae >>> 16, ae &= 65535, ie += j * se, te += ie >>> 16, ie &= 65535, ie += Y * ee, te += ie >>> 16, ie &= 65535, ie += X * ne, te += ie >>> 16, ie &= 65535, te += W * se + j * ee + Y * ne + X * Z, te &= 65535, l(ae << 16 | de, te << 16 | ie, this.unsigned);
}, A.mul = A.multiply, A.divide = function(T) {
if (r(T) || (T = d(T)), T.isZero())
throw Error("division by zero");
if (n) {
if (!this.unsigned && this.high === -2147483648 && T.low === -1 && T.high === -1)
return this;
var L = (this.unsigned ? n.div_u : n.div_s)(this.low, this.high, T.low, T.high);
return l(L, n.get_high(), this.unsigned);
}
if (this.isZero())
return this.unsigned ? x : v;
var W, j, Y;
if (this.unsigned) {
if (T.unsigned || (T = T.toUnsigned()), T.gt(this))
return x;
if (T.gt(this.shru(1)))
return I;
Y = x;
} else {
if (this.eq(P)) {
if (T.eq(k) || T.eq($))
return P;
if (T.eq(P))
return k;
var X = this.shr(1);
return W = X.div(T).shl(1), W.eq(v) ? T.isNegative() ? k : $ : (j = this.sub(T.mul(W)), Y = W.add(j.div(T)), Y);
} else if (T.eq(P))
return this.unsigned ? x : v;
if (this.isNegative())
return T.isNegative() ? this.neg().div(T.neg()) : this.neg().div(T).neg();
if (T.isNegative())
return this.div(T.neg()).neg();
Y = v;
}
for (j = this; j.gte(T); ) {
W = Math.max(1, Math.floor(j.toNumber() / T.toNumber()));
for (var Z = Math.ceil(Math.log(W) / Math.LN2), ne = Z <= 48 ? 1 : c(2, Z - 48), ee = u(W), se = ee.mul(T); se.isNegative() || se.gt(j); )
W -= ne, ee = u(W, this.unsigned), se = ee.mul(T);
ee.isZero() && (ee = k), Y = Y.add(ee), j = j.sub(se);
}
return Y;
}, A.div = A.divide, A.modulo = function(T) {
if (r(T) || (T = d(T)), n) {
var L = (this.unsigned ? n.rem_u : n.rem_s)(this.low, this.high, T.low, T.high);
return l(L, n.get_high(), this.unsigned);
}
return this.sub(this.div(T).mul(T));
}, A.mod = A.modulo, A.rem = A.modulo, A.not = function() {
return l(~this.low, ~this.high, this.unsigned);
}, A.and = function(T) {
return r(T) || (T = d(T)), l(this.low & T.low, this.high & T.high, this.unsigned);
}, A.or = function(T) {
return r(T) || (T = d(T)), l(this.low | T.low, this.high | T.high, this.unsigned);
}, A.xor = function(T) {
return r(T) || (T = d(T)), l(this.low ^ T.low, this.high ^ T.high, this.unsigned);
}, A.shiftLeft = function(T) {
return r(T) && (T = T.toInt()), (T &= 63) === 0 ? this : T < 32 ? l(this.low << T, this.high << T | this.low >>> 32 - T, this.unsigned) : l(0, this.low << T - 32, this.unsigned);
}, A.shl = A.shiftLeft, A.shiftRight = function(T) {
return r(T) && (T = T.toInt()), (T &= 63) === 0 ? this : T < 32 ? l(this.low >>> T | this.high << 32 - T, this.high >> T, this.unsigned) : l(this.high >> T - 32, this.high >= 0 ? 0 : -1, this.unsigned);
}, A.shr = A.shiftRight, A.shiftRightUnsigned = function(T) {
if (r(T) && (T = T.toInt()), T &= 63, T === 0)
return this;
var L = this.high;
if (T < 32) {
var W = this.low;
return l(W >>> T | L << 32 - T, L >>> T, this.unsigned);
} else
return T === 32 ? l(L, 0, this.unsigned) : l(L >>> T - 32, 0, this.unsigned);
}, A.shru = A.shiftRightUnsigned, A.shr_u = A.shiftRightUnsigned, A.toSigned = function() {
return this.unsigned ? l(this.low, this.high, false) : this;
}, A.toUnsigned = function() {
return this.unsigned ? this : l(this.low, this.high, true);
}, A.toBytes = function(T) {
return T ? this.toBytesLE() : this.toBytesBE();
}, A.toBytesLE = function() {
var T = this.high, L = this.low;
return [L & 255, L >>> 8 & 255, L >>> 16 & 255, L >>> 24, T & 255, T >>> 8 & 255, T >>> 16 & 255, T >>> 24];
}, A.toBytesBE = function() {
var T = this.high, L = this.low;
return [T >>> 24, T >>> 16 & 255, T >>> 8 & 255, T & 255, L >>> 24, L >>> 16 & 255, L >>> 8 & 255, L & 255];
}, s.fromBytes = function(T, L, W) {
return W ? s.fromBytesLE(T, L) : s.fromBytesBE(T, L);
}, s.fromBytesLE = function(T, L) {
return new s(T[0] | T[1] << 8 | T[2] << 16 | T[3] << 24, T[4] | T[5] << 8 | T[6] << 16 | T[7] << 24, L);
}, s.fromBytesBE = function(T, L) {
return new s(T[4] << 24 | T[5] << 16 | T[6] << 8 | T[7], T[0] << 24 | T[1] << 16 | T[2] << 8 | T[3], L);
};
} });
var l$ = zt({ "(disabled):src/node_modules/node-fetch/browser.js"() {
} });
var c$ = zt({ "(disabled):util"() {
} });
var d$ = zt({ "src/node_modules/seedrandom/lib/alea.js"(e, t) {
(function(n, s, r) {
function a(l) {
var c = this, p = u();
c.next = function() {
var d = 2091639 * c.s0 + c.c * 23283064365386963e-26;
return c.s0 = c.s1, c.s1 = c.s2, c.s2 = d - (c.c = d | 0);
}, c.c = 1, c.s0 = p(" "), c.s1 = p(" "), c.s2 = p(" "), c.s0 -= p(l), c.s0 < 0 && (c.s0 += 1), c.s1 -= p(l), c.s1 < 0 && (c.s1 += 1), c.s2 -= p(l), c.s2 < 0 && (c.s2 += 1), p = null;
}
function o(l, c) {
return c.c = l.c, c.s0 = l.s0, c.s1 = l.s1, c.s2 = l.s2, c;
}
function i(l, c) {
var p = new a(l), d = c && c.state, h = p.next;
return h.int32 = function() {
return p.next() * 4294967296 | 0;
}, h.double = function() {
return h() + (h() * 2097152 | 0) * 11102230246251565e-32;
}, h.quick = h, d && (typeof d == "object" && o(d, p), h.state = function() {
return o(p, {});
}), h;
}
function u() {
var l = 4022871197, c = function(p) {
p = String(p);
for (var d = 0; d < p.length; d++) {
l += p.charCodeAt(d);
var h = 0.02519603282416938 * l;
l = h >>> 0, h -= l, h *= l, l = h >>> 0, h -= l, l += h * 4294967296;
}
return (l >>> 0) * 23283064365386963e-26;
};
return c;
}
s && s.exports ? s.exports = i : r && r.amd ? r(function() {
return i;
}) : this.alea = i;
})(e, typeof t == "object" && t, typeof define == "function" && define);
} });
var p$ = zt({ "src/node_modules/seedrandom/lib/xor128.js"(e, t) {
(function(n, s, r) {
function a(u) {
var l = this, c = "";
l.x = 0, l.y = 0, l.z = 0, l.w = 0, l.next = function() {
var d = l.x ^ l.x << 11;
return l.x = l.y, l.y = l.z, l.z = l.w, l.w ^= l.w >>> 19 ^ d ^ d >>> 8;
}, u === (u | 0) ? l.x = u : c += u;
for (var p = 0; p < c.length + 64; p++)
l.x ^= c.charCodeAt(p) | 0, l.next();
}
function o(u, l) {
return l.x = u.x, l.y = u.y, l.z = u.z, l.w = u.w, l;
}
function i(u, l) {
var c = new a(u), p = l && l.state, d = function() {
return (c.next() >>> 0) / 4294967296;
};
return d.double = function() {
do
var h = c.next() >>> 11, f = (c.next() >>> 0) / 4294967296, m = (h + f) / (1 << 21);
while (m === 0);
return m;
}, d.int32 = c.next, d.quick = d, p && (typeof p == "object" && o(p, c), d.state = function() {
return o(c, {});
}), d;
}
s && s.exports ? s.exports = i : r && r.amd ? r(function() {
return i;
}) : this.xor128 = i;
})(e, typeof t == "object" && t, typeof define == "function" && define);
} });
var h$ = zt({ "src/node_modules/seedrandom/lib/xorwow.js"(e, t) {
(function(n, s, r) {
function a(u) {
var l = this, c = "";
l.next = function() {
var d = l.x ^ l.x >>> 2;
return l.x = l.y, l.y = l.z, l.z = l.w, l.w = l.v, (l.d = l.d + 362437 | 0) + (l.v = l.v ^ l.v << 4 ^ (d ^ d << 1)) | 0;
}, l.x = 0, l.y = 0, l.z = 0, l.w = 0, l.v = 0, u === (u | 0) ? l.x = u : c += u;
for (var p = 0; p < c.length + 64; p++)
l.x ^= c.charCodeAt(p) | 0, p == c.length && (l.d = l.x << 10 ^ l.x >>> 4), l.next();
}
function o(u, l) {
return l.x = u.x, l.y = u.y, l.z = u.z, l.w = u.w, l.v = u.v, l.d = u.d, l;
}
function i(u, l) {
var c = new a(u), p = l && l.state, d = function() {
return (c.next() >>> 0) / 4294967296;
};
return d.double = function() {
do
var h = c.next() >>> 11, f = (c.next() >>> 0) / 4294967296, m = (h + f) / (1 << 21);
while (m === 0);
return m;
}, d.int32 = c.next, d.quick = d, p && (typeof p == "object" && o(p, c), d.state = function() {
return o(c, {});
}), d;
}
s && s.exports ? s.exports = i : r && r.amd ? r(function() {
return i;
}) : this.xorwow = i;
})(e, typeof t == "object" && t, typeof define == "function" && define);
} });
var f$ = zt({ "src/node_modules/seedrandom/lib/xorshift7.js"(e, t) {
(function(n, s, r) {
function a(u) {
var l = this;
l.next = function() {
var p = l.x, d = l.i, h, f, m;
return h = p[d], h ^= h >>> 7, f = h ^ h << 24, h = p[d + 1 & 7], f ^= h ^ h >>> 10, h = p[d + 3 & 7], f ^= h ^ h >>> 3, h = p[d + 4 & 7], f ^= h ^ h << 7, h = p[d + 7 & 7], h = h ^ h << 13, f ^= h ^ h << 9, p[d] = f, l.i = d + 1 & 7, f;
};
function c(p, d) {
var h, f, m = [];
if (d === (d | 0))
f = m[0] = d;
else
for (d = "" + d, h = 0; h < d.length; ++h)
m[h & 7] = m[h & 7] << 15 ^ d.charCodeAt(h) + m[h + 1 & 7] << 13;
for (; m.length < 8; )
m.push(0);
for (h = 0; h < 8 && m[h] === 0; ++h)
;
for (h == 8 ? f = m[7] = -1 : f = m[h], p.x = m, p.i = 0, h = 256; h > 0; --h)
p.next();
}
c(l, u);
}
function o(u, l) {
return l.x = u.x.slice(), l.i = u.i, l;
}
function i(u, l) {
u == null && (u = +new Date());
var c = new a(u), p = l && l.state, d = function() {
return (c.next() >>> 0) / 4294967296;
};
return d.double = function() {
do
var h = c.next() >>> 11, f = (c.next() >>> 0) / 4294967296, m = (h + f) / (1 << 21);
while (m === 0);
return m;
}, d.int32 = c.next, d.quick = d, p && (p.x && o(p, c), d.state = function() {
return o(c, {});
}), d;
}
s && s.exports ? s.exports = i : r && r.amd ? r(function() {
return i;
}) : this.xorshift7 = i;
})(e, typeof t == "object" && t, typeof define == "function" && define);
} });
var m$ = zt({ "src/node_modules/seedrandom/lib/xor4096.js"(e, t) {
(function(n, s, r) {
function a(u) {
var l = this;
l.next = function() {
var p = l.w, d = l.X, h = l.i, f, m;
return l.w = p = p + 1640531527 | 0, m = d[h + 34 & 127], f = d[h = h + 1 & 127], m ^= m << 13, f ^= f << 17, m ^= m >>> 15, f ^= f >>> 12, m = d[h] = m ^ f, l.i = h, m + (p ^ p >>> 16) | 0;
};
function c(p, d) {
var h, f, m, g, b, y = [], v = 128;
for (d === (d | 0) ? (f = d, d = null) : (d = d + "\0", f = 0, v = Math.max(v, d.length)), m = 0, g = -32; g < v; ++g)
d && (f ^= d.charCodeAt((g + 32) % d.length)), g === 0 && (b = f), f ^= f << 10, f ^= f >>> 15, f ^= f << 4, f ^= f >>> 13, g >= 0 && (b = b + 1640531527 | 0, h = y[g & 127] ^= f + b, m = h == 0 ? m + 1 : 0);
for (m >= 128 && (y[(d && d.length || 0) & 127] = -1), m = 127, g = 4 * 128; g > 0; --g)
f = y[m + 34 & 127], h = y[m = m + 1 & 127], f ^= f << 13, h ^= h << 17, f ^= f >>> 15, h ^= h >>> 12, y[m] = f ^ h;
p.w = b, p.X = y, p.i = m;
}
c(l, u);
}
function o(u, l) {
return l.i = u.i, l.w = u.w, l.X = u.X.slice(), l;
}
function i(u, l) {
u == null && (u = +new Date());
var c = new a(u), p = l && l.state, d = function() {
return (c.next() >>> 0) / 4294967296;
};
return d.double = function() {
do
var h = c.next() >>> 11, f = (c.next() >>> 0) / 4294967296, m = (h + f) / (1 << 21);
while (m === 0);
return m;
}, d.int32 = c.next, d.quick = d, p && (p.X && o(p, c), d.state = function() {
return o(c, {});
}), d;
}
s && s.exports ? s.exports = i : r && r.amd ? r(function() {
return i;
}) : this.xor4096 = i;
})(e, typeof t == "object" && t, typeof define == "function" && define);
} });
var g$ = zt({ "src/node_modules/seedrandom/lib/tychei.js"(e, t) {
(function(n, s, r) {
function a(u) {
var l = this, c = "";
l.next = function() {
var d = l.b, h = l.c, f = l.d, m = l.a;
return d = d << 25 ^ d >>> 7 ^ h, h = h - f | 0, f = f << 24 ^ f >>> 8 ^ m, m = m - d | 0, l.b = d = d << 20 ^ d >>> 12 ^ h, l.c = h = h - f | 0, l.d = f << 16 ^ h >>> 16 ^ m, l.a = m - d | 0;
}, l.a = 0, l.b = 0, l.c = -1640531527, l.d = 1367130551, u === Math.floor(u) ? (l.a = u / 4294967296 | 0, l.b = u | 0) : c += u;
for (var p = 0; p < c.length + 20; p++)
l.b ^= c.charCodeAt(p) | 0, l.next();
}
function o(u, l) {
return l.a = u.a, l.b = u.b, l.c = u.c, l.d = u.d, l;
}
function i(u, l) {
var c = new a(u), p = l && l.state, d = function() {
return (c.next() >>> 0) / 4294967296;
};
return d.double = function() {
do
var h = c.next() >>> 11, f = (c.next() >>> 0) / 4294967296, m = (h + f) / (1 << 21);
while (m === 0);
return m;
}, d.int32 = c.next, d.quick = d, p && (typeof p == "object" && o(p, c), d.state = function() {
return o(c, {});
}), d;
}
s && s.exports ? s.exports = i : r && r.amd ? r(function() {
return i;
}) : this.tychei = i;
})(e, typeof t == "object" && t, typeof define == "function" && define);
} });
var b$ = zt({ "(disabled):crypto"() {
} });
var y$ = zt({ "src/node_modules/seedrandom/seedrandom.js"(e, t) {
(function(n, s, r) {
var a = 256, o = 6, i = 52, u = "random", l = r.pow(a, o), c = r.pow(2, i), p = c * 2, d = a - 1, h;
function f(k, I, $) {
var R = [];
I = I == true ? { entropy: true } : I || {};
var E = y(b(I.entropy ? [k, x(s)] : k == null ? v() : k, 3), R), P = new m(R), A = function() {
for (var D = P.g(o), T = l, L = 0; D < c; )
D = (D + L) * a, T *= a, L = P.g(1);
for (; D >= p; )
D /= 2, T /= 2, L >>>= 1;
return (D + L) / T;
};
return A.int32 = function() {
return P.g(4) | 0;
}, A.quick = function() {
return P.g(4) / 4294967296;
}, A.double = A, y(x(P.S), s), (I.pass || $ || function(D, T, L, W) {
return W && (W.S && g(W, P), D.state = function() {
return g(P, {});
}), L ? (r[u] = D, T) : D;
})(A, E, "global" in I ? I.global : this == r, I.state);
}
function m(k) {
var I, $ = k.length, R = this, E = 0, P = R.i = R.j = 0, A = R.S = [];
for ($ || (k = [$++]); E < a; )
A[E] = E++;
for (E = 0; E < a; E++)
A[E] = A[P = d & P + k[E % $] + (I = A[E])], A[P] = I;
(R.g = function(D) {
for (var T, L = 0, W = R.i, j = R.j, Y = R.S; D--; )
T = Y[W = d & W + 1], L = L * a + Y[d & (Y[W] = Y[j = d & j + T]) + (Y[j] = T)];
return R.i = W, R.j = j, L;
})(a);
}
function g(k, I) {
return I.i = k.i, I.j = k.j, I.S = k.S.slice(), I;
}
function b(k, I) {
var $ = [], R = typeof k, E;
if (I && R == "object")
for (E in k)
try {
$.push(b(k[E], I - 1));
} catch (P) {
}
return $.length ? $ : R == "string" ? k : k + "\0";
}
function y(k, I) {
for (var $ = k + "", R, E = 0; E < $.length; )
I[d & E] = d & (R ^= I[d & E] * 19) + $.charCodeAt(E++);
return x(I);
}
function v() {
try {
var k;
return h && (k = h.randomBytes) ? k = k(a) : (k = new Uint8Array(a), (n.crypto || n.msCrypto).getRandomValues(k)), x(k);
} catch (R) {
var I = n.navigator, $ = I && I.plugins;
return [+new Date(), n, $, n.screen, x(s)];
}
}
function x(k) {
return String.fromCharCode.apply(0, k);
}
if (y(r.random(), s), typeof t == "object" && t.exports) {
t.exports = f;
try {
h = b$();
} catch (k) {
}
} else
typeof define == "function" && define.amd ? define(function() {
return f;
}) : r["seed" + u] = f;
})(typeof self != "undefined" ? self : e, [], Math);
} });
var Qd = zt({ "src/node_modules/seedrandom/index.js"(e, t) {
var n = d$(), s = p$(), r = h$(), a = f$(), o = m$(), i = g$(), u = y$();
u.alea = n, u.xor128 = s, u.xorwow = r, u.xorshift7 = a, u.xor4096 = o, u.tychei = i, t.exports = u;
} });
var sk = zt({ "(disabled):src/node_modules/string_decoder/index.js"() {
} });
var pg = zt({ "(disabled):fs"() {
} });
var bd = zt({ "(disabled):path"() {
} });
var v$ = zt({ "(disabled):worker_threads"() {
} });
var x$ = zt({ "(disabled):perf_hooks"() {
} });
var w$ = zt({ "(disabled):os"() {
} });
var k$ = zt({ "src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm-threaded-simd.js"(e, t) {
var n = (() => {
var s = typeof document != "undefined" && document.currentScript ? document.currentScript.src : void 0;
return typeof __filename != "undefined" && (s = s || __filename), function(r) {
r = r || {};
function a() {
return Ce.buffer != nn && rs(Ce.buffer), cc;
}
function o() {
return Ce.buffer != nn && rs(Ce.buffer), dc;
}
function i() {
return Ce.buffer != nn && rs(Ce.buffer), bu;
}
function u() {
return Ce.buffer != nn && rs(Ce.buffer), pc;
}
function l() {
return Ce.buffer != nn && rs(Ce.buffer), hc;
}
function c() {
return Ce.buffer != nn && rs(Ce.buffer), fc;
}
function p() {
return Ce.buffer != nn && rs(Ce.buffer), mc;
}
var d = typeof r != "undefined" ? r : {}, h, f;
d.ready = new Promise(function(N, F) {
h = N, f = F;
});
var m;
typeof process != "undefined" && process.listeners && (m = { uncaughtException: process.listeners("uncaughtException"), unhandledRejection: process.listeners("unhandledRejection") });
var g = Object.assign({}, d), b = [], y = "./this.program", v = (N, F) => {
throw F;
}, x = typeof window == "object", k = typeof importScripts == "function", I = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string", $ = d.ENVIRONMENT_IS_PTHREAD || false, R = "";
function E(N) {
return d.locateFile ? d.locateFile(N, R) : R + N;
}
var P, A, D, T;
function L(N) {
if (N instanceof Nu)
return;
ee("exiting due to exception: " + N);
}
var W, j, Y;
if (I) {
k ? R = bd().dirname(R) + "/" : R = __dirname + "/", Y = () => {
j || (W = pg(), j = bd());
}, P = function(B, Q) {
return Y(), B = j.normalize(B), W.readFileSync(B, Q ? void 0 : "utf8");
}, D = (F) => {
var B = P(F, true);
return B.buffer || (B = new Uint8Array(B)), B;
}, A = (F, B, Q) => {
Y(), F = j.normalize(F), W.readFile(F, function(ue, he) {
ue ? Q(ue) : B(he.buffer);
});
}, process.argv.length > 1 && (y = process.argv[1].replace(/\\/g, "/")), b = process.argv.slice(2), process.on("uncaughtException", function(F) {
if (!(F instanceof Nu))
throw F;
}), process.on("unhandledRejection", function(F) {
throw F;
}), v = (F, B) => {
if (Lr())
throw process.exitCode = F, B;
L(B), process.exit(F);
}, d.inspect = function() {
return "[Emscripten Module object]";
};
let N;
try {
N = v$();
} catch (F) {
throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'), F;
}
global.Worker = N.Worker;
} else
(x || k) && (k ? R = self.location.href : typeof document != "undefined" && document.currentScript && (R = document.currentScript.src), typeof s != "undefined" && s && (R = s), R.indexOf("blob:") !== 0 ? R = R.substr(0, R.replace(/[?#].*/, "").lastIndexOf("/") + 1) : R = "", I || (P = (N) => {
var F = new XMLHttpRequest();
return F.open("GET", N, false), F.send(null), F.responseText;
}, k && (D = (N) => {
var F = new XMLHttpRequest();
return F.open("GET", N, false), F.responseType = "arraybuffer", F.send(null), new Uint8Array(F.response);
}), A = (N, F, B) => {
var Q = new XMLHttpRequest();
Q.open("GET", N, true), Q.responseType = "arraybuffer", Q.onload = () => {
if (Q.status == 200 || Q.status == 0 && Q.response) {
F(Q.response);
return;
}
B();
}, Q.onerror = B, Q.send(null);
}), T = (N) => document.title = N);
I && typeof performance == "undefined" && (global.performance = x$().performance);
var X = console.log.bind(console), Z = console.warn.bind(console);
I && (Y(), X = (N) => W.writeSync(1, N + `
`), Z = (N) => W.writeSync(2, N + `
`));
var ne = d.print || X, ee = d.printErr || Z;
Object.assign(d, g), g = null, d.arguments && (b = d.arguments), d.thisProgram && (y = d.thisProgram), d.quit && (v = d.quit);
var se = 4;
function te(N) {
te.shown || (te.shown = {}), te.shown[N] || (te.shown[N] = 1, ee(N));
}
function ie(N, F) {
if (typeof WebAssembly.Function == "function") {
for (var B = { i: "i32", j: "i64", f: "f32", d: "f64" }, Q = { parameters: [], results: F[0] == "v" ? [] : [B[F[0]]] }, ue = 1; ue < F.length; ++ue)
Q.parameters.push(B[F[ue]]);
return new WebAssembly.Function(Q, N);
}
var he = [1, 0, 1, 96], ye = F.slice(0, 1), Te = F.slice(1), bt = { i: 127, j: 126, f: 125, d: 124 };
he.push(Te.length);
for (var ue = 0; ue < Te.length; ++ue)
he.push(bt[Te[ue]]);
ye == "v" ? he.push(0) : he = he.concat([1, bt[ye]]), he[1] = he.length - 2;
var us = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0].concat(he, [2, 7, 1, 1, 101, 1, 102, 0, 0, 7, 5, 1, 1, 102, 0, 0])), ls = new WebAssembly.Module(us), Gc = new WebAssembly.Instance(ls, { e: { f: N } }), Tu = Gc.exports.f;
return Tu;
}
var ae = [], de;
function me() {
if (ae.length)
return ae.pop();
try {
Fn.grow(1);
} catch (N) {
throw N instanceof RangeError ? "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH." : N;
}
return Fn.length - 1;
}
function ke(N, F) {
for (var B = N; B < N + F; B++) {
var Q = Eo(B);
Q && de.set(Q, B);
}
}
var Ie = 0, Re = (N) => {
Ie = N;
}, Pe = Atomics.load, Xe = Atomics.store, Je = Atomics.compareExchange, Ye;
d.wasmBinary && (Ye = d.wasmBinary);
var tt = d.noExitRuntime || true;
typeof WebAssembly != "object" && $o("no native wasm support detected");
var Ce, ut, ot = false, Jt;
function Nt(N, F) {
N || $o(F);
}
function In(N) {
var F = d["_" + N];
return F;
}
function Et(N, F, B, Q, ue) {
var he = { string: function(Tn) {
var Lo = 0;
if (Tn != null && Tn !== 0) {
var dx = (Tn.length << 2) + 1;
Lo = zo(dx), Ls(Tn, Lo, dx);
}
return Lo;
}, array: function(Tn) {
var Lo = zo(Tn.length);
return Ms(Tn, Lo), Lo;
} };
function ye(Tn) {
return F === "string" ? tn(Tn) : F === "boolean" ? Boolean(Tn) : Tn;
}
var Te = In(N), bt = [], us = 0;
if (Q)
for (var ls = 0; ls < Q.length; ls++) {
var Gc = he[B[ls]];
Gc ? (us === 0 && (us = Uf()), bt[ls] = Gc(Q[ls])) : bt[ls] = Q[ls];
}
var Tu = Te.apply(null, bt);
function t$(Tn) {
return us !== 0 && Bc(us), ye(Tn);
}
return Tu = t$(Tu), Tu;
}
function en(N, F, B, Q) {
B = B || [];
var ue = B.every(function(ye) {
return ye === "number";
}), he = F !== "string";
return he && ue && !Q ? In(N) : function() {
return Et(N, F, B, arguments, Q);
};
}
var Cn = 1;
function Nn(N) {
var F = new TextDecoder(N);
this.decode = (B) => (B.buffer instanceof SharedArrayBuffer && (B = new Uint8Array(B)), F.decode.call(F, B));
}
var Yt = typeof TextDecoder != "undefined" ? new Nn("utf8") : void 0;
function Dn(N, F, B) {
for (var Q = F + B, ue = F; N[ue] && !(ue >= Q); )
++ue;
if (ue - F > 16 && N.subarray && Yt)
return Yt.decode(N.subarray(F, ue));
for (var he = ""; F < ue; ) {
var ye = N[F++];
if (!(ye & 128)) {
he += String.fromCharCode(ye);
continue;
}
var Te = N[F++] & 63;
if ((ye & 224) == 192) {
he += String.fromCharCode((ye & 31) << 6 | Te);
continue;
}
var bt = N[F++] & 63;
if ((ye & 240) == 224 ? ye = (ye & 15) << 12 | Te << 6 | bt : ye = (ye & 7) << 18 | Te << 12 | bt << 6 | N[F++] & 63, ye < 65536)
he += String.fromCharCode(ye);
else {
var us = ye - 65536;
he += String.fromCharCode(55296 | us >> 10, 56320 | us & 1023);
}
}
return he;
}
function tn(N, F) {
return N ? Dn(o(), N, F) : "";
}
function zs(N, F, B, Q) {
if (!(Q > 0))
return 0;
for (var ue = B, he = B + Q - 1, ye = 0; ye < N.length; ++ye) {
var Te = N.charCodeAt(ye);
if (Te >= 55296 && Te <= 57343) {
var bt = N.charCodeAt(++ye);
Te = 65536 + ((Te & 1023) << 10) | bt & 1023;
}
if (Te <= 127) {
if (B >= he)
break;
F[B++] = Te;
} else if (Te <= 2047) {
if (B + 1 >= he)
break;
F[B++] = 192 | Te >> 6, F[B++] = 128 | Te & 63;
} else if (Te <= 65535) {
if (B + 2 >= he)
break;
F[B++] = 224 | Te >> 12, F[B++] = 128 | Te >> 6 & 63, F[B++] = 128 | Te & 63;
} else {
if (B + 3 >= he)
break;
F[B++] = 240 | Te >> 18, F[B++] = 128 | Te >> 12 & 63, F[B++] = 128 | Te >> 6 & 63, F[B++] = 128 | Te & 63;
}
}
return F[B] = 0, B - ue;
}
function Ls(N, F, B) {
return zs(N, o(), F, B);
}
function Co(N) {
for (var F = 0, B = 0; B < N.length; ++B) {
var Q = N.charCodeAt(B);
Q >= 55296 && Q <= 57343 && (Q = 65536 + ((Q & 1023) << 10) | N.charCodeAt(++B) & 1023), Q <= 127 ? ++F : Q <= 2047 ? F += 2 : Q <= 65535 ? F += 3 : F += 4;
}
return F;
}
var Zs = typeof TextDecoder != "undefined" ? new Nn("utf-16le") : void 0;
function Ms(N, F) {
a().set(N, F);
}
function gu(N, F, B) {
for (var Q = 0; Q < N.length; ++Q)
a()[F++ >> 0] = N.charCodeAt(Q);
B || (a()[F >> 0] = 0);
}
function No(N, F) {
return N % F > 0 && (N += F - N % F), N;
}
var nn, cc, dc, bu, pc, hc, Hv, fc, mc;
$ && (nn = d.buffer);
function rs(N) {
nn = N, d.HEAP8 = cc = new Int8Array(N), d.HEAP16 = bu = new Int16Array(N), d.HEAP32 = hc = new Int32Array(N), d.HEAPU8 = dc = new Uint8Array(N), d.HEAPU16 = pc = new Uint16Array(N), d.HEAPU32 = Hv = new Uint32Array(N), d.HEAPF32 = fc = new Float32Array(N), d.HEAPF64 = mc = new Float64Array(N);
}
var gc = d.INITIAL_MEMORY || 16777216;
if ($)
Ce = d.wasmMemory, nn = d.buffer;
else if (d.wasmMemory)
Ce = d.wasmMemory;
else if (Ce = new WebAssembly.Memory({ initial: gc / 65536, maximum: 32768, shared: true }), !(Ce.buffer instanceof SharedArrayBuffer))
throw ee("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"), I && console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"), Error("bad memory");
Ce && (nn = Ce.buffer), gc = nn.byteLength, rs(nn);
var Fn, To = [], Js = [], ch = [], bc = [], zr = false, dh = false, yc = 0;
function Lr() {
return tt || yc > 0;
}
function sn() {
if (d.preRun)
for (typeof d.preRun == "function" && (d.preRun = [d.preRun]); d.preRun.length; )
qv(d.preRun.shift());
Sc(To);
}
function yu() {
zr = true, !$ && Sc(Js);
}
function ph() {
$ || ($e.terminateAllThreads(), dh = true);
}
function hh() {
if (!$) {
if (d.postRun)
for (typeof d.postRun == "function" && (d.postRun = [d.postRun]); d.postRun.length; )
vu(d.postRun.shift());
Sc(bc);
}
}
function qv(N) {
To.unshift(N);
}
function jv(N) {
Js.unshift(N);
}
function vu(N) {
bc.unshift(N);
}
var er = 0, vc = null, as = null;
function xu(N) {
er++, d.monitorRunDependencies && d.monitorRunDependencies(er);
}
function Kv(N) {
if (er--, d.monitorRunDependencies && d.monitorRunDependencies(er), er == 0 && (vc !== null && (clearInterval(vc), vc = null), as)) {
var F = as;
as = null, F();
}
}
d.preloadedImages = {}, d.preloadedAudios = {};
function $o(N) {
$ ? postMessage({ cmd: "onAbort", arg: N }) : d.onAbort && d.onAbort(N), N = "Aborted(" + N + ")", ee(N), ot = true, Jt = 1, N += ". Build with -s ASSERTIONS=1 for more info.";
var F = new WebAssembly.RuntimeError(N);
throw f(F), F;
}
var fh = "data:application/octet-stream;base64,";
function xc(N) {
return N.startsWith(fh);
}
function wc(N) {
return N.startsWith("file://");
}
var rn;
rn = "tfjs-backend-wasm-threaded-simd.wasm", xc(rn) || (rn = E(rn));
function kc(N) {
try {
if (N == rn && Ye)
return new Uint8Array(Ye);
if (D)
return D(N);
throw "both async and sync fetching of the wasm failed";
} catch (F) {
$o(F);
}
}
function _o() {
if (!Ye && (x || k)) {
if (typeof fetch == "function" && !wc(rn))
return fetch(rn, { credentials: "same-origin" }).then(function(N) {
if (!N.ok)
throw "failed to load wasm binary file at '" + rn + "'";
return N.arrayBuffer();
}).catch(function() {
return kc(rn);
});
if (A)
return new Promise(function(N, F) {
A(rn, function(B) {
N(new Uint8Array(B));
}, F);
});
}
return Promise.resolve().then(function() {
return kc(rn);
});
}
function mh() {
var N = { env: Oc, wasi_snapshot_preview1: Oc };
function F(ye, Te) {
var bt = ye.exports;
if (d.asm = bt, kh(d.asm.emscripten_tls_init), Fn = d.asm.__indirect_function_table, jv(d.asm.__wasm_call_ctors), ut = Te, !$) {
var us = $e.unusedWorkers.length;
$e.unusedWorkers.forEach(function(ls) {
$e.loadWasmModuleToWorker(ls, function() {
--us || Kv("wasm-instantiate");
});
});
}
}
$ || xu("wasm-instantiate");
function B(ye) {
F(ye.instance, ye.module);
}
function Q(ye) {
return _o().then(function(Te) {
return WebAssembly.instantiate(Te, N);
}).then(function(Te) {
return Te;
}).then(ye, function(Te) {
ee("failed to asynchronously prepare wasm: " + Te), $o(Te);
});
}
function ue() {
return !Ye && typeof WebAssembly.instantiateStreaming == "function" && !xc(rn) && !wc(rn) && typeof fetch == "function" ? fetch(rn, { credentials: "same-origin" }).then(function(ye) {
var Te = WebAssembly.instantiateStreaming(ye, N);
return Te.then(B, function(bt) {
return ee("wasm streaming compile failed: " + bt), ee("falling back to ArrayBuffer instantiation"), Q(B);
});
}) : Q(B);
}
if (d.instantiateWasm)
try {
var he = d.instantiateWasm(N, F);
return he;
} catch (ye) {
return ee("Module.instantiateWasm callback failed with error: " + ye), false;
}
return ue().catch(f), {};
}
var Xv, Yv, gh = {};
function Sc(N) {
for (; N.length > 0; ) {
var F = N.shift();
if (typeof F == "function") {
F(d);
continue;
}
var B = F.func;
typeof B == "number" ? F.arg === void 0 ? Eo(B)() : Eo(B)(F.arg) : B(F.arg === void 0 ? null : F.arg);
}
}
function Ao(N) {
var F = Uf(), B = N();
return Bc(F), B;
}
function lT(N) {
return N;
}
function Qv(N) {
var F = /\b_Z[\w\d_]+/g;
return N.replace(F, function(B) {
var Q = B;
return B === Q ? B : Q + " [" + B + "]";
});
}
function bh(N) {
l()[N >> 2] = 0;
var F = $e.pthreads[N];
delete $e.pthreads[N], F.worker.terminate(), Wf(N), $e.runningWorkers.splice($e.runningWorkers.indexOf(F.worker), 1), F.worker.pthread = void 0;
}
function yh(N) {
var F = $e.pthreads[N];
F.worker.postMessage({ cmd: "cancel" });
}
function Ic(N) {
var F = $e.pthreads[N];
if (F) {
l()[N >> 2] = 0;
var B = F.worker;
$e.returnWorkerToPool(B);
}
}
function Cc(N) {
ZT(N);
}
function vh(N) {
if (N instanceof Nu || N == "unwind")
return Jt;
v(1, N);
}
var $e = { unusedWorkers: [], runningWorkers: [], tlsInitFunctions: [], init: function() {
$ ? $e.initWorker() : $e.initMainThread();
}, initMainThread: function() {
for (var N = 8, F = 0; F < N; ++F)
$e.allocateUnusedWorker();
}, initWorker: function() {
tt = false;
}, pthreads: {}, setExitStatus: function(N) {
Jt = N;
}, terminateAllThreads: function() {
for (var N in $e.pthreads) {
var F = $e.pthreads[N];
F && F.worker && $e.returnWorkerToPool(F.worker);
}
for (var B = 0; B < $e.unusedWorkers.length; ++B) {
var Q = $e.unusedWorkers[B];
Q.terminate();
}
$e.unusedWorkers = [];
}, returnWorkerToPool: function(N) {
$e.runWithoutMainThreadQueuedCalls(function() {
delete $e.pthreads[N.pthread.threadInfoStruct], $e.unusedWorkers.push(N), $e.runningWorkers.splice($e.runningWorkers.indexOf(N), 1), Wf(N.pthread.threadInfoStruct), N.pthread = void 0;
});
}, runWithoutMainThreadQueuedCalls: function(N) {
l()[cx >> 2] = 0;
try {
N();
} finally {
l()[cx >> 2] = 1;
}
}, receiveObjectTransfer: function(N) {
}, threadInit: function() {
for (var N in $e.tlsInitFunctions)
$e.tlsInitFunctions[N]();
}, loadWasmModuleToWorker: function(N, F) {
N.onmessage = (B) => {
var Q = B.data, ue = Q.cmd;
if (N.pthread && ($e.currentProxiedOperationCallerThread = N.pthread.threadInfoStruct), Q.targetThread && Q.targetThread != Mc()) {
var he = $e.pthreads[Q.targetThread];
he ? he.worker.postMessage(Q, Q.transferList) : ee('Internal error! Worker sent a message "' + ue + '" to target pthread ' + Q.targetThread + ", but that thread no longer exists!"), $e.currentProxiedOperationCallerThread = void 0;
return;
}
ue === "processQueuedMainThreadWork" ? ax() : ue === "spawnThread" ? Tc(Q) : ue === "cleanupThread" ? Ic(Q.thread) : ue === "killThread" ? bh(Q.thread) : ue === "cancelThread" ? yh(Q.thread) : ue === "loaded" ? (N.loaded = true, F && F(N), N.runPthread && (N.runPthread(), delete N.runPthread)) : ue === "print" ? ne("Thread " + Q.threadId + ": " + Q.text) : ue === "printErr" ? ee("Thread " + Q.threadId + ": " + Q.text) : ue === "alert" ? alert("Thread " + Q.threadId + ": " + Q.text) : Q.target === "setimmediate" ? N.postMessage(Q) : ue === "onAbort" ? d.onAbort && d.onAbort(Q.arg) : ee("worker sent an unknown command " + ue), $e.currentProxiedOperationCallerThread = void 0;
}, N.onerror = (B) => {
var Q = "worker sent an error!";
throw ee(Q + " " + B.filename + ":" + B.lineno + ": " + B.message), B;
}, I && (N.on("message", function(B) {
N.onmessage({ data: B });
}), N.on("error", function(B) {
N.onerror(B);
}), N.on("detachedExit", function() {
})), N.postMessage({ cmd: "load", urlOrBlob: d.mainScriptUrlOrBlob || s, wasmMemory: Ce, wasmModule: ut });
}, allocateUnusedWorker: function() {
var N = E("tfjs-backend-wasm-threaded-simd.worker.js");
$e.unusedWorkers.push(new Worker(N));
}, getNewWorker: function() {
return $e.unusedWorkers.length == 0 && ($e.allocateUnusedWorker(), $e.loadWasmModuleToWorker($e.unusedWorkers[0])), $e.unusedWorkers.pop();
} };
function xh() {
var N = Mc(), F = l()[N + 44 >> 2], B = l()[N + 48 >> 2], Q = F - B;
lx(F, Q), Bc(F);
}
d.establishStackSpace = xh;
function Nc(N) {
if ($)
return Vr(1, 0, N);
try {
Cc(N);
} catch (F) {
vh(F);
}
}
var Mr = [];
function Eo(N) {
var F = Mr[N];
return F || (N >= Mr.length && (Mr.length = N + 1), Mr[N] = F = Fn.get(N)), F;
}
function wh(N, F) {
return Eo(N)(F);
}
d.invokeEntryPoint = wh;
function Zv() {
var N = new Error();
if (!N.stack) {
try {
throw new Error();
} catch (F) {
N = F;
}
if (!N.stack)
return "(no stack trace available)";
}
return N.stack.toString();
}
function kh(N, F, B) {
$e.tlsInitFunctions.push(N);
}
function Jv(N, F) {
Fn.set(N, F), Mr[N] = F;
}
var Br;
I ? Br = () => {
var N = process.hrtime();
return N[0] * 1e3 + N[1] / 1e6;
} : $ ? Br = () => performance.now() - d.__performance_now_clock_drift : Br = () => performance.now();
var Sh = true;
function Ih(N) {
return l()[rx() >> 2] = N, N;
}
function Ch(N, F) {
var B;
if (N === 0)
B = Date.now();
else if ((N === 1 || N === 4) && Sh)
B = Br();
else
return Ih(28), -1;
return l()[F >> 2] = B / 1e3 | 0, l()[F + 4 >> 2] = B % 1e3 * 1e3 * 1e3 | 0, 0;
}
function Nh(N, F) {
return Ch(N, F);
}
function Th(N) {
ox(N, !k, 1, !x), $e.threadInit();
}
function $h(N) {
$ ? postMessage({ cmd: "cleanupThread", thread: N }) : Ic(N);
}
function Tc(N) {
var F = $e.getNewWorker();
if (!F)
return 6;
$e.runningWorkers.push(F);
var B = $e.pthreads[N.pthread_ptr] = { worker: F, threadInfoStruct: N.pthread_ptr };
F.pthread = B;
var Q = { cmd: "run", start_routine: N.startRoutine, arg: N.arg, threadInfoStruct: N.pthread_ptr };
return F.runPthread = () => {
Q.time = performance.now(), F.postMessage(Q, N.transferList);
}, F.loaded && (F.runPthread(), delete F.runPthread), 0;
}
function _h(N, F, B, Q) {
if (typeof SharedArrayBuffer == "undefined")
return ee("Current environment does not support SharedArrayBuffer, pthreads are not available!"), 6;
var ue = [], he = 0;
if ($ && (ue.length === 0 || he))
return ix(687865856, N, F, B, Q);
if (he)
return he;
var ye = { startRoutine: B, pthread_ptr: N, arg: Q, transferList: ue };
return $ ? (ye.cmd = "spawnThread", postMessage(ye, ue), 0) : Tc(ye);
}
function Ah() {
return 2097152;
}
function Eh(N, F) {
if (N == F)
postMessage({ cmd: "processQueuedMainThreadWork" });
else if ($)
postMessage({ targetThread: N, cmd: "processThreadQueue" });
else {
var B = $e.pthreads[N], Q = B && B.worker;
if (!Q)
return;
Q.postMessage({ cmd: "processThreadQueue" });
}
return 1;
}
function Rh() {
$o("");
}
function Dh() {
I || k || te("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread");
}
function $c() {
return 2147483648;
}
function Fh(N, F, B) {
o().copyWithin(N, F, F + B);
}
function Oh() {
return I ? w$().cpus().length : navigator.hardwareConcurrency;
}
function Vr(N, F) {
var B = arguments.length - 2, Q = arguments;
return Ao(function() {
for (var ue = B, he = zo(ue * 8), ye = he >> 3, Te = 0; Te < B; Te++) {
var bt = Q[2 + Te];
p()[ye + Te] = bt;
}
return ux(N, ue, he, F);
});
}
var wu = [];
function Ph(N, F, B) {
wu.length = F;
for (var Q = B >> 3, ue = 0; ue < F; ue++)
wu[ue] = p()[Q + ue];
var he = N < 0, ye = he ? gh[-N - 1] : tf[N];
return ye.apply(null, wu);
}
function zh(N) {
try {
return Ce.grow(N - nn.byteLength + 65535 >>> 16), rs(Ce.buffer), 1;
} catch (F) {
}
}
function Lh(N) {
var F = o().length;
if (N = N >>> 0, N <= F)
return false;
var B = $c();
if (N > B)
return false;
for (var Q = 1; Q <= 4; Q *= 2) {
var ue = F * (1 + 0.2 / Q);
ue = Math.min(ue, N + 100663296);
var he = Math.min(B, No(Math.max(N, ue), 65536)), ye = zh(he);
if (ye)
return true;
}
return false;
}
var Me = { inEventHandler: 0, removeAllEventListeners: function() {
for (var N = Me.eventHandlers.length - 1; N >= 0; --N)
Me._removeHandler(N);
Me.eventHandlers = [], Me.deferredCalls = [];
}, registerRemoveEventListeners: function() {
Me.removeEventListenersRegistered || (ch.push(Me.removeAllEventListeners), Me.removeEventListenersRegistered = true);
}, deferredCalls: [], deferCall: function(N, F, B) {
function Q(ye, Te) {
if (ye.length != Te.length)
return false;
for (var bt in ye)
if (ye[bt] != Te[bt])
return false;
return true;
}
for (var ue in Me.deferredCalls) {
var he = Me.deferredCalls[ue];
if (he.targetFunction == N && Q(he.argsList, B))
return;
}
Me.deferredCalls.push({ targetFunction: N, precedence: F, argsList: B }), Me.deferredCalls.sort(function(ye, Te) {
return ye.precedence < Te.precedence;
});
}, removeDeferredCalls: function(N) {
for (var F = 0; F < Me.deferredCalls.length; ++F)
Me.deferredCalls[F].targetFunction == N && (Me.deferredCalls.splice(F, 1), --F);
}, canPerformEventHandlerRequests: function() {
return Me.inEventHandler && Me.currentEventHandler.allowsDeferredCalls;
}, runDeferredCalls: function() {
if (!!Me.canPerformEventHandlerRequests())
for (var N = 0; N < Me.deferredCalls.length; ++N) {
var F = Me.deferredCalls[N];
Me.deferredCalls.splice(N, 1), --N, F.targetFunction.apply(null, F.argsList);
}
}, eventHandlers: [], removeAllHandlersOnTarget: function(N, F) {
for (var B = 0; B < Me.eventHandlers.length; ++B)
Me.eventHandlers[B].target == N && (!F || F == Me.eventHandlers[B].eventTypeString) && Me._removeHandler(B--);
}, _removeHandler: function(N) {
var F = Me.eventHandlers[N];
F.target.removeEventListener(F.eventTypeString, F.eventListenerFunc, F.useCapture), Me.eventHandlers.splice(N, 1);
}, registerOrRemoveHandler: function(N) {
var F = function(ue) {
++Me.inEventHandler, Me.currentEventHandler = N, Me.runDeferredCalls(), N.handlerFunc(ue), Me.runDeferredCalls(), --Me.inEventHandler;
};
if (N.callbackfunc)
N.eventListenerFunc = F, N.target.addEventListener(N.eventTypeString, F, N.useCapture), Me.eventHandlers.push(N), Me.registerRemoveEventListeners();
else
for (var B = 0; B < Me.eventHandlers.length; ++B)
Me.eventHandlers[B].target == N.target && Me.eventHandlers[B].eventTypeString == N.eventTypeString && Me._removeHandler(B--);
}, queueEventHandlerOnThread_iiii: function(N, F, B, Q, ue) {
Ao(function() {
var he = zo(12);
l()[he >> 2] = B, l()[he + 4 >> 2] = Q, l()[he + 8 >> 2] = ue, Vf(N, 637534208, F, Q, he);
});
}, getTargetThreadForEventCallback: function(N) {
switch (N) {
case 1:
return 0;
case 2:
return $e.currentProxiedOperationCallerThread;
default:
return N;
}
}, getNodeNameForTarget: function(N) {
return N ? N == window ? "#window" : N == screen ? "#screen" : N && N.nodeName ? N.nodeName : "" : "";
}, fullscreenEnabled: function() {
return document.fullscreenEnabled || document.webkitFullscreenEnabled;
} };
function Mh(N) {
var F = Co(N) + 1, B = Bf(F);
return Ls(N, B, F), B;
}
function Bh(N, F, B, Q) {
Ao(function() {
var ue = zo(12), he = 0;
F && (he = Mh(F)), l()[ue >> 2] = he, l()[ue + 4 >> 2] = B, l()[ue + 8 >> 2] = Q, Vf(N, 657457152, 0, he, ue);
});
}
function Vh(N, F, B, Q) {
F = F ? tn(F) : "", Bh(N, F, B, Q);
}
function Wh(N) {
return N > 2 ? tn(N) : N;
}
var Uh = [0, typeof document != "undefined" ? document : 0, typeof window != "undefined" ? window : 0];
function Gh(N) {
N = Wh(N);
var F = Uh[N] || (typeof document != "undefined" ? document.querySelector(N) : void 0);
return F;
}
function ku(N) {
return Gh(N);
}
function _c(N, F, B) {
var Q = ku(N);
if (!Q)
return -4;
if (Q.canvasSharedPtr && (l()[Q.canvasSharedPtr >> 2] = F, l()[Q.canvasSharedPtr + 4 >> 2] = B), Q.offscreenCanvas || !Q.controlTransferredOffscreen) {
Q.offscreenCanvas && (Q = Q.offscreenCanvas);
var ue = false;
if (Q.GLctxObject && Q.GLctxObject.GLctx) {
var he = Q.GLctxObject.GLctx.getParameter(2978);
ue = he[0] === 0 && he[1] === 0 && he[2] === Q.width && he[3] === Q.height;
}
Q.width = F, Q.height = B, ue && Q.GLctxObject.GLctx.viewport(0, 0, F, B);
} else if (Q.canvasSharedPtr) {
var ye = l()[Q.canvasSharedPtr + 8 >> 2];
return Vh(ye, N, F, B), 1;
} else
return -4;
return 0;
}
function Ac(N, F, B) {
return $ ? Vr(2, 1, N, F, B) : _c(N, F, B);
}
function Hh(N, F, B) {
var Q = ku(N);
return Q ? _c(N, F, B) : Ac(N, F, B);
}
function qh() {
throw "unwind";
}
function jh(N) {
var F = N.getExtension("ANGLE_instanced_arrays");
if (F)
return N.vertexAttribDivisor = function(B, Q) {
F.vertexAttribDivisorANGLE(B, Q);
}, N.drawArraysInstanced = function(B, Q, ue, he) {
F.drawArraysInstancedANGLE(B, Q, ue, he);
}, N.drawElementsInstanced = function(B, Q, ue, he, ye) {
F.drawElementsInstancedANGLE(B, Q, ue, he, ye);
}, 1;
}
function Kh(N) {
var F = N.getExtension("OES_vertex_array_object");
if (F)
return N.createVertexArray = function() {
return F.createVertexArrayOES();
}, N.deleteVertexArray = function(B) {
F.deleteVertexArrayOES(B);
}, N.bindVertexArray = function(B) {
F.bindVertexArrayOES(B);
}, N.isVertexArray = function(B) {
return F.isVertexArrayOES(B);
}, 1;
}
function Xh(N) {
var F = N.getExtension("WEBGL_draw_buffers");
if (F)
return N.drawBuffers = function(B, Q) {
F.drawBuffersWEBGL(B, Q);
}, 1;
}
function Yh(N) {
return !!(N.multiDrawWebgl = N.getExtension("WEBGL_multi_draw"));
}
var gt = { counter: 1, buffers: [], programs: [], framebuffers: [], renderbuffers: [], textures: [], shaders: [], vaos: [], contexts: {}, offscreenCanvases: {}, queries: [], stringCache: {}, unpackAlignment: 4, recordError: function(F) {
gt.lastError || (gt.lastError = F);
}, getNewId: function(N) {
for (var F = gt.counter++, B = N.length; B < F; B++)
N[B] = null;
return F;
}, getSource: function(N, F, B, Q) {
for (var ue = "", he = 0; he < F; ++he) {
var ye = Q ? l()[Q + he * 4 >> 2] : -1;
ue += tn(l()[B + he * 4 >> 2], ye < 0 ? void 0 : ye);
}
return ue;
}, createContext: function(N, F) {
N.getContextSafariWebGL2Fixed || (N.getContextSafariWebGL2Fixed = N.getContext, N.getContext = function(ue, he) {
var ye = N.getContextSafariWebGL2Fixed(ue, he);
return ue == "webgl" == ye instanceof WebGLRenderingContext ? ye : null;
});
var B = N.getContext("webgl", F);
if (!B)
return 0;
var Q = gt.registerContext(B, F);
return Q;
}, registerContext: function(N, F) {
var B = Bf(8);
l()[B + 4 >> 2] = Mc();
var Q = { handle: B, attributes: F, version: F.majorVersion, GLctx: N };
return N.canvas && (N.canvas.GLctxObject = Q), gt.contexts[B] = Q, (typeof F.enableExtensionsByDefault == "undefined" || F.enableExtensionsByDefault) && gt.initExtensions(Q), B;
}, makeContextCurrent: function(N) {
return gt.currentContext = gt.contexts[N], d.ctx = Fc = gt.currentContext && gt.currentContext.GLctx, !(N && !Fc);
}, getContext: function(N) {
return gt.contexts[N];
}, deleteContext: function(N) {
gt.currentContext === gt.contexts[N] && (gt.currentContext = null), typeof Me == "object" && Me.removeAllHandlersOnTarget(gt.contexts[N].GLctx.canvas), gt.contexts[N] && gt.contexts[N].GLctx.canvas && (gt.contexts[N].GLctx.canvas.GLctxObject = void 0), sx(gt.contexts[N].handle), gt.contexts[N] = null;
}, initExtensions: function(N) {
if (N || (N = gt.currentContext), !N.initExtensionsDone) {
N.initExtensionsDone = true;
var F = N.GLctx;
jh(F), Kh(F), Xh(F), F.disjointTimerQueryExt = F.getExtension("EXT_disjoint_timer_query"), Yh(F);
var B = F.getSupportedExtensions() || [];
B.forEach(function(Q) {
!Q.includes("lose_context") && !Q.includes("debug") && F.getExtension(Q);
});
}
} }, Qh = ["default", "low-power", "high-performance"];
function Zh(N, F) {
var B = F >> 2, Q = l()[B + 6], ue = { alpha: !!l()[B + 0], depth: !!l()[B + 1], stencil: !!l()[B + 2], antialias: !!l()[B + 3], premultipliedAlpha: !!l()[B + 4], preserveDrawingBuffer: !!l()[B + 5], powerPreference: Qh[Q], failIfMajorPerformanceCaveat: !!l()[B + 7], majorVersion: l()[B + 8], minorVersion: l()[B + 9], enableExtensionsByDefault: l()[B + 10], explicitSwapControl: l()[B + 11], proxyContextToMainThread: l()[B + 12], renderViaOffscreenBackBuffer: l()[B + 13] }, he = ku(N);
if (!he || ue.explicitSwapControl)
return 0;
var ye = gt.createContext(he, ue);
return ye;
}
function Jh(N, F) {
return Zh(N, F);
}
var Ro = { mappings: {}, buffers: [null, [], []], printChar: function(N, F) {
var B = Ro.buffers[N];
F === 0 || F === 10 ? ((N === 1 ? ne : ee)(Dn(B, 0)), B.length = 0) : B.push(F);
}, varargs: void 0, get: function() {
Ro.varargs += 4;
var N = l()[Ro.varargs - 4 >> 2];
return N;
}, getStr: function(N) {
var F = tn(N);
return F;
}, get64: function(N, F) {
return N;
} };
function Ec(N) {
return $ ? Vr(3, 1, N) : 0;
}
function Rc(N, F, B, Q, ue) {
if ($)
return Vr(4, 1, N, F, B, Q, ue);
}
function Dc(N, F, B, Q) {
if ($)
return Vr(5, 1, N, F, B, Q);
for (var ue = 0, he = 0; he < B; he++) {
var ye = l()[F >> 2], Te = l()[F + 4 >> 2];
F += 8;
for (var bt = 0; bt < Te; bt++)
Ro.printChar(N, o()[ye + bt]);
ue += Te;
}
return l()[Q >> 2] = ue, 0;
}
function ef(N) {
Re(N);
}
$e.init();
var Fc, tf = [null, Nc, Ac, Ec, Rc, Dc], ex = false, Oc = { __clock_gettime: Nh, __emscripten_init_main_thread_js: Th, __emscripten_thread_cleanup: $h, __pthread_create_js: _h, _emscripten_default_pthread_stack_size: Ah, _emscripten_notify_thread_queue: Eh, abort: Rh, emscripten_check_blocking_allowed: Dh, emscripten_get_heap_max: $c, emscripten_get_now: Br, emscripten_memcpy_big: Fh, emscripten_num_logical_cores: Oh, emscripten_receive_on_main_thread_js: Ph, emscripten_resize_heap: Lh, emscripten_set_canvas_element_size: Hh, emscripten_unwind_to_js_event_loop: qh, emscripten_webgl_create_context: Jh, exit: Cc, fd_close: Ec, fd_seek: Rc, fd_write: Dc, memory: Ce || d.wasmMemory, setTempRet0: ef }, tx = mh(), nf = d.___wasm_call_ctors = function() {
return (nf = d.___wasm_call_ctors = d.asm.__wasm_call_ctors).apply(null, arguments);
}, sf = d._init = function() {
return (sf = d._init = d.asm.init).apply(null, arguments);
}, rf = d._init_with_threads_count = function() {
return (rf = d._init_with_threads_count = d.asm.init_with_threads_count).apply(null, arguments);
}, af = d._get_threads_count = function() {
return (af = d._get_threads_count = d.asm.get_threads_count).apply(null, arguments);
}, of = d._register_tensor = function() {
return (of = d._register_tensor = d.asm.register_tensor).apply(null, arguments);
}, uf = d._dispose_data = function() {
return (uf = d._dispose_data = d.asm.dispose_data).apply(null, arguments);
}, lf = d._dispose = function() {
return (lf = d._dispose = d.asm.dispose).apply(null, arguments);
}, cf = d._Abs = function() {
return (cf = d._Abs = d.asm.Abs).apply(null, arguments);
}, df = d._Add = function() {
return (df = d._Add = d.asm.Add).apply(null, arguments);
}, pf = d._AddN = function() {
return (pf = d._AddN = d.asm.AddN).apply(null, arguments);
}, hf = d._All = function() {
return (hf = d._All = d.asm.All).apply(null, arguments);
}, ff = d._Any = function() {
return (ff = d._Any = d.asm.Any).apply(null, arguments);
}, mf = d._ArgMax = function() {
return (mf = d._ArgMax = d.asm.ArgMax).apply(null, arguments);
}, gf = d._AvgPool = function() {
return (gf = d._AvgPool = d.asm.AvgPool).apply(null, arguments);
}, bf = d._BatchMatMul = function() {
return (bf = d._BatchMatMul = d.asm.BatchMatMul).apply(null, arguments);
}, yf = d._Ceil = function() {
return (yf = d._Ceil = d.asm.Ceil).apply(null, arguments);
}, vf = d._ClipByValue = function() {
return (vf = d._ClipByValue = d.asm.ClipByValue).apply(null, arguments);
}, xf = d._Conv2D = function() {
return (xf = d._Conv2D = d.asm.Conv2D).apply(null, arguments);
}, wf = d._Conv2DBackpropInput = function() {
return (wf = d._Conv2DBackpropInput = d.asm.Conv2DBackpropInput).apply(null, arguments);
}, kf = d._Cos = function() {
return (kf = d._Cos = d.asm.Cos).apply(null, arguments);
}, Sf = d._Cosh = function() {
return (Sf = d._Cosh = d.asm.Cosh).apply(null, arguments);
}, If = d._CropAndResize = function() {
return (If = d._CropAndResize = d.asm.CropAndResize).apply(null, arguments);
}, Cf = d._Cumprod = function() {
return (Cf = d._Cumprod = d.asm.Cumprod).apply(null, arguments);
}, Nf = d._Cumsum = function() {
return (Nf = d._Cumsum = d.asm.Cumsum).apply(null, arguments);
}, Tf = d._DepthToSpace = function() {
return (Tf = d._DepthToSpace = d.asm.DepthToSpace).apply(null, arguments);
}, $f = d._DepthwiseConv2dNative = function() {
return ($f = d._DepthwiseConv2dNative = d.asm.DepthwiseConv2dNative).apply(null, arguments);
}, _f = d._Elu = function() {
return (_f = d._Elu = d.asm.Elu).apply(null, arguments);
}, Af = d._Equal = function() {
return (Af = d._Equal = d.asm.Equal).apply(null, arguments);
}, Ef = d._Exp = function() {
return (Ef = d._Exp = d.asm.Exp).apply(null, arguments);
}, Rf = d._FlipLeftRight = function() {
return (Rf = d._FlipLeftRight = d.asm.FlipLeftRight).apply(null, arguments);
}, Df = d._Floor = function() {
return (Df = d._Floor = d.asm.Floor).apply(null, arguments);
}, Ff = d._FloorDiv = function() {
return (Ff = d._FloorDiv = d.asm.FloorDiv).apply(null, arguments);
}, Of = d._FusedBatchNorm = function() {
return (Of = d._FusedBatchNorm = d.asm.FusedBatchNorm).apply(null, arguments);
}, Pc = d._FusedConv2D = function() {
return (Pc = d._FusedConv2D = d.asm.FusedConv2D).apply(null, arguments);
}, zc = d._FusedDepthwiseConv2D = function() {
return (zc = d._FusedDepthwiseConv2D = d.asm.FusedDepthwiseConv2D).apply(null, arguments);
}, Su = d._Gather = function() {
return (Su = d._Gather = d.asm.Gather).apply(null, arguments);
}, Pf = d._GatherNd = function() {
return (Pf = d._GatherNd = d.asm.GatherNd).apply(null, arguments);
}, zf = d._Greater = function() {
return (zf = d._Greater = d.asm.Greater).apply(null, arguments);
}, Do = d._GreaterEqual = function() {
return (Do = d._GreaterEqual = d.asm.GreaterEqual).apply(null, arguments);
}, Iu = d._LeakyRelu = function() {
return (Iu = d._LeakyRelu = d.asm.LeakyRelu).apply(null, arguments);
}, Cu = d._Less = function() {
return (Cu = d._Less = d.asm.Less).apply(null, arguments);
}, nx = d._LessEqual = function() {
return (nx = d._LessEqual = d.asm.LessEqual).apply(null, arguments);
}, Fo = d._Log = function() {
return (Fo = d._Log = d.asm.Log).apply(null, arguments);
}, Oo = d._LogicalAnd = function() {
return (Oo = d._LogicalAnd = d.asm.LogicalAnd).apply(null, arguments);
}, Lf = d._LogicalNot = function() {
return (Lf = d._LogicalNot = d.asm.LogicalNot).apply(null, arguments);
}, H = d._LogicalOr = function() {
return (H = d._LogicalOr = d.asm.LogicalOr).apply(null, arguments);
}, J = d._LogicalXor = function() {
return (J = d._LogicalXor = d.asm.LogicalXor).apply(null, arguments);
}, ce = d._Max = function() {
return (ce = d._Max = d.asm.Max).apply(null, arguments);
}, Se = d._MaxPool = function() {
return (Se = d._MaxPool = d.asm.MaxPool).apply(null, arguments);
}, Qe = d._Maximum = function() {
return (Qe = d._Maximum = d.asm.Maximum).apply(null, arguments);
}, Ze = d._Mean = function() {
return (Ze = d._Mean = d.asm.Mean).apply(null, arguments);
}, Be = d._Min = function() {
return (Be = d._Min = d.asm.Min).apply(null, arguments);
}, ze = d._Minimum = function() {
return (ze = d._Minimum = d.asm.Minimum).apply(null, arguments);
}, Tt = d._MirrorPad = function() {
return (Tt = d._MirrorPad = d.asm.MirrorPad).apply(null, arguments);
}, os = d._Multiply = function() {
return (os = d._Multiply = d.asm.Multiply).apply(null, arguments);
}, is = d._Neg = function() {
return (is = d._Neg = d.asm.Neg).apply(null, arguments);
}, Po = d._NonMaxSuppressionV3 = function() {
return (Po = d._NonMaxSuppressionV3 = d.asm.NonMaxSuppressionV3).apply(null, arguments);
}, Wr = d._NonMaxSuppressionV4 = function() {
return (Wr = d._NonMaxSuppressionV4 = d.asm.NonMaxSuppressionV4).apply(null, arguments);
}, Mf = d._NonMaxSuppressionV5 = function() {
return (Mf = d._NonMaxSuppressionV5 = d.asm.NonMaxSuppressionV5).apply(null, arguments);
}, an = d._NotEqual = function() {
return (an = d._NotEqual = d.asm.NotEqual).apply(null, arguments);
}, tr = d._OneHot = function() {
return (tr = d._OneHot = d.asm.OneHot).apply(null, arguments);
}, Lc = d._PadV2 = function() {
return (Lc = d._PadV2 = d.asm.PadV2).apply(null, arguments);
}, cT = d._Pow = function() {
return (cT = d._Pow = d.asm.Pow).apply(null, arguments);
}, dT = d._Prelu = function() {
return (dT = d._Prelu = d.asm.Prelu).apply(null, arguments);
}, pT = d._Prod = function() {
return (pT = d._Prod = d.asm.Prod).apply(null, arguments);
}, hT = d._RealDiv = function() {
return (hT = d._RealDiv = d.asm.RealDiv).apply(null, arguments);
}, fT = d._Relu = function() {
return (fT = d._Relu = d.asm.Relu).apply(null, arguments);
}, mT = d._Relu6 = function() {
return (mT = d._Relu6 = d.asm.Relu6).apply(null, arguments);
}, gT = d._ResizeBilinear = function() {
return (gT = d._ResizeBilinear = d.asm.ResizeBilinear).apply(null, arguments);
}, bT = d._Reverse = function() {
return (bT = d._Reverse = d.asm.Reverse).apply(null, arguments);
}, yT = d._RotateWithOffset = function() {
return (yT = d._RotateWithOffset = d.asm.RotateWithOffset).apply(null, arguments);
}, vT = d._Round = function() {
return (vT = d._Round = d.asm.Round).apply(null, arguments);
}, xT = d._Rsqrt = function() {
return (xT = d._Rsqrt = d.asm.Rsqrt).apply(null, arguments);
}, wT = d._ScatterNd = function() {
return (wT = d._ScatterNd = d.asm.ScatterNd).apply(null, arguments);
}, kT = d._SelectV2 = function() {
return (kT = d._SelectV2 = d.asm.SelectV2).apply(null, arguments);
}, ST = d._Sigmoid = function() {
return (ST = d._Sigmoid = d.asm.Sigmoid).apply(null, arguments);
}, IT = d._Sin = function() {
return (IT = d._Sin = d.asm.Sin).apply(null, arguments);
}, CT = d._Softmax = function() {
return (CT = d._Softmax = d.asm.Softmax).apply(null, arguments);
}, NT = d._SparseFillEmptyRows = function() {
return (NT = d._SparseFillEmptyRows = d.asm.SparseFillEmptyRows).apply(null, arguments);
}, TT = d._SparseReshape = function() {
return (TT = d._SparseReshape = d.asm.SparseReshape).apply(null, arguments);
}, $T = d._SparseSegmentReduction = function() {
return ($T = d._SparseSegmentReduction = d.asm.SparseSegmentReduction).apply(null, arguments);
}, _T = d._Sqrt = function() {
return (_T = d._Sqrt = d.asm.Sqrt).apply(null, arguments);
}, AT = d._Square = function() {
return (AT = d._Square = d.asm.Square).apply(null, arguments);
}, ET = d._SquaredDifference = function() {
return (ET = d._SquaredDifference = d.asm.SquaredDifference).apply(null, arguments);
}, RT = d._Step = function() {
return (RT = d._Step = d.asm.Step).apply(null, arguments);
}, DT = d._StridedSlice = function() {
return (DT = d._StridedSlice = d.asm.StridedSlice).apply(null, arguments);
}, FT = d._Sub = function() {
return (FT = d._Sub = d.asm.Sub).apply(null, arguments);
}, OT = d._Sum = function() {
return (OT = d._Sum = d.asm.Sum).apply(null, arguments);
}, PT = d._Tan = function() {
return (PT = d._Tan = d.asm.Tan).apply(null, arguments);
}, zT = d._Tanh = function() {
return (zT = d._Tanh = d.asm.Tanh).apply(null, arguments);
}, LT = d._Tile = function() {
return (LT = d._Tile = d.asm.Tile).apply(null, arguments);
}, MT = d._TopK = function() {
return (MT = d._TopK = d.asm.TopK).apply(null, arguments);
}, BT = d._Transform = function() {
return (BT = d._Transform = d.asm.Transform).apply(null, arguments);
}, VT = d._Transpose = function() {
return (VT = d._Transpose = d.asm.Transpose).apply(null, arguments);
}, WT = d.__FusedMatMul = function() {
return (WT = d.__FusedMatMul = d.asm._FusedMatMul).apply(null, arguments);
}, Bf = d._malloc = function() {
return (Bf = d._malloc = d.asm.malloc).apply(null, arguments);
}, sx = d._free = function() {
return (sx = d._free = d.asm.free).apply(null, arguments);
}, UT = d._emscripten_tls_init = function() {
return (UT = d._emscripten_tls_init = d.asm.emscripten_tls_init).apply(null, arguments);
}, rx = d.___errno_location = function() {
return (rx = d.___errno_location = d.asm.__errno_location).apply(null, arguments);
}, Mc = d._pthread_self = function() {
return (Mc = d._pthread_self = d.asm.pthread_self).apply(null, arguments);
}, ax = d._emscripten_main_thread_process_queued_calls = function() {
return (ax = d._emscripten_main_thread_process_queued_calls = d.asm.emscripten_main_thread_process_queued_calls).apply(null, arguments);
}, GT = d.__emscripten_thread_crashed = function() {
return (GT = d.__emscripten_thread_crashed = d.asm._emscripten_thread_crashed).apply(null, arguments);
}, ox = d.__emscripten_thread_init = function() {
return (ox = d.__emscripten_thread_init = d.asm._emscripten_thread_init).apply(null, arguments);
}, HT = d._emscripten_current_thread_process_queued_calls = function() {
return (HT = d._emscripten_current_thread_process_queued_calls = d.asm.emscripten_current_thread_process_queued_calls).apply(null, arguments);
}, qT = d._emscripten_main_browser_thread_id = function() {
return (qT = d._emscripten_main_browser_thread_id = d.asm.emscripten_main_browser_thread_id).apply(null, arguments);
}, jT = d._emscripten_sync_run_in_main_thread_2 = function() {
return (jT = d._emscripten_sync_run_in_main_thread_2 = d.asm.emscripten_sync_run_in_main_thread_2).apply(null, arguments);
}, ix = d._emscripten_sync_run_in_main_thread_4 = function() {
return (ix = d._emscripten_sync_run_in_main_thread_4 = d.asm.emscripten_sync_run_in_main_thread_4).apply(null, arguments);
}, ux = d._emscripten_run_in_main_runtime_thread_js = function() {
return (ux = d._emscripten_run_in_main_runtime_thread_js = d.asm.emscripten_run_in_main_runtime_thread_js).apply(null, arguments);
}, Vf = d._emscripten_dispatch_to_thread_ = function() {
return (Vf = d._emscripten_dispatch_to_thread_ = d.asm.emscripten_dispatch_to_thread_).apply(null, arguments);
}, Wf = d.__emscripten_thread_free_data = function() {
return (Wf = d.__emscripten_thread_free_data = d.asm._emscripten_thread_free_data).apply(null, arguments);
}, KT = d.__emscripten_thread_exit = function() {
return (KT = d.__emscripten_thread_exit = d.asm._emscripten_thread_exit).apply(null, arguments);
}, XT = d._memalign = function() {
return (XT = d._memalign = d.asm.memalign).apply(null, arguments);
}, lx = d._emscripten_stack_set_limits = function() {
return (lx = d._emscripten_stack_set_limits = d.asm.emscripten_stack_set_limits).apply(null, arguments);
}, Uf = d.stackSave = function() {
return (Uf = d.stackSave = d.asm.stackSave).apply(null, arguments);
}, Bc = d.stackRestore = function() {
return (Bc = d.stackRestore = d.asm.stackRestore).apply(null, arguments);
}, zo = d.stackAlloc = function() {
return (zo = d.stackAlloc = d.asm.stackAlloc).apply(null, arguments);
}, YT = d.dynCall_iijjiiii = function() {
return (YT = d.dynCall_iijjiiii = d.asm.dynCall_iijjiiii).apply(null, arguments);
}, QT = d.dynCall_jiji = function() {
return (QT = d.dynCall_jiji = d.asm.dynCall_jiji).apply(null, arguments);
}, cx = d.__emscripten_allow_main_runtime_queued_calls = 21664;
d.cwrap = en, d.keepRuntimeAlive = Lr, d.PThread = $e, d.PThread = $e, d.wasmMemory = Ce, d.ExitStatus = Nu;
var Vc;
function Nu(N) {
this.name = "ExitStatus", this.message = "Program terminated with exit(" + N + ")", this.status = N;
}
as = function N() {
Vc || Gf(), Vc || (as = N);
};
function Gf(N) {
if (N = N || b, er > 0)
return;
if ($) {
h(d), yu(), postMessage({ cmd: "loaded" });
return;
}
if (sn(), er > 0)
return;
function F() {
Vc || (Vc = true, d.calledRun = true, !ot && (yu(), h(d), d.onRuntimeInitialized && d.onRuntimeInitialized(), hh()));
}
d.setStatus ? (d.setStatus("Running..."), setTimeout(function() {
setTimeout(function() {
d.setStatus("");
}, 1), F();
}, 1)) : F();
}
d.run = Gf;
function ZT(N, F) {
if (Jt = N, !F && $)
throw Nc(N), "unwind";
Lr() || ph(), JT(N);
}
function JT(N) {
Jt = N, Lr() || ($e.terminateAllThreads(), d.onExit && d.onExit(N), ot = true), v(N, new Nu(N));
}
if (d.preInit)
for (typeof d.preInit == "function" && (d.preInit = [d.preInit]); d.preInit.length > 0; )
d.preInit.pop()();
Gf();
var Wc;
m && (Wc = { uncaughtException: process.listeners("uncaughtException").filter(function(N) {
return !m.uncaughtException.indexOf(N) > -1;
}), unhandledRejection: process.listeners("unhandledRejection").filter(function(N) {
return !m.unhandledRejection.indexOf(N) > -1;
}) });
var Uc;
if (typeof WasmBackendModule != "undefined")
Uc = WasmBackendModule;
else if (typeof r != "undefined")
Uc = r;
else
throw new Error("Could not find wasm module in post.js");
if (Wc) {
var e$ = Uc._dispose;
Uc._dispose = function() {
e$(), Wc.uncaughtException.forEach(function(N) {
process.removeListener("uncaughtException", N);
}), Wc.unhandledRejection.forEach(function(N) {
process.removeListener("unhandledRejection", N);
});
};
}
return r.ready;
};
})();
typeof e == "object" && typeof t == "object" ? t.exports = n : typeof define == "function" && define.amd ? define([], function() {
return n;
}) : typeof e == "object" && (e.WasmBackendModuleThreadedSimd = n);
} });
var S$ = zt({ "src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js"(e, t) {
var n = (() => {
var s = typeof document != "undefined" && document.currentScript ? document.currentScript.src : void 0;
return typeof __filename != "undefined" && (s = s || __filename), function(r) {
r = r || {};
var a = typeof r != "undefined" ? r : {}, o, i;
a.ready = new Promise(function(H, J) {
o = H, i = J;
});
var u;
typeof process != "undefined" && process.listeners && (u = { uncaughtException: process.listeners("uncaughtException"), unhandledRejection: process.listeners("unhandledRejection") });
var l = Object.assign({}, a), c = [], p = "./this.program", d = (H, J) => {
throw J;
}, h = typeof window == "object", f = typeof importScripts == "function", m = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string", g = "";
function b(H) {
return a.locateFile ? a.locateFile(H, g) : g + H;
}
var y, v, x, k;
function I(H) {
if (H instanceof Iu)
return;
A("exiting due to exception: " + H);
}
var $, R, E;
m ? (f ? g = bd().dirname(g) + "/" : g = __dirname + "/", E = () => {
R || ($ = pg(), R = bd());
}, y = function(J, ce) {
return E(), J = R.normalize(J), $.readFileSync(J, ce ? void 0 : "utf8");
}, x = (H) => {
var J = y(H, true);
return J.buffer || (J = new Uint8Array(J)), J;
}, v = (H, J, ce) => {
E(), H = R.normalize(H), $.readFile(H, function(Se, Qe) {
Se ? ce(Se) : J(Qe.buffer);
});
}, process.argv.length > 1 && (p = process.argv[1].replace(/\\/g, "/")), c = process.argv.slice(2), process.on("uncaughtException", function(H) {
if (!(H instanceof Iu))
throw H;
}), process.on("unhandledRejection", function(H) {
throw H;
}), d = (H, J) => {
if (bu())
throw process.exitCode = H, J;
I(J), process.exit(H);
}, a.inspect = function() {
return "[Emscripten Module object]";
}) : (h || f) && (f ? g = self.location.href : typeof document != "undefined" && document.currentScript && (g = document.currentScript.src), s && (g = s), g.indexOf("blob:") !== 0 ? g = g.substr(0, g.replace(/[?#].*/, "").lastIndexOf("/") + 1) : g = "", y = (H) => {
var J = new XMLHttpRequest();
return J.open("GET", H, false), J.send(null), J.responseText;
}, f && (x = (H) => {
var J = new XMLHttpRequest();
return J.open("GET", H, false), J.responseType = "arraybuffer", J.send(null), new Uint8Array(J.response);
}), v = (H, J, ce) => {
var Se = new XMLHttpRequest();
Se.open("GET", H, true), Se.responseType = "arraybuffer", Se.onload = () => {
if (Se.status == 200 || Se.status == 0 && Se.response) {
J(Se.response);
return;
}
ce();
}, Se.onerror = ce, Se.send(null);
}, k = (H) => document.title = H);
var P = a.print || console.log.bind(console), A = a.printErr || console.warn.bind(console);
Object.assign(a, l), l = null, a.arguments && (c = a.arguments), a.thisProgram && (p = a.thisProgram), a.quit && (d = a.quit);
var D = 4;
function T(H) {
T.shown || (T.shown = {}), T.shown[H] || (T.shown[H] = 1, A(H));
}
function L(H, J) {
if (typeof WebAssembly.Function == "function") {
for (var ce = { i: "i32", j: "i64", f: "f32", d: "f64" }, Se = { parameters: [], results: J[0] == "v" ? [] : [ce[J[0]]] }, Qe = 1; Qe < J.length; ++Qe)
Se.parameters.push(ce[J[Qe]]);
return new WebAssembly.Function(Se, H);
}
var Ze = [1, 0, 1, 96], Be = J.slice(0, 1), ze = J.slice(1), Tt = { i: 127, j: 126, f: 125, d: 124 };
Ze.push(ze.length);
for (var Qe = 0; Qe < ze.length; ++Qe)
Ze.push(Tt[ze[Qe]]);
Be == "v" ? Ze.push(0) : Ze = Ze.concat([1, Tt[Be]]), Ze[1] = Ze.length - 2;
var os = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0].concat(Ze, [2, 7, 1, 1, 101, 1, 102, 0, 0, 7, 5, 1, 1, 102, 0, 0])), is = new WebAssembly.Module(os), Po = new WebAssembly.Instance(is, { e: { f: H } }), Wr = Po.exports.f;
return Wr;
}
var W = [], j;
function Y() {
if (W.length)
return W.pop();
try {
Zs.grow(1);
} catch (H) {
throw H instanceof RangeError ? "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH." : H;
}
return Zs.length - 1;
}
function X(H, J) {
for (var ce = H; ce < H + J; ce++) {
var Se = xu(ce);
Se && j.set(Se, ce);
}
}
var Z = 0, ne = (H) => {
Z = H;
}, ee;
a.wasmBinary && (ee = a.wasmBinary);
var se = a.noExitRuntime || true;
typeof WebAssembly != "object" && zr("no native wasm support detected");
var te, ie = false, ae;
function de(H, J) {
H || zr(J);
}
function me(H) {
var J = a["_" + H];
return J;
}
function ke(H, J, ce, Se, Qe) {
var Ze = { string: function(an) {
var tr = 0;
if (an != null && an !== 0) {
var Lc = (an.length << 2) + 1;
tr = Su(Lc), tt(an, tr, Lc);
}
return tr;
}, array: function(an) {
var tr = Su(an.length);
return ot(an, tr), tr;
} };
function Be(an) {
return J === "string" ? Je(an) : J === "boolean" ? Boolean(an) : an;
}
var ze = me(H), Tt = [], os = 0;
if (Se)
for (var is = 0; is < Se.length; is++) {
var Po = Ze[ce[is]];
Po ? (os === 0 && (os = Pc()), Tt[is] = Po(Se[is])) : Tt[is] = Se[is];
}
var Wr = ze.apply(null, Tt);
function Mf(an) {
return os !== 0 && zc(os), Be(an);
}
return Wr = Mf(Wr), Wr;
}
function Ie(H, J, ce, Se) {
ce = ce || [];
var Qe = ce.every(function(Be) {
return Be === "number";
}), Ze = J !== "string";
return Ze && Qe && !Se ? me(H) : function() {
return ke(H, J, ce, arguments, Se);
};
}
var Re = 1, Pe = typeof TextDecoder != "undefined" ? new TextDecoder("utf8") : void 0;
function Xe(H, J, ce) {
for (var Se = J + ce, Qe = J; H[Qe] && !(Qe >= Se); )
++Qe;
if (Qe - J > 16 && H.subarray && Pe)
return Pe.decode(H.subarray(J, Qe));
for (var Ze = ""; J < Qe; ) {
var Be = H[J++];
if (!(Be & 128)) {
Ze += String.fromCharCode(Be);
continue;
}
var ze = H[J++] & 63;
if ((Be & 224) == 192) {
Ze += String.fromCharCode((Be & 31) << 6 | ze);
continue;
}
var Tt = H[J++] & 63;
if ((Be & 240) == 224 ? Be = (Be & 15) << 12 | ze << 6 | Tt : Be = (Be & 7) << 18 | ze << 12 | Tt << 6 | H[J++] & 63, Be < 65536)
Ze += String.fromCharCode(Be);
else {
var os = Be - 65536;
Ze += String.fromCharCode(55296 | os >> 10, 56320 | os & 1023);
}
}
return Ze;
}
function Je(H, J) {
return H ? Xe(en, H, J) : "";
}
function Ye(H, J, ce, Se) {
if (!(Se > 0))
return 0;
for (var Qe = ce, Ze = ce + Se - 1, Be = 0; Be < H.length; ++Be) {
var ze = H.charCodeAt(Be);
if (ze >= 55296 && ze <= 57343) {
var Tt = H.charCodeAt(++Be);
ze = 65536 + ((ze & 1023) << 10) | Tt & 1023;
}
if (ze <= 127) {
if (ce >= Ze)
break;
J[ce++] = ze;
} else if (ze <= 2047) {
if (ce + 1 >= Ze)
break;
J[ce++] = 192 | ze >> 6, J[ce++] = 128 | ze & 63;
} else if (ze <= 65535) {
if (ce + 2 >= Ze)
break;
J[ce++] = 224 | ze >> 12, J[ce++] = 128 | ze >> 6 & 63, J[ce++] = 128 | ze & 63;
} else {
if (ce + 3 >= Ze)
break;
J[ce++] = 240 | ze >> 18, J[ce++] = 128 | ze >> 12 & 63, J[ce++] = 128 | ze >> 6 & 63, J[ce++] = 128 | ze & 63;
}
}
return J[ce] = 0, ce - Qe;
}
function tt(H, J, ce) {
return Ye(H, en, J, ce);
}
function Ce(H) {
for (var J = 0, ce = 0; ce < H.length; ++ce) {
var Se = H.charCodeAt(ce);
Se >= 55296 && Se <= 57343 && (Se = 65536 + ((Se & 1023) << 10) | H.charCodeAt(++ce) & 1023), Se <= 127 ? ++J : Se <= 2047 ? J += 2 : Se <= 65535 ? J += 3 : J += 4;
}
return J;
}
var ut = typeof TextDecoder != "undefined" ? new TextDecoder("utf-16le") : void 0;
function ot(H, J) {
Et.set(H, J);
}
function Jt(H, J, ce) {
for (var Se = 0; Se < H.length; ++Se)
Et[J++ >> 0] = H.charCodeAt(Se);
ce || (Et[J >> 0] = 0);
}
function Nt(H, J) {
return H % J > 0 && (H += J - H % J), H;
}
var In, Et, en, Cn, Nn, Yt, Dn, tn, zs;
function Ls(H) {
In = H, a.HEAP8 = Et = new Int8Array(H), a.HEAP16 = Cn = new Int16Array(H), a.HEAP32 = Yt = new Int32Array(H), a.HEAPU8 = en = new Uint8Array(H), a.HEAPU16 = Nn = new Uint16Array(H), a.HEAPU32 = Dn = new Uint32Array(H), a.HEAPF32 = tn = new Float32Array(H), a.HEAPF64 = zs = new Float64Array(H);
}
var Co = a.INITIAL_MEMORY || 16777216, Zs, Ms = [], gu = [], No = [], nn = false, cc = false, dc = 0;
function bu() {
return se || dc > 0;
}
function pc() {
if (a.preRun)
for (typeof a.preRun == "function" && (a.preRun = [a.preRun]); a.preRun.length; )
mc(a.preRun.shift());
vu(Ms);
}
function hc() {
nn = true, vu(gu);
}
function Hv() {
cc = true;
}
function fc() {
if (a.postRun)
for (typeof a.postRun == "function" && (a.postRun = [a.postRun]); a.postRun.length; )
gc(a.postRun.shift());
vu(No);
}
function mc(H) {
Ms.unshift(H);
}
function rs(H) {
gu.unshift(H);
}
function gc(H) {
No.unshift(H);
}
var Fn = 0, To = null, Js = null;
function ch(H) {
Fn++, a.monitorRunDependencies && a.monitorRunDependencies(Fn);
}
function bc(H) {
if (Fn--, a.monitorRunDependencies && a.monitorRunDependencies(Fn), Fn == 0 && (To !== null && (clearInterval(To), To = null), Js)) {
var J = Js;
Js = null, J();
}
}
a.preloadedImages = {}, a.preloadedAudios = {};
function zr(H) {
a.onAbort && a.onAbort(H), H = "Aborted(" + H + ")", A(H), ie = true, ae = 1, H += ". Build with -s ASSERTIONS=1 for more info.";
var J = new WebAssembly.RuntimeError(H);
throw i(J), J;
}
var dh = "data:application/octet-stream;base64,";
function yc(H) {
return H.startsWith(dh);
}
function Lr(H) {
return H.startsWith("file://");
}
var sn;
sn = "tfjs-backend-wasm.wasm", yc(sn) || (sn = b(sn));
function yu(H) {
try {
if (H == sn && ee)
return new Uint8Array(ee);
if (x)
return x(H);
throw "both async and sync fetching of the wasm failed";
} catch (J) {
zr(J);
}
}
function ph() {
if (!ee && (h || f)) {
if (typeof fetch == "function" && !Lr(sn))
return fetch(sn, { credentials: "same-origin" }).then(function(H) {
if (!H.ok)
throw "failed to load wasm binary file at '" + sn + "'";
return H.arrayBuffer();
}).catch(function() {
return yu(sn);
});
if (v)
return new Promise(function(H, J) {
v(sn, function(ce) {
H(new Uint8Array(ce));
}, J);
});
}
return Promise.resolve().then(function() {
return yu(sn);
});
}
function hh() {
var H = { env: Ao, wasi_snapshot_preview1: Ao };
function J(Be, ze) {
var Tt = Be.exports;
a.asm = Tt, te = a.asm.memory, Ls(te.buffer), Zs = a.asm.__indirect_function_table, rs(a.asm.__wasm_call_ctors), bc("wasm-instantiate");
}
ch("wasm-instantiate");
function ce(Be) {
J(Be.instance);
}
function Se(Be) {
return ph().then(function(ze) {
return WebAssembly.instantiate(ze, H);
}).then(function(ze) {
return ze;
}).then(Be, function(ze) {
A("failed to asynchronously prepare wasm: " + ze), zr(ze);
});
}
function Qe() {
return !ee && typeof WebAssembly.instantiateStreaming == "function" && !yc(sn) && !Lr(sn) && typeof fetch == "function" ? fetch(sn, { credentials: "same-origin" }).then(function(Be) {
var ze = WebAssembly.instantiateStreaming(Be, H);
return ze.then(ce, function(Tt) {
return A("wasm streaming compile failed: " + Tt), A("falling back to ArrayBuffer instantiation"), Se(ce);
});
}) : Se(ce);
}
if (a.instantiateWasm)
try {
var Ze = a.instantiateWasm(H, J);
return Ze;
} catch (Be) {
return A("Module.instantiateWasm callback failed with error: " + Be), false;
}
return Qe().catch(i), {};
}
var qv, jv;
function vu(H) {
for (; H.length > 0; ) {
var J = H.shift();
if (typeof J == "function") {
J(a);
continue;
}
var ce = J.func;
typeof ce == "number" ? J.arg === void 0 ? xu(ce)() : xu(ce)(J.arg) : ce(J.arg === void 0 ? null : J.arg);
}
}
function er(H) {
return H;
}
function vc(H) {
var J = /\b_Z[\w\d_]+/g;
return H.replace(J, function(ce) {
var Se = ce;
return ce === Se ? ce : Se + " [" + ce + "]";
});
}
var as = [];
function xu(H) {
var J = as[H];
return J || (H >= as.length && (as.length = H + 1), as[H] = J = Zs.get(H)), J;
}
function Kv() {
var H = new Error();
if (!H.stack) {
try {
throw new Error();
} catch (J) {
H = J;
}
if (!H.stack)
return "(no stack trace available)";
}
return H.stack.toString();
}
function $o(H, J) {
Zs.set(H, J), as[H] = J;
}
function fh() {
zr("");
}
function xc(H, J, ce) {
en.copyWithin(H, J, J + ce);
}
function wc() {
return 2147483648;
}
function rn(H) {
try {
return te.grow(H - In.byteLength + 65535 >>> 16), Ls(te.buffer), 1;
} catch (J) {
}
}
function kc(H) {
var J = en.length;
H = H >>> 0;
var ce = wc();
if (H > ce)
return false;
for (var Se = 1; Se <= 4; Se *= 2) {
var Qe = J * (1 + 0.2 / Se);
Qe = Math.min(Qe, H + 100663296);
var Ze = Math.min(ce, Nt(Math.max(H, Qe), 65536)), Be = rn(Ze);
if (Be)
return true;
}
return false;
}
var _o = { mappings: {}, buffers: [null, [], []], printChar: function(H, J) {
var ce = _o.buffers[H];
J === 0 || J === 10 ? ((H === 1 ? P : A)(Xe(ce, 0)), ce.length = 0) : ce.push(J);
}, varargs: void 0, get: function() {
_o.varargs += 4;
var H = Yt[_o.varargs - 4 >> 2];
return H;
}, getStr: function(H) {
var J = Je(H);
return J;
}, get64: function(H, J) {
return H;
} };
function mh(H) {
return 0;
}
function Xv(H, J, ce, Se, Qe) {
}
function Yv(H, J, ce, Se) {
for (var Qe = 0, Ze = 0; Ze < ce; Ze++) {
var Be = Yt[J >> 2], ze = Yt[J + 4 >> 2];
J += 8;
for (var Tt = 0; Tt < ze; Tt++)
_o.printChar(H, en[Be + Tt]);
Qe += ze;
}
return Yt[Se >> 2] = Qe, 0;
}
function gh(H) {
ne(H);
}
var Sc = false, Ao = { abort: fh, emscripten_memcpy_big: xc, emscripten_resize_heap: kc, fd_close: mh, fd_seek: Xv, fd_write: Yv, setTempRet0: gh }, lT = hh(), Qv = a.___wasm_call_ctors = function() {
return (Qv = a.___wasm_call_ctors = a.asm.__wasm_call_ctors).apply(null, arguments);
}, bh = a._init = function() {
return (bh = a._init = a.asm.init).apply(null, arguments);
}, yh = a._init_with_threads_count = function() {
return (yh = a._init_with_threads_count = a.asm.init_with_threads_count).apply(null, arguments);
}, Ic = a._get_threads_count = function() {
return (Ic = a._get_threads_count = a.asm.get_threads_count).apply(null, arguments);
}, Cc = a._register_tensor = function() {
return (Cc = a._register_tensor = a.asm.register_tensor).apply(null, arguments);
}, vh = a._dispose_data = function() {
return (vh = a._dispose_data = a.asm.dispose_data).apply(null, arguments);
}, $e = a._dispose = function() {
return ($e = a._dispose = a.asm.dispose).apply(null, arguments);
}, xh = a._Abs = function() {
return (xh = a._Abs = a.asm.Abs).apply(null, arguments);
}, Nc = a._Add = function() {
return (Nc = a._Add = a.asm.Add).apply(null, arguments);
}, Mr = a._AddN = function() {
return (Mr = a._AddN = a.asm.AddN).apply(null, arguments);
}, Eo = a._All = function() {
return (Eo = a._All = a.asm.All).apply(null, arguments);
}, wh = a._Any = function() {
return (wh = a._Any = a.asm.Any).apply(null, arguments);
}, Zv = a._ArgMax = function() {
return (Zv = a._ArgMax = a.asm.ArgMax).apply(null, arguments);
}, kh = a._AvgPool = function() {
return (kh = a._AvgPool = a.asm.AvgPool).apply(null, arguments);
}, Jv = a._BatchMatMul = function() {
return (Jv = a._BatchMatMul = a.asm.BatchMatMul).apply(null, arguments);
}, Br = a._Ceil = function() {
return (Br = a._Ceil = a.asm.Ceil).apply(null, arguments);
}, Sh = a._ClipByValue = function() {
return (Sh = a._ClipByValue = a.asm.ClipByValue).apply(null, arguments);
}, Ih = a._Conv2D = function() {
return (Ih = a._Conv2D = a.asm.Conv2D).apply(null, arguments);
}, Ch = a._Conv2DBackpropInput = function() {
return (Ch = a._Conv2DBackpropInput = a.asm.Conv2DBackpropInput).apply(null, arguments);
}, Nh = a._Cos = function() {
return (Nh = a._Cos = a.asm.Cos).apply(null, arguments);
}, Th = a._Cosh = function() {
return (Th = a._Cosh = a.asm.Cosh).apply(null, arguments);
}, $h = a._CropAndResize = function() {
return ($h = a._CropAndResize = a.asm.CropAndResize).apply(null, arguments);
}, Tc = a._Cumprod = function() {
return (Tc = a._Cumprod = a.asm.Cumprod).apply(null, arguments);
}, _h = a._Cumsum = function() {
return (_h = a._Cumsum = a.asm.Cumsum).apply(null, arguments);
}, Ah = a._DepthToSpace = function() {
return (Ah = a._DepthToSpace = a.asm.DepthToSpace).apply(null, arguments);
}, Eh = a._DepthwiseConv2dNative = function() {
return (Eh = a._DepthwiseConv2dNative = a.asm.DepthwiseConv2dNative).apply(null, arguments);
}, Rh = a._Elu = function() {
return (Rh = a._Elu = a.asm.Elu).apply(null, arguments);
}, Dh = a._Equal = function() {
return (Dh = a._Equal = a.asm.Equal).apply(null, arguments);
}, $c = a._Exp = function() {
return ($c = a._Exp = a.asm.Exp).apply(null, arguments);
}, Fh = a._FlipLeftRight = function() {
return (Fh = a._FlipLeftRight = a.asm.FlipLeftRight).apply(null, arguments);
}, Oh = a._Floor = function() {
return (Oh = a._Floor = a.asm.Floor).apply(null, arguments);
}, Vr = a._FloorDiv = function() {
return (Vr = a._FloorDiv = a.asm.FloorDiv).apply(null, arguments);
}, wu = a._FusedBatchNorm = function() {
return (wu = a._FusedBatchNorm = a.asm.FusedBatchNorm).apply(null, arguments);
}, Ph = a._FusedConv2D = function() {
return (Ph = a._FusedConv2D = a.asm.FusedConv2D).apply(null, arguments);
}, zh = a._FusedDepthwiseConv2D = function() {
return (zh = a._FusedDepthwiseConv2D = a.asm.FusedDepthwiseConv2D).apply(null, arguments);
}, Lh = a._Gather = function() {
return (Lh = a._Gather = a.asm.Gather).apply(null, arguments);
}, Me = a._GatherNd = function() {
return (Me = a._GatherNd = a.asm.GatherNd).apply(null, arguments);
}, Mh = a._Greater = function() {
return (Mh = a._Greater = a.asm.Greater).apply(null, arguments);
}, Bh = a._GreaterEqual = function() {
return (Bh = a._GreaterEqual = a.asm.GreaterEqual).apply(null, arguments);
}, Vh = a._LeakyRelu = function() {
return (Vh = a._LeakyRelu = a.asm.LeakyRelu).apply(null, arguments);
}, Wh = a._Less = function() {
return (Wh = a._Less = a.asm.Less).apply(null, arguments);
}, Uh = a._LessEqual = function() {
return (Uh = a._LessEqual = a.asm.LessEqual).apply(null, arguments);
}, Gh = a._Log = function() {
return (Gh = a._Log = a.asm.Log).apply(null, arguments);
}, ku = a._LogicalAnd = function() {
return (ku = a._LogicalAnd = a.asm.LogicalAnd).apply(null, arguments);
}, _c = a._LogicalNot = function() {
return (_c = a._LogicalNot = a.asm.LogicalNot).apply(null, arguments);
}, Ac = a._LogicalOr = function() {
return (Ac = a._LogicalOr = a.asm.LogicalOr).apply(null, arguments);
}, Hh = a._LogicalXor = function() {
return (Hh = a._LogicalXor = a.asm.LogicalXor).apply(null, arguments);
}, qh = a._Max = function() {
return (qh = a._Max = a.asm.Max).apply(null, arguments);
}, jh = a._MaxPool = function() {
return (jh = a._MaxPool = a.asm.MaxPool).apply(null, arguments);
}, Kh = a._Maximum = function() {
return (Kh = a._Maximum = a.asm.Maximum).apply(null, arguments);
}, Xh = a._Mean = function() {
return (Xh = a._Mean = a.asm.Mean).apply(null, arguments);
}, Yh = a._Min = function() {
return (Yh = a._Min = a.asm.Min).apply(null, arguments);
}, gt = a._Minimum = function() {
return (gt = a._Minimum = a.asm.Minimum).apply(null, arguments);
}, Qh = a._MirrorPad = function() {
return (Qh = a._MirrorPad = a.asm.MirrorPad).apply(null, arguments);
}, Zh = a._Multiply = function() {
return (Zh = a._Multiply = a.asm.Multiply).apply(null, arguments);
}, Jh = a._Neg = function() {
return (Jh = a._Neg = a.asm.Neg).apply(null, arguments);
}, Ro = a._NonMaxSuppressionV3 = function() {
return (Ro = a._NonMaxSuppressionV3 = a.asm.NonMaxSuppressionV3).apply(null, arguments);
}, Ec = a._NonMaxSuppressionV4 = function() {
return (Ec = a._NonMaxSuppressionV4 = a.asm.NonMaxSuppressionV4).apply(null, arguments);
}, Rc = a._NonMaxSuppressionV5 = function() {
return (Rc = a._NonMaxSuppressionV5 = a.asm.NonMaxSuppressionV5).apply(null, arguments);
}, Dc = a._NotEqual = function() {
return (Dc = a._NotEqual = a.asm.NotEqual).apply(null, arguments);
}, ef = a._OneHot = function() {
return (ef = a._OneHot = a.asm.OneHot).apply(null, arguments);
}, Fc = a._PadV2 = function() {
return (Fc = a._PadV2 = a.asm.PadV2).apply(null, arguments);
}, tf = a._Pow = function() {
return (tf = a._Pow = a.asm.Pow).apply(null, arguments);
}, ex = a._Prelu = function() {
return (ex = a._Prelu = a.asm.Prelu).apply(null, arguments);
}, Oc = a._Prod = function() {
return (Oc = a._Prod = a.asm.Prod).apply(null, arguments);
}, tx = a._RealDiv = function() {
return (tx = a._RealDiv = a.asm.RealDiv).apply(null, arguments);
}, nf = a._Relu = function() {
return (nf = a._Relu = a.asm.Relu).apply(null, arguments);
}, sf = a._Relu6 = function() {
return (sf = a._Relu6 = a.asm.Relu6).apply(null, arguments);
}, rf = a._ResizeBilinear = function() {
return (rf = a._ResizeBilinear = a.asm.ResizeBilinear).apply(null, arguments);
}, af = a._Reverse = function() {
return (af = a._Reverse = a.asm.Reverse).apply(null, arguments);
}, of = a._RotateWithOffset = function() {
return (of = a._RotateWithOffset = a.asm.RotateWithOffset).apply(null, arguments);
}, uf = a._Round = function() {
return (uf = a._Round = a.asm.Round).apply(null, arguments);
}, lf = a._Rsqrt = function() {
return (lf = a._Rsqrt = a.asm.Rsqrt).apply(null, arguments);
}, cf = a._ScatterNd = function() {
return (cf = a._ScatterNd = a.asm.ScatterNd).apply(null, arguments);
}, df = a._SelectV2 = function() {
return (df = a._SelectV2 = a.asm.SelectV2).apply(null, arguments);
}, pf = a._Sigmoid = function() {
return (pf = a._Sigmoid = a.asm.Sigmoid).apply(null, arguments);
}, hf = a._Sin = function() {
return (hf = a._Sin = a.asm.Sin).apply(null, arguments);
}, ff = a._Softmax = function() {
return (ff = a._Softmax = a.asm.Softmax).apply(null, arguments);
}, mf = a._SparseFillEmptyRows = function() {
return (mf = a._SparseFillEmptyRows = a.asm.SparseFillEmptyRows).apply(null, arguments);
}, gf = a._SparseReshape = function() {
return (gf = a._SparseReshape = a.asm.SparseReshape).apply(null, arguments);
}, bf = a._SparseSegmentReduction = function() {
return (bf = a._SparseSegmentReduction = a.asm.SparseSegmentReduction).apply(null, arguments);
}, yf = a._Sqrt = function() {
return (yf = a._Sqrt = a.asm.Sqrt).apply(null, arguments);
}, vf = a._Square = function() {
return (vf = a._Square = a.asm.Square).apply(null, arguments);
}, xf = a._SquaredDifference = function() {
return (xf = a._SquaredDifference = a.asm.SquaredDifference).apply(null, arguments);
}, wf = a._Step = function() {
return (wf = a._Step = a.asm.Step).apply(null, arguments);
}, kf = a._StridedSlice = function() {
return (kf = a._StridedSlice = a.asm.StridedSlice).apply(null, arguments);
}, Sf = a._Sub = function() {
return (Sf = a._Sub = a.asm.Sub).apply(null, arguments);
}, If = a._Sum = function() {
return (If = a._Sum = a.asm.Sum).apply(null, arguments);
}, Cf = a._Tan = function() {
return (Cf = a._Tan = a.asm.Tan).apply(null, arguments);
}, Nf = a._Tanh = function() {
return (Nf = a._Tanh = a.asm.Tanh).apply(null, arguments);
}, Tf = a._Tile = function() {
return (Tf = a._Tile = a.asm.Tile).apply(null, arguments);
}, $f = a._TopK = function() {
return ($f = a._TopK = a.asm.TopK).apply(null, arguments);
}, _f = a._Transform = function() {
return (_f = a._Transform = a.asm.Transform).apply(null, arguments);
}, Af = a._Transpose = function() {
return (Af = a._Transpose = a.asm.Transpose).apply(null, arguments);
}, Ef = a.__FusedMatMul = function() {
return (Ef = a.__FusedMatMul = a.asm._FusedMatMul).apply(null, arguments);
}, Rf = a._malloc = function() {
return (Rf = a._malloc = a.asm.malloc).apply(null, arguments);
}, Df = a._free = function() {
return (Df = a._free = a.asm.free).apply(null, arguments);
}, Ff = a.___errno_location = function() {
return (Ff = a.___errno_location = a.asm.__errno_location).apply(null, arguments);
}, Of = a._emscripten_main_thread_process_queued_calls = function() {
return (Of = a._emscripten_main_thread_process_queued_calls = a.asm.emscripten_main_thread_process_queued_calls).apply(null, arguments);
}, Pc = a.stackSave = function() {
return (Pc = a.stackSave = a.asm.stackSave).apply(null, arguments);
}, zc = a.stackRestore = function() {
return (zc = a.stackRestore = a.asm.stackRestore).apply(null, arguments);
}, Su = a.stackAlloc = function() {
return (Su = a.stackAlloc = a.asm.stackAlloc).apply(null, arguments);
}, Pf = a.dynCall_iijjiiii = function() {
return (Pf = a.dynCall_iijjiiii = a.asm.dynCall_iijjiiii).apply(null, arguments);
}, zf = a.dynCall_jiji = function() {
return (zf = a.dynCall_jiji = a.asm.dynCall_jiji).apply(null, arguments);
};
a.cwrap = Ie;
var Do;
function Iu(H) {
this.name = "ExitStatus", this.message = "Program terminated with exit(" + H + ")", this.status = H;
}
Js = function H() {
Do || Cu(), Do || (Js = H);
};
function Cu(H) {
if (H = H || c, Fn > 0 || (pc(), Fn > 0))
return;
function J() {
Do || (Do = true, a.calledRun = true, !ie && (hc(), o(a), a.onRuntimeInitialized && a.onRuntimeInitialized(), fc()));
}
a.setStatus ? (a.setStatus("Running..."), setTimeout(function() {
setTimeout(function() {
a.setStatus("");
}, 1), J();
}, 1)) : J();
}
a.run = Cu;
function nx(H) {
ae = H, bu() || (a.onExit && a.onExit(H), ie = true), d(H, new Iu(H));
}
if (a.preInit)
for (typeof a.preInit == "function" && (a.preInit = [a.preInit]); a.preInit.length > 0; )
a.preInit.pop()();
Cu();
var Fo;
u && (Fo = { uncaughtException: process.listeners("uncaughtException").filter(function(H) {
return !u.uncaughtException.indexOf(H) > -1;
}), unhandledRejection: process.listeners("unhandledRejection").filter(function(H) {
return !u.unhandledRejection.indexOf(H) > -1;
}) });
var Oo;
if (typeof r != "undefined")
Oo = r;
else if (typeof WasmBackendModuleThreadedSimd != "undefined")
Oo = WasmBackendModuleThreadedSimd;
else
throw new Error("Could not find wasm module in post.js");
if (Fo) {
var Lf = Oo._dispose;
Oo._dispose = function() {
Lf(), Fo.uncaughtException.forEach(function(H) {
process.removeListener("uncaughtException", H);
}), Fo.unhandledRejection.forEach(function(H) {
process.removeListener("unhandledRejection", H);
});
};
}
return r.ready;
};
})();
typeof e == "object" && typeof t == "object" ? t.exports = n : typeof define == "function" && define.amd ? define([], function() {
return n;
}) : typeof e == "object" && (e.WasmBackendModule = n);
} });
var I$ = 1e-7;
var C$ = 1e-4;
var Zd = class {
constructor(e, t) {
this.backend = e, this.dataMover = t, this.data = /* @__PURE__ */ new WeakMap(), this.dataIdsCount = 0;
}
get(e) {
return this.data.has(e) || this.dataMover.moveData(this.backend, e), this.data.get(e);
}
set(e, t) {
this.dataIdsCount++, this.data.set(e, t);
}
has(e) {
return this.data.has(e);
}
delete(e) {
return this.dataIdsCount--, this.data.delete(e);
}
numDataIds() {
return this.dataIdsCount;
}
};
var il = class {
refCount(e) {
return On("refCount");
}
incRef(e) {
return On("incRef");
}
timerAvailable() {
return true;
}
time(e) {
return On("time");
}
read(e) {
return On("read");
}
readSync(e) {
return On("readSync");
}
readToGPU(e, t) {
return On("readToGPU");
}
numDataIds() {
return On("numDataIds");
}
disposeData(e, t) {
return On("disposeData");
}
write(e, t, n) {
return On("write");
}
move(e, t, n, s, r) {
return On("move");
}
memory() {
return On("memory");
}
floatPrecision() {
return On("floatPrecision");
}
epsilon() {
return this.floatPrecision() === 32 ? I$ : C$;
}
dispose() {
return On("dispose");
}
};
function On(e) {
throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`);
}
function rk(e) {
let t = e.length, n = 0;
for (; t > 0; )
n = Math.random() * t | 0, t--, yd(e, t, n);
}
function N$(e, t) {
if (e.length !== t.length)
throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);
let n = e.length, s = 0;
for (; n > 0; )
s = Math.random() * n | 0, n--, yd(e, n, s), yd(t, n, s);
}
function Hu(e, t, n) {
return Math.max(e, Math.min(t, n));
}
function T$(e) {
return e % 2 === 0 ? e : e + 1;
}
function yd(e, t, n) {
let s = e[t];
e[t] = e[n], e[n] = s;
}
function $$(e) {
let t = 0;
for (let n = 0; n < e.length; n++)
t += e[n];
return t;
}
function _$(e, t) {
let n = Math.random();
return t * n + (1 - n) * e;
}
function A$(e, t) {
let n = 0;
for (let s = 0; s < e.length; s++) {
let r = Number(e[s]) - Number(t[s]);
n += r * r;
}
return n;
}
function O(e, t) {
if (!e)
throw new Error(typeof t == "string" ? t : t());
}
function hn(e, t, n = "") {
O(Ir(e, t), () => n + ` Shapes ${e} and ${t} must match`);
}
function ka(e) {
O(e != null, () => "The input to the tensor constructor must be a non-null value.");
}
function aa(e, t = [], n = false) {
if (t == null && (t = []), Array.isArray(e) || Qt(e) && !n)
for (let s = 0; s < e.length; ++s)
aa(e[s], t, n);
else
t.push(e);
return t;
}
function dt(e) {
if (e.length === 0)
return 1;
let t = e[0];
for (let n = 1; n < e.length; n++)
t *= e[n];
return t;
}
function E$(e) {
return e.length === 0;
}
function Ir(e, t) {
if (e === t)
return true;
if (e == null || t == null || e.length !== t.length)
return false;
for (let n = 0; n < e.length; n++)
if (e[n] !== t[n])
return false;
return true;
}
function ei(e) {
return e % 1 === 0;
}
function R$(e) {
if (Math.tanh != null)
return Math.tanh(e);
if (e === 1 / 0)
return 1;
if (e === -1 / 0)
return -1;
{
let t = Math.exp(2 * e);
return (t - 1) / (t + 1);
}
}
function D$(e) {
let t = Math.ceil(Math.sqrt(e));
return [t, Math.ceil(e / t)];
}
function F$(e) {
let t = new Uint32Array(e);
for (let n = 0; n < e; ++n)
t[n] = n;
return rk(t), t;
}
function Vu(e, t) {
return t <= e.length ? e : e + " ".repeat(t - e.length);
}
function O$(e, t = (s) => 0, n) {
return new Promise((s, r) => {
let a = 0, o = () => {
if (e()) {
s();
return;
}
a++;
let i = t(a);
if (n != null && a >= n) {
r();
return;
}
setTimeout(o, i);
};
o();
});
}
function P$(e, t) {
let n = 1, s = -1;
for (let a = 0; a < e.length; ++a)
if (e[a] >= 0)
n *= e[a];
else if (e[a] === -1) {
if (s !== -1)
throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${a}`);
s = a;
} else if (e[a] < 0)
throw Error(`Shapes can not be < 0. Found ${e[a]} at dim ${a}`);
if (s === -1) {
if (t > 0 && t !== n)
throw Error(`Size(${t}) must match the product of shape ${e}`);
return e;
}
if (n === 0)
throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);
if (t % n !== 0)
throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);
let r = e.slice();
return r[s] = t / n, r;
}
function ts(e, t) {
let n = t.length;
return e = e == null ? t.map((s, r) => r) : [].concat(e), O(e.every((s) => s >= -n && s < n), () => `All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`), O(e.every((s) => ei(s)), () => `All values in axis param must be integers but got axis ${e}`), e.map((s) => s < 0 ? n + s : s);
}
function ak(e, t) {
let n = [], s = [], r = t != null && Array.isArray(t) && t.length === 0, a = t == null || r ? null : ts(t, e).sort(), o = 0;
for (let i = 0; i < e.length; ++i) {
if (a != null) {
if (a[o] === i && e[i] !== 1)
throw new Error(`Can't squeeze axis ${i} since its dim '${e[i]}' is not 1`);
(a[o] == null || a[o] > i) && e[i] === 1 && (n.push(e[i]), s.push(i)), a[o] <= i && o++;
}
e[i] !== 1 && (n.push(e[i]), s.push(i));
}
return { newShape: n, keptDims: s };
}
function ok(e, t) {
let n = null;
if (e == null || e === "float32")
n = new Float32Array(t);
else if (e === "int32")
n = new Int32Array(t);
else if (e === "bool")
n = new Uint8Array(t);
else
throw new Error(`Unknown data type ${e}`);
return n;
}
function ik(e, t) {
let n = null;
if (e == null || e === "float32")
n = new Float32Array(t);
else if (e === "int32")
n = new Int32Array(t);
else if (e === "bool")
n = new Uint8Array(t);
else if (e === "string")
n = new Array(t);
else
throw new Error(`Unknown data type ${e}`);
return n;
}
function uk(e, t) {
for (let n = 0; n < e.length; n++) {
let s = e[n];
if (isNaN(s) || !isFinite(s))
throw Error(`A tensor of type ${t} being uploaded contains ${s}.`);
}
}
function lk(e) {
return e === "bool" || e === "complex64" || e === "float32" || e === "int32" || e === "string";
}
function z$(e, t) {
return !(t === "complex64" || t === "float32" && e !== "complex64" || t === "int32" && e !== "float32" && e !== "complex64" || t === "bool" && e === "bool");
}
function Qt(e) {
return e instanceof Float32Array || e instanceof Int32Array || e instanceof Uint8Array || e instanceof Uint8ClampedArray;
}
function om(e) {
if (e === "float32" || e === "int32")
return 4;
if (e === "complex64")
return 8;
if (e === "bool")
return 1;
throw new Error(`Unknown dtype ${e}`);
}
function ck(e) {
if (e == null)
return 0;
let t = 0;
return e.forEach((n) => t += n.length), t;
}
function or(e) {
return typeof e == "string" || e instanceof String;
}
function dk(e) {
return typeof e == "boolean";
}
function pk(e) {
return typeof e == "number";
}
function Jd(e) {
return Array.isArray(e) ? Jd(e[0]) : e instanceof Float32Array ? "float32" : e instanceof Int32Array || e instanceof Uint8Array || e instanceof Uint8ClampedArray ? "int32" : pk(e) ? "float32" : or(e) ? "string" : dk(e) ? "bool" : "float32";
}
function fr(e) {
return !!(e && e.constructor && e.call && e.apply);
}
function vd(e, t) {
for (let n = t; n < e; ++n)
if (e % n === 0)
return n;
return e;
}
function ci(e) {
let t = e.length;
if (t < 2)
return [];
let n = new Array(t - 1);
n[t - 2] = e[t - 1];
for (let s = t - 3; s >= 0; --s)
n[s] = n[s + 1] * e[s + 1];
return n;
}
function hk(e, t, n, s = false) {
let r = new Array();
if (t.length === 1) {
let a = t[0] * (s ? 2 : 1);
for (let o = 0; o < a; o++)
r[o] = n[e + o];
} else {
let a = t[0], o = t.slice(1), i = o.reduce((u, l) => u * l) * (s ? 2 : 1);
for (let u = 0; u < a; u++)
r[u] = hk(e + u * i, o, n, s);
}
return r;
}
function Xo(e, t, n = false) {
if (e.length === 0)
return t[0];
let s = e.reduce((r, a) => r * a) * (n ? 2 : 1);
if (s === 0)
return [];
if (s !== t.length)
throw new Error(`[${e}] does not match the input size ${t.length}${n ? " for a complex tensor" : ""}.`);
return hk(0, e, t, n);
}
function hg(e, t) {
let n = ep(e, t);
for (let s = 0; s < n.length; s++)
n[s] = 1;
return n;
}
function ep(e, t) {
if (t == null || t === "float32" || t === "complex64")
return new Float32Array(e);
if (t === "int32")
return new Int32Array(e);
if (t === "bool")
return new Uint8Array(e);
throw new Error(`Unknown data type ${t}`);
}
function L$(e, t) {
let n = e.reduce((s, r) => s * r, 1);
if (t == null || t === "float32")
return Xo(e, new Float32Array(n));
if (t === "int32")
return Xo(e, new Int32Array(n));
if (t === "bool")
return Xo(e, new Uint8Array(n));
throw new Error(`Unknown data type ${t}`);
}
function fg(e) {
e.forEach((t) => {
O(Number.isInteger(t) && t >= 0, () => `Tensor must have a shape comprised of positive integers but got shape [${e}].`);
});
}
function M$(e, t, n) {
if (t === 0)
return 0;
if (t === 1)
return e[0];
let s = e[e.length - 1];
for (let r = 0; r < e.length - 1; ++r)
s += n[r] * e[r];
return s;
}
function B$(e, t, n) {
if (t === 0)
return [];
if (t === 1)
return [e];
let s = new Array(t);
for (let r = 0; r < s.length - 1; ++r)
s[r] = Math.floor(e / n[r]), e -= s[r] * n[r];
return s[s.length - 1] = e, s;
}
function mg(e) {
return e && e.then && typeof e.then == "function";
}
var px = "tfjsflags";
var V$ = class {
constructor(e) {
this.global = e, this.flags = {}, this.flagRegistry = {}, this.urlFlags = {}, this.getQueryParams = W$, this.populateURLFlags();
}
setPlatform(e, t) {
this.platform != null && (K().getBool("IS_TEST") || K().getBool("PROD") || console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)), this.platformName = e, this.platform = t;
}
registerFlag(e, t, n) {
if (this.flagRegistry[e] = { evaluationFn: t, setHook: n }, this.urlFlags[e] != null) {
let s = this.urlFlags[e];
K().getBool("IS_TEST") || K().getBool("PROD") || console.warn(`Setting feature override from URL ${e}: ${s}.`), this.set(e, s);
}
}
async getAsync(e) {
return e in this.flags ? this.flags[e] : (this.flags[e] = await this.evaluateFlag(e), this.flags[e]);
}
get(e) {
if (e in this.flags)
return this.flags[e];
let t = this.evaluateFlag(e);
if (mg(t))
throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);
return this.flags[e] = t, this.flags[e];
}
getNumber(e) {
return this.get(e);
}
getBool(e) {
return this.get(e);
}
getFlags() {
return this.flags;
}
get features() {
return this.flags;
}
set(e, t) {
if (this.flagRegistry[e] == null)
throw new Error(`Cannot set flag ${e} as it has not been registered.`);
this.flags[e] = t, this.flagRegistry[e].setHook != null && this.flagRegistry[e].setHook(t);
}
evaluateFlag(e) {
if (this.flagRegistry[e] == null)
throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);
return this.flagRegistry[e].evaluationFn();
}
setFlags(e) {
this.flags = Object.assign({}, e);
}
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;
let e = this.getQueryParams(this.global.location.search);
px in e && e[px].split(",").forEach((n) => {
let [s, r] = n.split(":");
this.urlFlags[s] = G$(s, r);
});
}
};
function W$(e) {
let t = {};
return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (n, ...s) => (U$(t, s[0], s[1]), s.join("="))), t;
}
function U$(e, t, n) {
e[decodeURIComponent(t)] = decodeURIComponent(n || "");
}
function G$(e, t) {
if (t = t.toLowerCase(), t === "true" || t === "false")
return t === "true";
if (`${+t}` === t)
return +t;
throw new Error(`Could not parse value flag value ${t} for flag ${e}.`);
}
function K() {
return fk;
}
var fk = null;
function H$(e) {
fk = e;
}
var Hf;
function mk() {
if (Hf == null) {
let e;
if (typeof window != "undefined")
e = window;
else if (typeof global != "undefined")
e = global;
else if (typeof process != "undefined")
e = process;
else if (typeof self != "undefined")
e = self;
else
throw new Error("Could not find a global object");
Hf = e;
}
return Hf;
}
function q$() {
let e = mk();
return e._tfGlobals == null && (e._tfGlobals = /* @__PURE__ */ new Map()), e._tfGlobals;
}
function gg(e, t) {
let n = q$();
if (n.has(e))
return n.get(e);
{
let s = t();
return n.set(e, s), n.get(e);
}
}
var di = "Abs";
var ul = "Acos";
var ll = "Acosh";
var Cr = "Add";
var Sa = "AddN";
var cl = "All";
var dl = "Any";
var Ia = "ArgMax";
var pl = "ArgMin";
var hl = "Asin";
var fl = "Asinh";
var ml = "Atan";
var gl = "Atanh";
var bl = "Atan2";
var Ca = "AvgPool";
var bg = "AvgPoolGrad";
var tp = "AvgPool3D";
var yg = "AvgPool3DGrad";
var Na = "BatchMatMul";
var pi = "BatchToSpaceND";
var vg = "Bincount";
var j$ = "BroadcastTo";
var xg = "BroadcastArgs";
var Ta = "Cast";
var $a = "Ceil";
var Nr = "ClipByValue";
var np = "Complex";
var sp = "ComplexAbs";
var hi = "Concat";
var _a = "Conv2D";
var wg = "Conv2DBackpropFilter";
var Aa = "Conv2DBackpropInput";
var rp = "Conv3D";
var kg = "Conv3DBackpropFilterV2";
var Sg = "Conv3DBackpropInputV2";
var Ea = "Cos";
var Ra = "Cosh";
var fi = "Cumprod";
var Da = "Cumsum";
var mi = "CropAndResize";
var Ig = "DenseBincount";
var gi = "DepthToSpace";
var Fa = "DepthwiseConv2dNative";
var Cg = "DepthwiseConv2dNativeBackpropFilter";
var Ng = "DepthwiseConv2dNativeBackpropInput";
var Tg = "Diag";
var ap = "Dilation2D";
var im = "Dilation2DBackpropInput";
var um = "Dilation2DBackpropFilter";
var Oa = "RealDiv";
var op = "Einsum";
var Pa = "Elu";
var $g = "EluGrad";
var yl = "Erf";
var bi = "Equal";
var za = "Exp";
var yi = "ExpandDims";
var vi = "Expm1";
var _g = "FFT";
var vl = "Fill";
var xi = "FlipLeftRight";
var La = "Floor";
var Ma = "FloorDiv";
var Ba = "FusedBatchNorm";
var wi = "GatherV2";
var ki = "GatherNd";
var Si = "Greater";
var Va = "GreaterEqual";
var Wa = "Identity";
var Ag = "IFFT";
var ip = "Imag";
var xl = "IsFinite";
var wl = "IsInf";
var kl = "IsNan";
var Ua = "LeakyRelu";
var Ii = "Less";
var Ci = "LessEqual";
var Eg = "LinSpace";
var Ga = "Log";
var Sl = "Log1p";
var Ni = "LogicalAnd";
var Ti = "LogicalNot";
var Il = "LogicalOr";
var K$ = "LogicalXor";
var X$ = "LogSoftmax";
var Cpe = "LowerBound";
var up = "LRN";
var Rg = "LRNGrad";
var Ha = "Max";
var qa = "Maximum";
var ja = "MaxPool";
var Dg = "MaxPoolGrad";
var lp = "MaxPool3D";
var Fg = "MaxPool3DGrad";
var Og = "MaxPoolWithArgmax";
var Ka = "Mean";
var Xa = "Min";
var Ya = "Minimum";
var Qa = "MirrorPad";
var Cl = "Mod";
var Pg = "Multinomial";
var Za = "Multiply";
var $i = "Neg";
var _i = "NotEqual";
var Ai = "NonMaxSuppressionV3";
var Nl = "NonMaxSuppressionV4";
var Ei = "NonMaxSuppressionV5";
var Ri = "OnesLike";
var Di = "OneHot";
var Fi = "Pack";
var Ja = "PadV2";
var Npe = "Pool";
var eo = "Pow";
var to = "Prelu";
var no = "Prod";
var Tl = "Range";
var cp = "Real";
var $l = "Reciprocal";
var so = "Relu";
var Oi = "Reshape";
var _l = "ResizeNearestNeighbor";
var zg = "ResizeNearestNeighborGrad";
var ro = "ResizeBilinear";
var Lg = "ResizeBilinearGrad";
var ao = "Relu6";
var Pi = "Reverse";
var zi = "Round";
var oo = "Rsqrt";
var Li = "ScatterNd";
var Mg = "SearchSorted";
var Mi = "Select";
var Al = "Selu";
var Bi = "Slice";
var io = "Sin";
var Vi = "Sinh";
var El = "Sign";
var uo = "Sigmoid";
var Rl = "Softplus";
var lo = "Sqrt";
var co = "Sum";
var Wi = "SpaceToBatchND";
var Ui = "SplitV";
var po = "Softmax";
var dp = "SparseFillEmptyRows";
var Dl = "SparseReshape";
var pp = "SparseSegmentMean";
var hp = "SparseSegmentSum";
var fp = "SparseToDense";
var ho = "SquaredDifference";
var Fl = "Square";
var Gi = "StridedSlice";
var mp = "StringNGrams";
var Bg = "StringSplit";
var Vg = "StringToHashBucketFast";
var fo = "Sub";
var Hi = "Tan";
var mo = "Tanh";
var Tr = "Tile";
var qi = "TopK";
var ji = "Transform";
var Hs = "Transpose";
var Wg = "Unique";
var Ki = "Unpack";
var gp = "UnsortedSegmentSum";
var Tpe = "UpperBound";
var Xi = "ZerosLike";
var go = "Step";
var xd = "FromPixels";
var Yi = "RotateWithOffset";
var oa = "_FusedMatMul";
var ia = "FusedConv2D";
var ua = "FusedDepthwiseConv2D";
function ar(...e) {
K().getBool("IS_TEST") || K().getBool("PROD") || console.warn(...e);
}
function Y$(...e) {
K().getBool("IS_TEST") || K().getBool("PROD") || console.log(...e);
}
var ti = gg("kernelRegistry", () => /* @__PURE__ */ new Map());
var qu = gg("gradRegistry", () => /* @__PURE__ */ new Map());
function lm(e, t) {
let n = Ug(e, t);
return ti.get(n);
}
function hx(e) {
return qu.get(e);
}
function cm(e) {
let t = ti.entries(), n = [];
for (; ; ) {
let { done: s, value: r } = t.next();
if (s)
break;
let [a, o] = r, [i] = a.split("_");
i === e && n.push(o);
}
return n;
}
function Ol(e) {
let { kernelName: t, backendName: n } = e, s = Ug(t, n);
ti.has(s) && ar(`The kernel '${t}' for backend '${n}' is already registered`), ti.set(s, e);
}
function Q$(e) {
let { kernelName: t } = e;
qu.has(t) && K().getBool("DEBUG") && ar(`Overriding the gradient for '${t}'`), qu.set(t, e);
}
function $pe(e, t) {
let n = Ug(e, t);
if (!ti.has(n))
throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);
ti.delete(n);
}
function _pe(e) {
if (!qu.has(e))
throw new Error(`The gradient '${e}' for backend is not registered`);
qu.delete(e);
}
function Ape(e, t) {
cm(e).forEach((s) => {
let r = Object.assign({}, s, { backendName: t });
Ol(r);
});
}
function Ug(e, t) {
return `${t}_${e}`;
}
var w = {};
Ee(w, { arraysEqual: () => Ir, assert: () => O, assertNonNegativeIntegerDimensions: () => fg, assertNonNull: () => ka, assertShapesMatch: () => hn, bytesFromStringArray: () => ck, bytesPerElement: () => om, checkConversionForErrors: () => uk, clamp: () => Hu, computeStrides: () => ci, createScalarValue: () => s_, createShuffledIndices: () => F$, decodeString: () => wd, distSquared: () => A$, encodeString: () => zl, fetch: () => a_, fingerPrint64: () => n_, flatten: () => aa, getArrayFromDType: () => ik, getTypedArrayFromDType: () => ok, hasEncodingLoss: () => z$, hexToLong: () => Pl, indexToLoc: () => B$, inferDtype: () => Jd, inferFromImplicitShape: () => P$, isBoolean: () => dk, isFunction: () => fr, isInt: () => ei, isNumber: () => pk, isPromise: () => mg, isScalarShape: () => E$, isString: () => or, isTypedArray: () => Qt, isValidDtype: () => lk, locToIndex: () => M$, makeOnesTypedArray: () => hg, makeZerosNestedTypedArray: () => L$, makeZerosTypedArray: () => ep, nearestDivisor: () => vd, nearestLargerEven: () => T$, now: () => ju, parseAxisParam: () => ts, randUniform: () => _$, repeatedTry: () => O$, rightPad: () => Vu, shuffle: () => rk, shuffleCombo: () => N$, sizeFromShape: () => dt, sizeToSquarishShape: () => D$, squeezeShape: () => ak, sum: () => $$, swap: () => yd, tanh: () => R$, toNestedArray: () => Xo, toTypedArray: () => bp });
var fx = wa(u$());
var Kr = fx.default || fx;
function Pl(e) {
return Kr.fromString(e, true, 16);
}
var gk = Pl("c3a5c85c97cb3127");
var qr = Pl("b492b66fbe98f273");
var on = Pl("9ae16a3b2f90404f");
function dm(e) {
return e.xor(e.shru(47));
}
function bk(e, t, n) {
let s = e.slice(t, t + n);
return Kr.fromBytes(Array.from(s), true, true);
}
function lt(e, t) {
return bk(e, t, 8);
}
function mx(e, t) {
return bk(e, t, 4);
}
function Mt(e, t) {
return t === 0 ? e : e.shru(t).or(e.shl(64 - t));
}
function ur(e, t, n = Pl("9ddfea08eb382d69")) {
let s = e.xor(t).mul(n);
s = s.xor(s.shru(47));
let r = t.xor(s).mul(n);
return r = r.xor(r.shru(47)), r = r.mul(n), r;
}
function Z$(e, t, n, s, r, a) {
r = r.add(e), a = Mt(a.add(r).add(s), 21);
let o = r;
return r = r.add(t), r = r.add(n), a = a.add(Mt(r, 44)), [r.add(s), a.add(o)];
}
function Hc(e, t, n, s) {
return Z$(lt(e, t), lt(e, t + 8), lt(e, t + 16), lt(e, t + 24), n, s);
}
function J$(e, t = e.length) {
if (t >= 8) {
let n = on.add(t * 2), s = lt(e, 0).add(on), r = lt(e, t - 8), a = Mt(r, 37).mul(n).add(s), o = Mt(s, 25).add(r).mul(n);
return ur(a, o, n);
}
if (t >= 4) {
let n = on.add(t * 2), s = mx(e, 0);
return ur(s.shl(3).add(t), mx(e, t - 4), n);
}
if (t > 0) {
let n = e[0], s = e[t >> 1], r = e[t - 1], a = n + (s << 8), o = t + (r << 2);
return dm(on.mul(a).xor(gk.mul(o))).mul(on);
}
return on;
}
function e_(e, t = e.length) {
let n = on.add(t * 2), s = lt(e, 0).mul(qr), r = lt(e, 8), a = lt(e, t - 8).mul(n), o = lt(e, t - 16).mul(on);
return ur(Mt(s.add(r), 43).add(Mt(a, 30)).add(o), s.add(Mt(r.add(on), 18)).add(a), n);
}
function t_(e, t = e.length) {
let n = on.add(t * 2), s = lt(e, 0).mul(on), r = lt(e, 8), a = lt(e, t - 8).mul(n), o = lt(e, t - 16).mul(on), i = Mt(s.add(r), 43).add(Mt(a, 30)).add(o), u = ur(i, s.add(Mt(r.add(on), 18)).add(a), n), l = lt(e, 16).mul(n), c = lt(e, 24), p = i.add(lt(e, t - 32)).mul(n), d = u.add(lt(e, t - 24)).mul(n);
return ur(Mt(l.add(c), 43).add(Mt(p, 30)).add(d), l.add(Mt(c.add(s), 18)).add(p), n);
}
function n_(e, t = e.length) {
let n = Kr.fromNumber(81, true);
if (t <= 32)
return t <= 16 ? J$(e, t) : e_(e, t);
if (t <= 64)
return t_(e, t);
let s = n, r = n.mul(qr).add(113), a = dm(r.mul(on).add(113)).mul(on), o = [Kr.UZERO, Kr.UZERO], i = [Kr.UZERO, Kr.UZERO];
s = s.mul(on).add(lt(e, 0));
let u = 0, l = (t - 1 >> 6) * 64, c = l + (t - 1 & 63) - 63;
do
s = Mt(s.add(r).add(o[0]).add(lt(e, u + 8)), 37).mul(qr), r = Mt(r.add(o[1]).add(lt(e, u + 48)), 42).mul(qr), s = s.xor(i[1]), r = r.add(o[0]).add(lt(e, u + 40)), a = Mt(a.add(i[0]), 33).mul(qr), o = Hc(e, u, o[1].mul(qr), s.add(i[0])), i = Hc(e, u + 32, a.add(i[1]), r.add(lt(e, u + 16))), [a, s] = [s, a], u += 64;
while (u !== l);
let p = qr.add(a.and(255).shl(1));
return u = c, i[0] = i[0].add(t - 1 & 63), o[0] = o[0].add(i[0]), i[0] = i[0].add(o[0]), s = Mt(s.add(r).add(o[0]).add(lt(e, u + 8)), 37).mul(p), r = Mt(r.add(o[1]).add(lt(e, u + 48)), 42).mul(p), s = s.xor(i[1].mul(9)), r = r.add(o[0].mul(9).add(lt(e, u + 40))), a = Mt(a.add(i[0]), 33).mul(p), o = Hc(e, u, o[1].mul(p), s.add(i[0])), i = Hc(e, u + 32, a.add(i[1]), r.add(lt(e, u + 16))), [a, s] = [s, a], ur(ur(o[0], i[0], p).add(dm(r).mul(gk)).add(a), ur(o[1], i[1], p).add(s), p);
}
function s_(e, t) {
return t === "string" ? zl(e) : bp([e], t);
}
function r_(e, t) {
return e instanceof Float32Array && t === "float32" || e instanceof Int32Array && t === "int32" || e instanceof Uint8Array && t === "bool";
}
function bp(e, t) {
if (t === "string")
throw new Error("Cannot convert a string[] to a TypedArray");
if (Array.isArray(e) && (e = aa(e)), K().getBool("DEBUG") && uk(e, t), r_(e, t))
return e;
if (t == null || t === "float32" || t === "complex64")
return new Float32Array(e);
if (t === "int32")
return new Int32Array(e);
if (t === "bool") {
let n = new Uint8Array(e.length);
for (let s = 0; s < n.length; ++s)
Math.round(e[s]) !== 0 && (n[s] = 1);
return n;
} else
throw new Error(`Unknown data type ${t}`);
}
function ju() {
return K().platform.now();
}
function a_(e, t) {
return K().platform.fetch(e, t);
}
function zl(e, t = "utf-8") {
return t = t || "utf-8", K().platform.encode(e, t);
}
function wd(e, t = "utf-8") {
return t = t || "utf-8", K().platform.decode(e, t);
}
var o_ = class {
constructor(e, t) {
this.backendTimer = e, this.logger = t, t == null && (this.logger = new u_());
}
profileKernel(e, t, n) {
let s, r = () => {
s = n();
}, a, o = ju();
if (this.backendTimer.timerAvailable())
a = this.backendTimer.time(r);
else {
r();
for (let u of s)
u.dataSync();
a = Promise.resolve({ kernelMs: ju() - o });
}
if (K().getBool("CHECK_COMPUTATION_FOR_ERRORS"))
for (let u = 0; u < s.length; u++) {
let l = s[u];
l.data().then((c) => {
i_(c, l.dtype, e);
});
}
return { kernelName: e, outputs: s, inputs: t, timeMs: a.then((u) => u.kernelMs), extraInfo: a.then((u) => u.getExtraProfileInfo != null ? u.getExtraProfileInfo() : "") };
}
logKernelProfile(e) {
let { kernelName: t, outputs: n, timeMs: s, inputs: r, extraInfo: a } = e;
n.forEach((o) => {
Promise.all([o.data(), s, a]).then((i) => {
this.logger.logKernelProfile(t, o, i[0], i[1], r, i[2]);
});
});
}
};
function i_(e, t, n) {
if (t !== "float32")
return false;
for (let s = 0; s < e.length; s++) {
let r = e[s];
if (isNaN(r) || !isFinite(r))
return console.warn(`Found ${r} in the result of '${n}'`), true;
}
return false;
}
var u_ = class {
logKernelProfile(e, t, n, s, r, a) {
let o = typeof s == "number" ? Vu(`${s}ms`, 9) : s.error, i = Vu(e, 25), u = t.rank, l = t.size, c = Vu(t.shape.toString(), 14), p = "";
for (let d in r) {
let h = r[d];
if (h != null) {
let f = h.shape || t.shape, m = f.length;
p += `${d}: ${m}D ${m > 0 ? f : ""} `;
}
}
console.log(`%c${i} %c${o} %c${u}D ${c} %c${l} %c${p} %c${a}`, "font-weight:bold", "color:red", "color:blue", "color: orange", "color: green", "color: steelblue");
}
};
function l_(e, t, n) {
let s = {}, r = {};
for (let u = 0; u < t.length; u++)
s[t[u].id] = true;
for (let u = 0; u < e.length; u++) {
let l = e[u], c = l.inputs;
for (let p in c) {
let d = c[p], h = false;
for (let f = 0; f < t.length; f++)
if (s[d.id]) {
l.outputs.forEach((m) => s[m.id] = true), h = true, r[l.id] = true;
break;
}
if (h)
break;
}
}
let a = {};
a[n.id] = true;
let o = {};
for (let u = e.length - 1; u >= 0; u--) {
let l = e[u], c = l.inputs;
for (let p = 0; p < l.outputs.length; p++)
if (a[l.outputs[p].id]) {
for (let d in c)
a[c[d].id] = true, o[l.id] = true;
break;
}
}
let i = [];
for (let u = 0; u < e.length; u++) {
let l = e[u];
if (r[l.id] && o[l.id]) {
let c = {};
for (let d in l.inputs) {
let h = l.inputs[d];
s[h.id] && (c[d] = h);
}
let p = Object.assign({}, l);
p.inputs = c, p.outputs = l.outputs, i.push(p);
}
}
return i;
}
function c_(e, t, n, s) {
for (let r = t.length - 1; r >= 0; r--) {
let a = t[r], o = [];
if (a.outputs.forEach((u) => {
let l = e[u.id];
l != null ? o.push(l) : o.push(null);
}), a.gradient == null)
throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);
let i = a.gradient(o);
for (let u in a.inputs) {
if (!(u in i))
throw new Error(`Cannot backprop through input ${u}. Available gradients found: ${Object.keys(i)}.`);
let l = n(() => i[u]());
if (l.dtype !== "float32")
throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${u} must have 'float32' dtype, but has '${l.dtype}'`);
let c = a.inputs[u];
if (!Ir(l.shape, c.shape))
throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${u}' has shape '${l.shape}', which does not match the shape of the input '${c.shape}'`);
if (e[c.id] == null)
e[c.id] = l;
else {
let p = e[c.id];
e[c.id] = s(p, l), p.dispose();
}
}
}
}
var gx = 20;
var $u = 3;
var qf = 7;
function d_(e, t, n, s) {
let r = ci(t), a = p_(e, t, n, r), o = t.length, i = ad(e, t, n, r, a), u = ["Tensor"];
return s && (u.push(` dtype: ${n}`), u.push(` rank: ${o}`), u.push(` shape: [${t}]`), u.push(" values:")), u.push(i.map((l) => " " + l).join(`
`)), u.join(`
`);
}
function p_(e, t, n, s) {
let r = dt(t), a = s[s.length - 1], o = new Array(a).fill(0), i = t.length, u = n === "complex64" ? Du(e) : e;
if (i > 1)
for (let l = 0; l < r / a; l++) {
let c = l * a;
for (let p = 0; p < a; p++)
o[p] = Math.max(o[p], Ru(u[c + p], 0, n).length);
}
return o;
}
function Ru(e, t, n) {
let s;
return Array.isArray(e) ? s = `${parseFloat(e[0].toFixed(qf))} + ${parseFloat(e[1].toFixed(qf))}j` : or(e) ? s = `'${e}'` : n === "bool" ? s = yk(e) : s = parseFloat(e.toFixed(qf)).toString(), Vu(s, t);
}
function yk(e) {
return e === 0 ? "false" : "true";
}
function ad(e, t, n, s, r, a = true) {
let o = n === "complex64" ? 2 : 1, i = t[0], u = t.length;
if (u === 0) {
if (n === "complex64") {
let m = Du(e);
return [Ru(m[0], 0, n)];
}
return n === "bool" ? [yk(e[0])] : [e[0].toString()];
}
if (u === 1) {
if (i > gx) {
let g = $u * o, b = Array.from(e.slice(0, g)), y = Array.from(e.slice((i - $u) * o, i * o));
return n === "complex64" && (b = Du(b), y = Du(y)), ["[" + b.map((v, x) => Ru(v, r[x], n)).join(", ") + ", ..., " + y.map((v, x) => Ru(v, r[i - $u + x], n)).join(", ") + "]"];
}
let m = n === "complex64" ? Du(e) : Array.from(e);
return ["[" + m.map((g, b) => Ru(g, r[b], n)).join(", ") + "]"];
}
let l = t.slice(1), c = s.slice(1), p = s[0] * o, d = [];
if (i > gx) {
for (let m = 0; m < $u; m++) {
let g = m * p, b = g + p;
d.push(...ad(e.slice(g, b), l, n, c, r, false));
}
d.push("...");
for (let m = i - $u; m < i; m++) {
let g = m * p, b = g + p;
d.push(...ad(e.slice(g, b), l, n, c, r, m === i - 1));
}
} else
for (let m = 0; m < i; m++) {
let g = m * p, b = g + p;
d.push(...ad(e.slice(g, b), l, n, c, r, m === i - 1));
}
let h = u === 2 ? "," : "";
d[0] = "[" + d[0] + h;
for (let m = 1; m < d.length - 1; m++)
d[m] = " " + d[m] + h;
let f = `,
`;
for (let m = 2; m < u; m++)
f += `
`;
return d[d.length - 1] = " " + d[d.length - 1] + "]" + (a ? "" : f), d;
}
function Du(e) {
let t = [];
for (let n = 0; n < e.length; n += 2)
t.push([e[n], e[n + 1]]);
return t;
}
var Vt = class {
constructor(e, t, n) {
if (this.dtype = t, this.shape = e.slice(), this.size = dt(e), n != null) {
let s = n.length;
O(s === this.size, () => `Length of values '${s}' does not match the size inferred by the shape '${this.size}'.`);
}
if (t === "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 = n || ik(t, this.size), this.strides = ci(e);
}
set(e, ...t) {
t.length === 0 && (t = [0]), O(t.length === this.rank, () => `The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);
let n = this.locToIndex(t);
this.values[n] = e;
}
get(...e) {
e.length === 0 && (e = [0]);
let t = 0;
for (let s of e) {
if (s < 0 || s >= this.shape[t]) {
let r = `Requested out of range element at ${e}. Buffer shape=${this.shape}`;
throw new Error(r);
}
t++;
}
let n = e[e.length - 1];
for (let s = 0; s < e.length - 1; ++s)
n += this.strides[s] * e[s];
return this.values[n];
}
locToIndex(e) {
if (this.rank === 0)
return 0;
if (this.rank === 1)
return e[0];
let t = e[e.length - 1];
for (let n = 0; n < e.length - 1; ++n)
t += this.strides[n] * e[n];
return t;
}
indexToLoc(e) {
if (this.rank === 0)
return [];
if (this.rank === 1)
return [e];
let t = new Array(this.shape.length);
for (let n = 0; n < t.length - 1; ++n)
t[n] = Math.floor(e / this.strides[n]), e -= t[n] * this.strides[n];
return t[t.length - 1] = e, t;
}
get rank() {
return this.shape.length;
}
toTensor() {
return cs().makeTensor(this.values, this.shape, this.dtype);
}
};
var cs = null;
var Ho = null;
var h_ = null;
function f_(e) {
cs = e;
}
function m_(e) {
Ho = e;
}
function g_(e) {
h_ = e;
}
var et = class {
constructor(e, t, n, s) {
this.kept = false, this.isDisposedInternal = false, this.shape = e.slice(), this.dtype = t || "float32", this.size = dt(e), this.strides = ci(e), this.dataId = n, this.id = s, this.rankType = this.rank < 5 ? this.rank.toString() : "higher";
}
get rank() {
return this.shape.length;
}
async buffer() {
let e = await this.data();
return Ho.buffer(this.shape, this.dtype, e);
}
bufferSync() {
return Ho.buffer(this.shape, this.dtype, this.dataSync());
}
async array() {
let e = await this.data();
return Xo(this.shape, e, this.dtype === "complex64");
}
arraySync() {
return Xo(this.shape, this.dataSync(), this.dtype === "complex64");
}
async data() {
this.throwIfDisposed();
let e = cs().read(this.dataId);
if (this.dtype === "string") {
let t = await e;
try {
return t.map((n) => wd(n));
} catch (n) {
throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");
}
}
return e;
}
dataToGPU(e) {
return this.throwIfDisposed(), cs().readToGPU(this.dataId, e);
}
dataSync() {
this.throwIfDisposed();
let e = cs().readSync(this.dataId);
if (this.dtype === "string")
try {
return e.map((t) => wd(t));
} catch (t) {
throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");
}
return e;
}
async bytes() {
this.throwIfDisposed();
let e = await cs().read(this.dataId);
return this.dtype === "string" ? e : new Uint8Array(e.buffer);
}
dispose() {
this.isDisposed || (cs().disposeTensor(this), this.isDisposedInternal = true);
}
get isDisposed() {
return this.isDisposedInternal;
}
throwIfDisposed() {
if (this.isDisposed)
throw new Error("Tensor is disposed.");
}
print(e = false) {
return Ho.print(this, e);
}
clone() {
return this.throwIfDisposed(), Ho.clone(this);
}
toString(e = false) {
let t = this.dataSync();
return d_(t, this.shape, this.dtype, e);
}
cast(e) {
return this.throwIfDisposed(), Ho.cast(this, e);
}
variable(e = true, t, n) {
return this.throwIfDisposed(), cs().makeVariable(this, e, t, n);
}
};
Object.defineProperty(et, Symbol.hasInstance, { value: (e) => !!e && e.data != null && e.dataSync != null && e.throwIfDisposed != null });
function b_() {
return gg("Tensor", () => et);
}
b_();
var kd = class extends et {
constructor(e, t, n, s) {
super(e.shape, e.dtype, e.dataId, s), this.trainable = t, this.name = n;
}
assign(e) {
if (e.dtype !== this.dtype)
throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);
if (!Ir(e.shape, this.shape))
throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);
cs().disposeTensor(this), this.dataId = e.dataId, cs().incRef(this, null);
}
dispose() {
cs().disposeVariable(this), this.isDisposedInternal = true;
}
};
Object.defineProperty(kd, Symbol.hasInstance, { value: (e) => e instanceof et && e.assign != null && e.assign instanceof Function });
var _s = {};
Ee(_s, { assertTypesMatch: () => Sk, getTensorsInContainer: () => Gg, isTensorInList: () => x_, makeTypesMatch: () => xt });
var y_ = ((e) => (e.R0 = "R0", e.R1 = "R1", e.R2 = "R2", e.R3 = "R3", e.R4 = "R4", e.R5 = "R5", e.R6 = "R6", e))(y_ || {});
var vk = ((e) => (e.float32 = "float32", e.int32 = "int32", e.bool = "int32", e.complex64 = "complex64", e))(vk || {});
var xk = ((e) => (e.float32 = "float32", e.int32 = "int32", e.bool = "bool", e.complex64 = "complex64", e))(xk || {});
var wk = ((e) => (e.float32 = "float32", e.int32 = "float32", e.bool = "float32", e.complex64 = "complex64", e))(wk || {});
var kk = ((e) => (e.float32 = "complex64", e.int32 = "complex64", e.bool = "complex64", e.complex64 = "complex64", e))(kk || {});
var v_ = { float32: wk, int32: vk, bool: xk, complex64: kk };
function cn(e, t) {
if (e === "string" || t === "string") {
if (e === "string" && t === "string")
return "string";
throw new Error(`Can not upcast ${e} with ${t}`);
}
return v_[e][t];
}
function yp(e) {
return cn(e, "int32");
}
function xt(e, t) {
if (e.dtype === t.dtype)
return [e, t];
let n = cn(e.dtype, t.dtype);
return [e.cast(n), t.cast(n)];
}
function Sk(e, t) {
O(e.dtype === t.dtype, () => `The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`);
}
function x_(e, t) {
return t.some((n) => n.id === e.id);
}
function Gg(e) {
let t = [];
return Ik(e, t, /* @__PURE__ */ new Set()), t;
}
function Ik(e, t, n) {
if (e == null)
return;
if (e instanceof et) {
t.push(e);
return;
}
if (!w_(e))
return;
let s = e;
for (let r in s) {
let a = s[r];
n.has(a) || (n.add(a), Ik(a, t, n));
}
}
function w_(e) {
return Array.isArray(e) || typeof e == "object";
}
function jf(e) {
return e.kernelName != null;
}
var bx = class {
constructor() {
this.registeredVariables = {}, this.nextTapeNodeId = 0, this.numBytes = 0, this.numTensors = 0, this.numStringTensors = 0, this.numDataBuffers = 0, this.gradientDepth = 0, this.kernelDepth = 0, this.scopeStack = [], this.numDataMovesStack = [], this.nextScopeId = 0, this.tensorInfo = /* @__PURE__ */ new WeakMap(), this.profiling = false, this.activeProfile = { newBytes: 0, newTensors: 0, peakBytes: 0, kernels: [], result: null, get kernelNames() {
return Array.from(new Set(this.kernels.map((e) => e.name)));
} };
}
dispose() {
for (let e in this.registeredVariables)
this.registeredVariables[e].dispose();
}
};
var pm = class {
constructor(e) {
this.ENV = e, this.registry = {}, this.registryFactory = {}, this.pendingBackendInitId = 0, this.state = new bx();
}
async ready() {
if (this.pendingBackendInit != null)
return this.pendingBackendInit.then(() => {
});
if (this.backendInstance != null)
return;
let e = this.getSortedBackends();
for (let t = 0; t < e.length; t++) {
let n = e[t];
if (await this.initializeBackend(n).success) {
await this.setBackend(n);
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) {
let { name: e, asyncInit: t } = this.initializeBackendsAndReturnBest();
if (t)
throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);
this.setBackend(e);
}
return this.backendInstance;
}
backendNames() {
return Object.keys(this.registryFactory);
}
findBackend(e) {
if (!(e in this.registry))
if (e in this.registryFactory) {
let { asyncInit: t } = this.initializeBackend(e);
if (t)
return null;
} else
return null;
return this.registry[e];
}
findBackendFactory(e) {
return e in this.registryFactory ? this.registryFactory[e].factory : null;
}
registerBackend(e, t, n = 1) {
return e in this.registryFactory ? (ar(`${e} backend was already registered. Reusing existing backend factory.`), false) : (this.registryFactory[e] = { factory: t, priority: n }, true);
}
async setBackend(e) {
if (this.registryFactory[e] == null)
throw new Error(`Backend name '${e}' not found in registry`);
if (this.backendName = e, this.registry[e] == null) {
this.backendInstance = null;
let { success: t, asyncInit: n } = this.initializeBackend(e);
if (!(n ? await t : t))
return false;
}
return this.backendInstance = this.registry[e], this.setupRegisteredKernels(), this.profiler = new o_(this.backendInstance), true;
}
setupRegisteredKernels() {
cm(this.backendName).forEach((t) => {
t.setupFunc != null && t.setupFunc(this.backendInstance);
});
}
disposeRegisteredKernels(e) {
cm(e).forEach((n) => {
n.disposeFunc != null && n.disposeFunc(this.registry[e]);
});
}
initializeBackend(e) {
let t = this.registryFactory[e];
if (t == null)
throw new Error(`Cannot initialize backend ${e}, no registration found.`);
try {
let n = t.factory();
if (n && !(n instanceof il) && typeof n.then == "function") {
let s = ++this.pendingBackendInitId, r = n.then((a) => s < this.pendingBackendInitId ? false : (this.registry[e] = a, this.pendingBackendInit = null, true)).catch((a) => (s < this.pendingBackendInitId || (this.pendingBackendInit = null, ar(`Initialization of backend ${e} failed`), ar(a.stack || a.message)), false));
return this.pendingBackendInit = r, { success: r, asyncInit: true };
} else
return this.registry[e] = n, { success: true, asyncInit: false };
} catch (n) {
return ar(`Initialization of backend ${e} failed`), ar(n.stack || n.message), { success: false, asyncInit: false };
}
}
removeBackend(e) {
if (!(e in this.registryFactory))
throw new Error(`${e} backend not found in registry`);
this.backendName === e && this.pendingBackendInit != null && this.pendingBackendInitId++, e in this.registry && (this.disposeRegisteredKernels(e), this.registry[e].dispose(), delete this.registry[e]), delete this.registryFactory[e], this.backendName === e && (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((e, t) => this.registryFactory[t].priority - this.registryFactory[e].priority);
}
initializeBackendsAndReturnBest() {
let e = this.getSortedBackends();
for (let t = 0; t < e.length; t++) {
let n = e[t], { success: s, asyncInit: r } = this.initializeBackend(n);
if (r || s)
return { name: n, asyncInit: r };
}
throw new Error("Could not initialize any backends, all backend initializations failed.");
}
moveData(e, t) {
let n = this.state.tensorInfo.get(t), s = n.backend, r = this.readSync(t), a = s.refCount(t);
s.disposeData(t, true), n.backend = e, e.move(t, r, n.shape, n.dtype, a), this.shouldCheckForMemLeaks() && this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;
}
tidy(e, t) {
let n = null;
if (t == null) {
if (typeof e != "function")
throw new Error("Please provide a function to tidy()");
t = e;
} else {
if (typeof e != "string" && !(e instanceof String))
throw new Error("When calling with two arguments, the first argument to tidy() must be a string");
if (typeof t != "function")
throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");
n = e;
}
let s;
return this.scopedRun(() => this.startScope(n), () => this.endScope(s), () => (s = t(), s instanceof Promise && console.error("Cannot return a Promise inside of tidy."), s));
}
scopedRun(e, t, n) {
e();
try {
let s = n();
return t(), s;
} catch (s) {
throw t(), s;
}
}
nextTensorId() {
return pm.nextTensorId++;
}
nextVariableId() {
return pm.nextVariableId++;
}
clone(e) {
let t = z.runKernel(Wa, { x: e }), n = { x: e }, s = (a) => ({ x: () => {
let o = "float32", i = { x: a }, u = { dtype: o };
return z.runKernel(Ta, i, u);
} }), r = [];
return this.addTapeNode(this.state.activeScope.name, n, [t], s, r, {}), t;
}
runKernel(e, t, n) {
if (this.backendName == null && this.backend, !(lm(e, this.backendName) != null))
throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);
return this.runKernelFunc({ kernelName: e, inputs: t, attrs: n });
}
shouldCheckForMemLeaks() {
return this.ENV.getBool("IS_TEST");
}
checkKernelForMemLeak(e, t, n) {
let s = this.backend.numDataIds(), r = 0;
n.forEach((i) => {
r += i.dtype === "complex64" ? 3 : 1;
});
let a = this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1], o = s - t - r - a;
if (o > 0)
throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`);
}
runKernelFunc(e) {
let t, n = [], s = this.isTapeOn(), r = this.state.numBytes, a = this.state.numTensors;
this.shouldCheckForMemLeaks() && this.state.numDataMovesStack.push(0);
let o;
this.backendName == null && this.backend;
let i, u = jf(e) ? e.kernelName : this.state.activeScope != null ? this.state.activeScope.name : "";
if (jf(e)) {
let { kernelName: h, inputs: f, attrs: m } = e;
this.backendName == null && this.backend;
let g = lm(h, this.backendName);
O(g != null, () => `Cannot find registered kernel '${h}' for backend '${this.backendName}'`), o = () => {
let b = this.backend.numDataIds();
i = g.kernelFunc({ inputs: f, attrs: m, backend: this.backend });
let y = Array.isArray(i) ? i : [i];
this.shouldCheckForMemLeaks() && this.checkKernelForMemLeak(h, b, y);
let v = y.map((x) => x.rank != null ? x : this.makeTensorFromTensorInfo(x));
if (s) {
let x = this.getTensorsForGradient(h, f, v);
n = this.saveTensorsForBackwardMode(x);
}
return v;
};
} else {
let { forwardFunc: h } = e, f = (m) => {
!s || (n = m.map((g) => this.keep(this.clone(g))));
};
o = () => {
let m = this.backend.numDataIds();
i = this.tidy(() => h(this.backend, f));
let g = Array.isArray(i) ? i : [i];
return this.shouldCheckForMemLeaks() && this.checkKernelForMemLeak(u, m, g), g;
};
}
let { inputs: l, attrs: c } = e, p = jf(e) ? null : e.backwardsFunc, d;
return this.scopedRun(() => this.state.kernelDepth++, () => this.state.kernelDepth--, () => {
!this.ENV.getBool("DEBUG") && !this.state.profiling ? t = o() : (d = this.profiler.profileKernel(u, l, () => o()), this.ENV.getBool("DEBUG") && this.profiler.logKernelProfile(d), t = d.outputs);
}), s && this.addTapeNode(u, l, t, p, n, c), this.state.profiling && this.state.activeProfile.kernels.push({ name: u, bytesAdded: this.state.numBytes - r, totalBytesSnapshot: this.state.numBytes, tensorsAdded: this.state.numTensors - a, totalTensorsSnapshot: this.state.numTensors, inputShapes: Object.keys(l).map((h) => l[h] != null ? l[h].shape : null), outputShapes: t.map((h) => h.shape), kernelTimeMs: d.timeMs, extraInfo: d.extraInfo }), Array.isArray(i) ? t : t[0];
}
saveTensorsForBackwardMode(e) {
return e.map((n) => this.keep(this.clone(n)));
}
getTensorsForGradient(e, t, n) {
let s = hx(e);
if (s != null) {
let r = s.inputsToSave || [], a = s.outputsToSave || [], o;
s.saveAllInputs ? (O(Array.isArray(t), () => "saveAllInputs is true, expected inputs to be an array."), o = Object.keys(t).map((u) => t[u])) : o = r.map((u) => t[u]);
let i = n.filter((u, l) => a[l]);
return o.concat(i);
}
return [];
}
makeTensor(e, t, n, s) {
if (e == null)
throw new Error("Values passed to engine.makeTensor() are null");
n = n || "float32", s = s || this.backend;
let r = e;
n === "string" && or(e[0]) && (r = e.map((i) => zl(i)));
let a = s.write(r, t, n), o = new et(t, n, a, this.nextTensorId());
if (this.trackTensor(o, s), n === "string") {
let i = this.state.tensorInfo.get(a), u = ck(r);
this.state.numBytes += u - i.bytes, i.bytes = u;
}
return o;
}
makeTensorFromDataId(e, t, n, s) {
n = n || "float32";
let r = { dataId: e, shape: t, dtype: n };
return this.makeTensorFromTensorInfo(r, s);
}
makeTensorFromTensorInfo(e, t) {
let { dataId: n, shape: s, dtype: r } = e, a = new et(s, r, n, this.nextTensorId());
return this.trackTensor(a, t), a;
}
makeVariable(e, t = true, n, s) {
n = n || this.nextVariableId().toString(), s != null && s !== e.dtype && (e = e.cast(s));
let r = new kd(e, t, n, this.nextTensorId());
if (this.state.registeredVariables[r.name] != null)
throw new Error(`Variable with name ${r.name} was already registered`);
return this.state.registeredVariables[r.name] = r, this.incRef(r, this.backend), r;
}
trackTensor(e, t) {
this.state.numTensors++, e.dtype === "string" && this.state.numStringTensors++;
let n = 0;
e.dtype !== "complex64" && e.dtype !== "string" && (n = e.size * om(e.dtype)), this.state.numBytes += n, this.state.tensorInfo.has(e.dataId) || (this.state.numDataBuffers++, this.state.tensorInfo.set(e.dataId, { backend: t || this.backend, dtype: e.dtype, shape: e.shape, bytes: n })), e instanceof kd || this.track(e);
}
incRef(e, t) {
this.trackTensor(e, t), this.backend.incRef(e.dataId);
}
removeDataId(e, t) {
this.state.tensorInfo.has(e) && this.state.tensorInfo.get(e).backend === t && (this.state.tensorInfo.delete(e), this.state.numDataBuffers--);
}
disposeTensor(e) {
if (!this.state.tensorInfo.has(e.dataId))
return;
let t = this.state.tensorInfo.get(e.dataId);
if (this.state.numTensors--, e.dtype === "string" && (this.state.numStringTensors--, this.state.numBytes -= t.bytes), e.dtype !== "complex64" && e.dtype !== "string") {
let n = e.size * om(e.dtype);
this.state.numBytes -= n;
}
t.backend.disposeData(e.dataId) && this.removeDataId(e.dataId, t.backend);
}
disposeVariables() {
for (let e in this.state.registeredVariables) {
let t = this.state.registeredVariables[e];
this.disposeVariable(t);
}
}
disposeVariable(e) {
this.disposeTensor(e), this.state.registeredVariables[e.name] != null && delete this.state.registeredVariables[e.name];
}
memory() {
let e = this.backend.memory();
return e.numTensors = this.state.numTensors, e.numDataBuffers = this.state.numDataBuffers, e.numBytes = this.state.numBytes, this.state.numStringTensors > 0 && (e.unreliable = true, e.reasons == null && (e.reasons = []), e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")), e;
}
async profile(e) {
this.state.profiling = true;
let t = this.state.numBytes, n = this.state.numTensors;
this.state.activeProfile.kernels = [], this.state.activeProfile.result = await e(), this.state.profiling = false, this.state.activeProfile.peakBytes = Math.max(...this.state.activeProfile.kernels.map((s) => s.totalBytesSnapshot)), this.state.activeProfile.newBytes = this.state.numBytes - t, this.state.activeProfile.newTensors = this.state.numTensors - n;
for (let s of this.state.activeProfile.kernels)
s.kernelTimeMs = await s.kernelTimeMs, s.extraInfo = await s.extraInfo;
return this.state.activeProfile;
}
isTapeOn() {
return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;
}
addTapeNode(e, t, n, s, r, a) {
let o = { id: this.state.nextTapeNodeId++, kernelName: e, inputs: t, outputs: n, saved: r }, i = hx(e);
i != null && (s = i.gradFunc), s != null && (o.gradient = (u) => (u = u.map((l, c) => {
if (l == null) {
let p = n[c], d = ep(p.size, p.dtype);
return this.makeTensor(d, p.shape, p.dtype);
}
return l;
}), s(u.length > 1 ? u : u[0], r, a))), this.state.activeTape.push(o);
}
keep(e) {
return e.kept = true, e;
}
startTape() {
this.state.gradientDepth === 0 && (this.state.activeTape = []), this.state.gradientDepth++;
}
endTape() {
this.state.gradientDepth--;
}
startScope(e) {
let t = { track: [], name: "unnamed scope", id: this.state.nextScopeId++ };
e && (t.name = e), this.state.scopeStack.push(t), this.state.activeScope = t;
}
endScope(e) {
let t = Gg(e), n = new Set(t.map((r) => r.id));
for (let r = 0; r < this.state.activeScope.track.length; r++) {
let a = this.state.activeScope.track[r];
!a.kept && !n.has(a.id) && a.dispose();
}
let s = this.state.scopeStack.pop();
this.state.activeScope = this.state.scopeStack.length === 0 ? null : this.state.scopeStack[this.state.scopeStack.length - 1], t.forEach((r) => {
!r.kept && r.scopeId === s.id && this.track(r);
});
}
gradients(e, t, n, s = false) {
if (O(t.length > 0, () => "gradients() received an empty list of xs."), n != null && n.dtype !== "float32")
throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);
let r = this.scopedRun(() => this.startTape(), () => this.endTape(), () => this.tidy("forward", e));
O(r instanceof et, () => "The result y returned by f() must be a tensor.");
let a = l_(this.state.activeTape, t, r);
if (!s && a.length === 0 && t.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", () => {
let o = {};
o[r.id] = n == null ? k_(r.shape) : n, c_(o, a, (u) => this.tidy(u), S_);
let i = t.map((u) => o[u.id]);
return this.state.gradientDepth === 0 && (this.state.activeTape.forEach((u) => {
for (let l of u.saved)
l.dispose();
}), this.state.activeTape = null), { value: r, grads: i };
});
}
customGrad(e) {
return O(fr(e), () => "The f passed in customGrad(f) must be a function."), (...t) => {
O(t.every((o) => o instanceof et), () => "The args passed in customGrad(f)(x1, x2,...) must all be tensors");
let n, s = {};
t.forEach((o, i) => {
s[i] = o;
});
let r = (o, i) => (n = e(...t, i), O(n.value instanceof et, () => "The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"), O(fr(n.gradFunc), () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."), n.value), a = (o, i) => {
let u = n.gradFunc(o, i), l = Array.isArray(u) ? u : [u];
O(l.length === t.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(...)."), O(l.every((p) => p instanceof et), () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");
let c = {};
return l.forEach((p, d) => {
c[d] = () => p;
}), c;
};
return this.runKernelFunc({ forwardFunc: r, backwardsFunc: a, inputs: s });
};
}
readSync(e) {
return this.state.tensorInfo.get(e).backend.readSync(e);
}
read(e) {
return this.state.tensorInfo.get(e).backend.read(e);
}
readToGPU(e, t) {
return this.state.tensorInfo.get(e).backend.readToGPU(e, t);
}
async time(e) {
let t = ju(), n = await this.backend.time(e);
return n.wallMs = ju() - t, n;
}
track(e) {
return this.state.activeScope != null && (e.scopeId = this.state.activeScope.id, this.state.activeScope.track.push(e)), e;
}
get registeredVariables() {
return this.state.registeredVariables;
}
reset() {
this.pendingBackendInitId++, this.state.dispose(), this.ENV.reset(), this.state = new bx();
for (let e in this.registry)
this.disposeRegisteredKernels(e), this.registry[e].dispose(), delete this.registry[e];
this.backendName = null, this.backendInstance = null, this.pendingBackendInit = null;
}
};
var Hg = pm;
Hg.nextTensorId = 0;
Hg.nextVariableId = 0;
function k_(e) {
let t = hg(dt(e), "float32");
return z.makeTensor(t, e, "float32");
}
function Ck() {
let e = mk();
if (e._tfengine == null) {
let t = new V$(e);
e._tfengine = new Hg(t);
}
return H$(e._tfengine.ENV), f_(() => e._tfengine), e._tfengine;
}
var z = Ck();
function S_(e, t) {
let n = { a: e, b: t };
return z.runKernel(Cr, n);
}
var vp = {};
Ee(vp, { isBrowser: () => Nk, isMobile: () => N_, mockIsMobile: () => C_ });
function I_() {
return typeof navigator != "undefined" && navigator != null;
}
var hm;
function C_(e) {
hm = e;
}
function N_(e) {
if (hm !== void 0)
return hm;
if (e || I_()) {
if (e || (e = navigator), e.product === "ReactNative")
return true;
let t = e.userAgent || e.vendor || (typeof window != "undefined" ? window.opera : "");
if (!t) {
let n = e;
return n.userAgentData && n.userAgentData.mobile;
}
return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0, 4));
}
return false;
}
function Nk() {
return typeof window != "undefined" && window.document != null || typeof WorkerGlobalScope != "undefined";
}
var Vn = K();
Vn.registerFlag("DEBUG", () => false, (e) => {
e && 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.");
});
Vn.registerFlag("IS_BROWSER", () => Nk());
Vn.registerFlag("IS_NODE", () => typeof process != "undefined" && typeof process.versions != "undefined" && typeof process.versions.node != "undefined");
Vn.registerFlag("IS_CHROME", () => typeof navigator != "undefined" && navigator != null && navigator.userAgent != null && /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor));
Vn.registerFlag("PROD", () => false);
Vn.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY", () => Vn.getBool("DEBUG"));
Vn.registerFlag("DEPRECATION_WARNINGS_ENABLED", () => true);
Vn.registerFlag("IS_TEST", () => false);
Vn.registerFlag("CHECK_COMPUTATION_FOR_ERRORS", () => true);
Vn.registerFlag("WRAP_TO_IMAGEBITMAP", () => false);
Vn.registerFlag("ENGINE_COMPILE_ONLY", () => false);
Vn.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY", () => false);
function Rs(e, t) {
let n = e;
if (Qt(e))
return t === "string" ? [] : [e.length];
if (!Array.isArray(e))
return [];
let s = [];
for (; Array.isArray(n) || Qt(n) && t !== "string"; )
s.push(n.length), n = n[0];
return Array.isArray(e) && K().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY") && Tk(e, s, []), s;
}
function Tk(e, t, n) {
if (n = n || [], !Array.isArray(e) && !Qt(e)) {
O(t.length === 0, () => `Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);
return;
}
O(t.length > 0, () => `Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`), O(e.length === t[0], () => `Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);
let s = t.slice(1);
for (let r = 0; r < e.length; ++r)
Tk(e[r], s, n.concat(r));
}
function yx(e, t, n, s) {
if (e !== "string_or_numeric") {
if (e == null)
throw new Error("Expected dtype cannot be null.");
if (e !== "numeric" && e !== t || e === "numeric" && t === "string")
throw new Error(`Argument '${n}' passed to '${s}' must be ${e} tensor, but got ${t} tensor`);
}
}
function _(e, t, n, s = "numeric") {
if (e instanceof et)
return yx(s, e.dtype, t, n), e;
let r = Jd(e);
if (r !== "string" && ["bool", "int32", "float32"].indexOf(s) >= 0 && (r = s), yx(s, r, t, n), e == null || !Qt(e) && !Array.isArray(e) && typeof e != "number" && typeof e != "boolean" && typeof e != "string") {
let u = e == null ? "null" : e.constructor.name;
throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${u}'`);
}
let a = Rs(e, r);
!Qt(e) && !Array.isArray(e) && (e = [e]);
let i = r !== "string" ? bp(e, r) : aa(e, [], true);
return z.makeTensor(i, a, r);
}
function Ku(e, t, n, s = "numeric") {
if (!Array.isArray(e))
throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);
return e.map((a, o) => _(a, `${t}[${o}]`, n, s));
}
var T_ = "__op";
function M(e) {
let t = Object.keys(e);
if (t.length !== 1)
throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);
let n = t[0], s = e[n];
n.endsWith("_") && (n = n.substring(0, n.length - 1)), n = n + T_;
let r = (...a) => {
z.startScope(n);
try {
let o = s(...a);
return mg(o) && console.error("Cannot return a Promise inside of tidy."), z.endScope(o), o;
} catch (o) {
throw z.endScope(null), o;
}
};
return Object.defineProperty(r, "name", { value: n, configurable: true }), r;
}
function $_(e, t) {
let n = _(e, "real", "complex"), s = _(t, "imag", "complex");
hn(n.shape, s.shape, `real and imag shapes, ${n.shape} and ${s.shape}, must match in call to tf.complex().`);
let r = { real: n, imag: s };
return z.runKernel(np, r);
}
var mr = M({ complex_: $_ });
function $r(e, t, n, s) {
if (s == null && (s = Jd(e)), s === "complex64")
throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");
if (!Qt(e) && !Array.isArray(e) && typeof e != "number" && typeof e != "boolean" && typeof e != "string")
throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");
if (t != null) {
fg(t);
let r = dt(t), a = dt(n);
O(r === a, () => `Based on the provided shape, [${t}], the tensor should have ${r} values but has ${a}`);
for (let o = 0; o < n.length; ++o) {
let i = n[o], u = o === n.length - 1 ? i !== dt(t.slice(o)) : true;
O(n[o] === t[o] || !u, () => `Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `);
}
}
return !Qt(e) && !Array.isArray(e) && (e = [e]), t = t || n, e = s !== "string" ? bp(e, s) : aa(e, [], true), z.makeTensor(e, t, s);
}
function ms(e, t, n) {
let s = Rs(e, n);
return $r(e, t, s, n);
}
var fm = { float32: 4, float16: 2, int32: 4, uint16: 2, uint8: 1, bool: 1, complex64: 8 };
var Sd = 4;
async function __(e, t) {
let n = [], s = [], r = Array.isArray(e) ? e.map((o) => o.name) : Object.keys(e);
for (let o = 0; o < r.length; ++o) {
let i = r[o], u = Array.isArray(e) ? e[o].tensor : e[i];
if (u.dtype !== "float32" && u.dtype !== "int32" && u.dtype !== "bool" && u.dtype !== "string" && u.dtype !== "complex64")
throw new Error(`Unsupported dtype in weight '${i}': ${u.dtype}`);
let l = { name: i, shape: u.shape, dtype: u.dtype };
if (u.dtype === "string") {
let c = new Promise(async (p) => {
let d = await u.bytes(), h = d.reduce((g, b) => g + b.length, 0) + Sd * d.length, f = new Uint8Array(h), m = 0;
for (let g = 0; g < d.length; g++) {
let b = d[g], y = new Uint8Array(new Uint32Array([b.length]).buffer);
f.set(y, m), m += Sd, f.set(b, m), m += b.length;
}
p(f);
});
s.push(c);
} else
s.push(u.data());
t != null && (l.group = t), n.push(l);
}
let a = await Promise.all(s);
return { data: A_(a), specs: n };
}
function $k(e, t) {
let n = {}, s, r = 0;
for (let a of t) {
let o = a.name, i = a.dtype, u = a.shape, l = dt(u), c;
if ("quantization" in a) {
let p = a.quantization;
if (p.dtype === "uint8" || p.dtype === "uint16") {
if (!("min" in p && "scale" in p))
throw new Error(`Weight ${a.name} with quantization ${p.dtype} doesn't have corresponding metadata min and scale.`);
} else if (p.dtype === "float16") {
if (i !== "float32")
throw new Error(`Weight ${a.name} is quantized with ${p.dtype} which only supports weights of type float32 not ${i}.`);
} else
throw new Error(`Weight ${a.name} has unknown quantization dtype ${p.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);
let d = fm[p.dtype], h = e.slice(r, r + l * d), f = p.dtype === "uint8" ? new Uint8Array(h) : new Uint16Array(h);
if (i === "float32")
if (p.dtype === "uint8" || p.dtype === "uint16") {
c = new Float32Array(f.length);
for (let m = 0; m < f.length; m++) {
let g = f[m];
c[m] = g * p.scale + p.min;
}
} else if (p.dtype === "float16")
s === void 0 && (s = P_()), c = s(f);
else
throw new Error(`Unsupported quantization type ${p.dtype} for weight type float32.`);
else if (i === "int32") {
if (p.dtype !== "uint8" && p.dtype !== "uint16")
throw new Error(`Unsupported quantization type ${p.dtype} for weight type int32.`);
c = new Int32Array(f.length);
for (let m = 0; m < f.length; m++) {
let g = f[m];
c[m] = Math.round(g * p.scale + p.min);
}
} else
throw new Error(`Unsupported dtype in weight '${o}': ${i}`);
r += l * d;
} else if (i === "string") {
let p = dt(a.shape);
c = [];
for (let d = 0; d < p; d++) {
let h = new Uint32Array(e.slice(r, r + Sd))[0];
r += Sd;
let f = new Uint8Array(e.slice(r, r + h));
c.push(f), r += h;
}
} else {
let p = fm[i], d = e.slice(r, r + l * p);
if (i === "float32")
c = new Float32Array(d);
else if (i === "int32")
c = new Int32Array(d);
else if (i === "bool")
c = new Uint8Array(d);
else if (i === "complex64") {
c = new Float32Array(d);
let h = new Float32Array(c.length / 2), f = new Float32Array(c.length / 2);
for (let b = 0; b < h.length; b++)
h[b] = c[b * 2], f[b] = c[b * 2 + 1];
let m = ms(h, u, "float32"), g = ms(f, u, "float32");
n[o] = mr(m, g), m.dispose(), g.dispose();
} else
throw new Error(`Unsupported dtype in weight '${o}': ${i}`);
r += l * p;
}
i !== "complex64" && (n[o] = ms(c, u, i));
}
return n;
}
function A_(e) {
if (e === null)
throw new Error(`Invalid input value: ${JSON.stringify(e)}`);
let t = 0, n = [];
e.forEach((a) => {
if (t += a.byteLength, n.push(a.byteLength === a.buffer.byteLength ? a : new a.constructor(a)), !(a instanceof Float32Array || a instanceof Int32Array || a instanceof Uint8Array))
throw new Error(`Unsupported TypedArray subtype: ${a.constructor.name}`);
});
let s = new Uint8Array(t), r = 0;
return n.forEach((a) => {
s.set(new Uint8Array(a.buffer), r), r += a.byteLength;
}), s.buffer;
}
var qg = typeof Buffer != "undefined" && (typeof Blob == "undefined" || typeof atob == "undefined" || typeof btoa == "undefined");
function vx(e) {
return qg ? Buffer.byteLength(e) : new Blob([e]).size;
}
function E_(e) {
if (qg)
return Buffer.from(e).toString("base64");
let t = new Uint8Array(e), n = "";
for (let s = 0, r = t.length; s < r; s++)
n += String.fromCharCode(t[s]);
return btoa(n);
}
function R_(e) {
if (qg) {
let s = Buffer.from(e, "base64");
return s.buffer.slice(s.byteOffset, s.byteOffset + s.byteLength);
}
let t = atob(e), n = new Uint8Array(t.length);
for (let s = 0; s < t.length; ++s)
n.set([t.charCodeAt(s)], s);
return n.buffer;
}
function jg(e) {
if (e.length === 1)
return e[0];
let t = 0;
e.forEach((r) => {
t += r.byteLength;
});
let n = new Uint8Array(t), s = 0;
return e.forEach((r) => {
n.set(new Uint8Array(r), s), s += r.byteLength;
}), n.buffer;
}
function xx(e) {
let t = "/";
for (e = e.trim(); e.endsWith(t); )
e = e.slice(0, e.length - 1);
let n = e.split(t);
return n[n.length - 1];
}
function _k(e, t) {
let n = { modelTopology: e.modelTopology, format: e.format, generatedBy: e.generatedBy, convertedBy: e.convertedBy, weightsManifest: t };
return e.signature != null && (n.signature = e.signature), e.userDefinedMetadata != null && (n.userDefinedMetadata = e.userDefinedMetadata), e.modelInitializer != null && (n.modelInitializer = e.modelInitializer), e.trainingConfig != null && (n.trainingConfig = e.trainingConfig), n;
}
async function Kg(e, t) {
let n = { modelTopology: e.modelTopology, format: e.format, generatedBy: e.generatedBy, convertedBy: e.convertedBy };
if (e.trainingConfig != null && (n.trainingConfig = e.trainingConfig), e.weightsManifest != null) {
let [s, r] = await t(e.weightsManifest);
n.weightSpecs = s, n.weightData = r;
}
return e.signature != null && (n.signature = e.signature), e.userDefinedMetadata != null && (n.userDefinedMetadata = e.userDefinedMetadata), e.modelInitializer != null && (n.modelInitializer = e.modelInitializer), n;
}
function Ll(e) {
if (e.modelTopology instanceof ArrayBuffer)
throw new Error("Expected JSON model topology, received ArrayBuffer.");
return { dateSaved: new Date(), modelTopologyType: "JSON", modelTopologyBytes: e.modelTopology == null ? 0 : vx(JSON.stringify(e.modelTopology)), weightSpecsBytes: e.weightSpecs == null ? 0 : vx(JSON.stringify(e.weightSpecs)), weightDataBytes: e.weightData == null ? 0 : e.weightData.byteLength };
}
function D_() {
let e = (n) => {
let s = n << 13, r = 0;
for (; (s & 8388608) === 0; )
r -= 8388608, s <<= 1;
return s &= -8388609, r += 947912704, s | r;
}, t = new Uint32Array(2048);
t[0] = 0;
for (let n = 1; n < 1024; n++)
t[n] = e(n);
for (let n = 1024; n < 2048; n++)
t[n] = 939524096 + (n - 1024 << 13);
return t;
}
function F_() {
let e = new Uint32Array(64);
e[0] = 0, e[31] = 1199570944, e[32] = 2147483648, e[63] = 3347054592;
for (let t = 1; t < 31; t++)
e[t] = t << 23;
for (let t = 33; t < 63; t++)
e[t] = 2147483648 + (t - 32 << 23);
return e;
}
function O_() {
let e = new Uint32Array(64);
for (let t = 0; t < 64; t++)
e[t] = 1024;
return e[0] = e[32] = 0, e;
}
function P_() {
let e = D_(), t = F_(), n = O_();
return (s) => {
let r = new ArrayBuffer(4 * s.length), a = new Uint32Array(r);
for (let o = 0; o < s.length; o++) {
let i = s[o], u = e[n[i >> 10] + (i & 1023)] + t[i >> 10];
a[o] = u;
}
return new Float32Array(r);
};
}
var wt = class {
constructor() {
this.saveRouters = [], this.loadRouters = [];
}
static getInstance() {
return wt.instance == null && (wt.instance = new wt()), wt.instance;
}
static registerSaveRouter(e) {
wt.getInstance().saveRouters.push(e);
}
static registerLoadRouter(e) {
wt.getInstance().loadRouters.push(e);
}
static getSaveHandlers(e) {
return wt.getHandlers(e, "save");
}
static getLoadHandlers(e, t) {
return wt.getHandlers(e, "load", t);
}
static getHandlers(e, t, n) {
let s = [];
return (t === "load" ? wt.getInstance().loadRouters : wt.getInstance().saveRouters).forEach((a) => {
let o = a(e, n);
o !== null && s.push(o);
}), s;
}
};
var z_ = (e) => wt.registerSaveRouter(e);
var L_ = (e) => wt.registerLoadRouter(e);
var M_ = (e) => wt.getSaveHandlers(e);
var B_ = (e, t) => wt.getLoadHandlers(e, t);
var mm = "tensorflowjs";
var gm = 1;
var Zr = "models_store";
var ir = "model_info_store";
function Ak() {
if (!K().getBool("IS_BROWSER"))
throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");
let e = typeof window == "undefined" ? self : window, t = e.indexedDB || e.mozIndexedDB || e.webkitIndexedDB || e.msIndexedDB || e.shimIndexedDB;
if (t == null)
throw new Error("The current browser does not appear to support IndexedDB.");
return t;
}
function bm(e) {
let t = e.result;
t.createObjectStore(Zr, { keyPath: "modelPath" }), t.createObjectStore(ir, { keyPath: "modelPath" });
}
var la = class {
constructor(e) {
if (this.indexedDB = Ak(), e == null || !e)
throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");
this.modelPath = e;
}
async save(e) {
if (e.modelTopology instanceof ArrayBuffer)
throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");
return this.databaseAction(this.modelPath, e);
}
async load() {
return this.databaseAction(this.modelPath);
}
databaseAction(e, t) {
return new Promise((n, s) => {
let r = this.indexedDB.open(mm, gm);
r.onupgradeneeded = () => bm(r), r.onsuccess = () => {
let a = r.result;
if (t == null) {
let o = a.transaction(Zr, "readonly"), u = o.objectStore(Zr).get(this.modelPath);
u.onsuccess = () => {
if (u.result == null)
return a.close(), s(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));
n(u.result.modelArtifacts);
}, u.onerror = (l) => (a.close(), s(u.error)), o.oncomplete = () => a.close();
} else {
let o = Ll(t), i = a.transaction(ir, "readwrite"), u = i.objectStore(ir), l = u.put({ modelPath: this.modelPath, modelArtifactsInfo: o }), c;
l.onsuccess = () => {
c = a.transaction(Zr, "readwrite");
let d = c.objectStore(Zr).put({ modelPath: this.modelPath, modelArtifacts: t, modelArtifactsInfo: o });
d.onsuccess = () => n({ modelArtifactsInfo: o }), d.onerror = (h) => {
u = i.objectStore(ir);
let f = u.delete(this.modelPath);
f.onsuccess = () => (a.close(), s(d.error)), f.onerror = (m) => (a.close(), s(d.error));
};
}, l.onerror = (p) => (a.close(), s(l.error)), i.oncomplete = () => {
c == null ? a.close() : c.oncomplete = () => a.close();
};
}
}, r.onerror = (a) => s(r.error);
});
}
};
la.URL_SCHEME = "indexeddb://";
var Ek = (e) => K().getBool("IS_BROWSER") && !Array.isArray(e) && e.startsWith(la.URL_SCHEME) ? V_(e.slice(la.URL_SCHEME.length)) : null;
wt.registerSaveRouter(Ek);
wt.registerLoadRouter(Ek);
function V_(e) {
return new la(e);
}
function W_(e) {
return e.startsWith(la.URL_SCHEME) ? e.slice(la.URL_SCHEME.length) : e;
}
var U_ = class {
constructor() {
this.indexedDB = Ak();
}
async listModels() {
return new Promise((e, t) => {
let n = this.indexedDB.open(mm, gm);
n.onupgradeneeded = () => bm(n), n.onsuccess = () => {
let s = n.result, r = s.transaction(ir, "readonly"), o = r.objectStore(ir).getAll();
o.onsuccess = () => {
let i = {};
for (let u of o.result)
i[u.modelPath] = u.modelArtifactsInfo;
e(i);
}, o.onerror = (i) => (s.close(), t(o.error)), r.oncomplete = () => s.close();
}, n.onerror = (s) => t(n.error);
});
}
async removeModel(e) {
return e = W_(e), new Promise((t, n) => {
let s = this.indexedDB.open(mm, gm);
s.onupgradeneeded = () => bm(s), s.onsuccess = () => {
let r = s.result, a = r.transaction(ir, "readwrite"), o = a.objectStore(ir), i = o.get(e), u;
i.onsuccess = () => {
if (i.result == null)
return r.close(), n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));
{
let l = o.delete(e), c = () => {
u = r.transaction(Zr, "readwrite");
let d = u.objectStore(Zr).delete(e);
d.onsuccess = () => t(i.result.modelArtifactsInfo), d.onerror = (h) => n(i.error);
};
l.onsuccess = c, l.onerror = (p) => (c(), r.close(), n(i.error));
}
}, i.onerror = (l) => (r.close(), n(i.error)), a.oncomplete = () => {
u == null ? r.close() : u.oncomplete = () => r.close();
};
}, s.onerror = (r) => n(s.error);
});
}
};
var Us = "/";
var qo = "tensorflowjs_models";
var Rk = "info";
var G_ = "model_topology";
var H_ = "weight_specs";
var q_ = "weight_data";
var j_ = "model_metadata";
function Dk(e) {
return { info: [qo, e, Rk].join(Us), topology: [qo, e, G_].join(Us), weightSpecs: [qo, e, H_].join(Us), weightData: [qo, e, q_].join(Us), modelMetadata: [qo, e, j_].join(Us) };
}
function Fk(e) {
for (let t of Object.values(e))
window.localStorage.removeItem(t);
}
function K_(e) {
let t = e.split(Us);
if (t.length < 3)
throw new Error(`Invalid key format: ${e}`);
return t.slice(1, t.length - 1).join(Us);
}
function X_(e) {
return e.startsWith(ca.URL_SCHEME) ? e.slice(ca.URL_SCHEME.length) : e;
}
var ca = class {
constructor(e) {
if (!K().getBool("IS_BROWSER") || typeof window == "undefined" || typeof window.localStorage == "undefined")
throw new Error("The current environment does not support local storage.");
if (this.LS = window.localStorage, e == null || !e)
throw new Error("For local storage, modelPath must not be null, undefined or empty.");
this.modelPath = e, this.keys = Dk(this.modelPath);
}
async save(e) {
if (e.modelTopology instanceof ArrayBuffer)
throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");
{
let t = JSON.stringify(e.modelTopology), n = JSON.stringify(e.weightSpecs), s = Ll(e);
try {
this.LS.setItem(this.keys.info, JSON.stringify(s)), this.LS.setItem(this.keys.topology, t), this.LS.setItem(this.keys.weightSpecs, n), this.LS.setItem(this.keys.weightData, E_(e.weightData));
let r = { format: e.format, generatedBy: e.generatedBy, convertedBy: e.convertedBy, signature: e.signature != null ? e.signature : void 0, userDefinedMetadata: e.userDefinedMetadata != null ? e.userDefinedMetadata : void 0, modelInitializer: e.modelInitializer != null ? e.modelInitializer : void 0, trainingConfig: e.trainingConfig != null ? e.trainingConfig : void 0 };
return this.LS.setItem(this.keys.modelMetadata, JSON.stringify(r)), { modelArtifactsInfo: s };
} catch (r) {
throw Fk(this.keys), new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${s.modelTopologyBytes}, weightSpecsBytes=${s.weightSpecsBytes}, weightDataBytes=${s.weightDataBytes}.`);
}
}
}
async load() {
let e = JSON.parse(this.LS.getItem(this.keys.info));
if (e == null)
throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);
if (e.modelTopologyType !== "JSON")
throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");
let t = {}, n = JSON.parse(this.LS.getItem(this.keys.topology));
if (n == null)
throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);
t.modelTopology = n;
let s = JSON.parse(this.LS.getItem(this.keys.weightSpecs));
if (s == null)
throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);
t.weightSpecs = s;
let r = this.LS.getItem(this.keys.modelMetadata);
if (r != null) {
let o = JSON.parse(r);
t.format = o.format, t.generatedBy = o.generatedBy, t.convertedBy = o.convertedBy, o.signature != null && (t.signature = o.signature), o.userDefinedMetadata != null && (t.userDefinedMetadata = o.userDefinedMetadata), o.modelInitializer != null && (t.modelInitializer = o.modelInitializer), o.trainingConfig != null && (t.trainingConfig = o.trainingConfig);
}
let a = this.LS.getItem(this.keys.weightData);
if (a == null)
throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);
return t.weightData = R_(a), t;
}
};
ca.URL_SCHEME = "localstorage://";
var Ok = (e) => K().getBool("IS_BROWSER") && !Array.isArray(e) && e.startsWith(ca.URL_SCHEME) ? Y_(e.slice(ca.URL_SCHEME.length)) : null;
wt.registerSaveRouter(Ok);
wt.registerLoadRouter(Ok);
function Y_(e) {
return new ca(e);
}
var Q_ = class {
constructor() {
O(K().getBool("IS_BROWSER"), () => "Current environment is not a web browser"), O(typeof window == "undefined" || typeof window.localStorage != "undefined", () => "Current browser does not appear to support localStorage"), this.LS = window.localStorage;
}
async listModels() {
let e = {}, t = qo + Us, n = Us + Rk;
for (let s = 0; s < this.LS.length; ++s) {
let r = this.LS.key(s);
if (r.startsWith(t) && r.endsWith(n)) {
let a = K_(r);
e[a] = JSON.parse(this.LS.getItem(r));
}
}
return e;
}
async removeModel(e) {
e = X_(e);
let t = Dk(e);
if (this.LS.getItem(t.info) == null)
throw new Error(`Cannot find model at path '${e}'`);
let n = JSON.parse(this.LS.getItem(t.info));
return Fk(t), n;
}
};
var Yo = "://";
var zn = class {
constructor() {
this.managers = {};
}
static getInstance() {
return zn.instance == null && (zn.instance = new zn()), zn.instance;
}
static registerManager(e, t) {
O(e != null, () => "scheme must not be undefined or null."), e.endsWith(Yo) && (e = e.slice(0, e.indexOf(Yo))), O(e.length > 0, () => "scheme must not be an empty string.");
let n = zn.getInstance();
O(n.managers[e] == null, () => `A model store manager is already registered for scheme '${e}'.`), n.managers[e] = t;
}
static getManager(e) {
let t = this.getInstance().managers[e];
if (t == null)
throw new Error(`Cannot find model manager for scheme '${e}'`);
return t;
}
static getSchemes() {
return Object.keys(this.getInstance().managers);
}
};
function od(e) {
if (e.indexOf(Yo) === -1)
throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${zn.getSchemes().join(",")}`);
return { scheme: e.split(Yo)[0], path: e.split(Yo)[1] };
}
async function Pk(e, t, n = false) {
O(e !== t, () => `Old path and new path are the same: '${e}'`);
let s = wt.getLoadHandlers(e);
O(s.length > 0, () => `Copying failed because no load handler is found for source URL ${e}.`), O(s.length < 2, () => `Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`);
let r = s[0], a = wt.getSaveHandlers(t);
O(a.length > 0, () => `Copying failed because no save handler is found for destination URL ${t}.`), O(a.length < 2, () => `Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`);
let o = a[0], i = od(e).scheme, u = od(e).path, l = i === od(e).scheme, c = await r.load();
n && l && await zn.getManager(i).removeModel(u);
let p = await o.save(c);
return n && !l && await zn.getManager(i).removeModel(u), p.modelArtifactsInfo;
}
async function Z_() {
let e = zn.getSchemes(), t = {};
for (let n of e) {
let s = await zn.getManager(n).listModels();
for (let r in s) {
let a = n + Yo + r;
t[a] = s[r];
}
}
return t;
}
async function J_(e) {
let t = od(e);
return zn.getManager(t.scheme).removeModel(t.path);
}
async function eA(e, t) {
return Pk(e, t, false);
}
async function tA(e, t) {
return Pk(e, t, true);
}
var nA = class {
fetch(e, t) {
return fetch(e, t);
}
now() {
return performance.now();
}
encode(e, t) {
if (t !== "utf-8" && t !== "utf8")
throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);
return this.textEncoder == null && (this.textEncoder = new TextEncoder()), this.textEncoder.encode(e);
}
decode(e, t) {
return new TextDecoder(t).decode(e);
}
};
if (K().get("IS_BROWSER")) {
K().setPlatform("browser", new nA());
try {
zn.registerManager(ca.URL_SCHEME, new Q_());
} catch (e) {
}
try {
zn.registerManager(la.URL_SCHEME, new U_());
} catch (e) {
}
}
var sA = { importFetch: () => l$() };
var Kf;
var rA = class {
constructor() {
this.util = c$(), this.textEncoder = new this.util.TextEncoder();
}
fetch(e, t) {
return K().global.fetch != null ? K().global.fetch(e, t) : (Kf == null && (Kf = sA.importFetch()), Kf(e, t));
}
now() {
let e = process.hrtime();
return e[0] * 1e3 + e[1] / 1e6;
}
encode(e, t) {
if (t !== "utf-8" && t !== "utf8")
throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);
return this.textEncoder.encode(e);
}
decode(e, t) {
return e.length === 0 ? "" : new this.util.TextDecoder(t).decode(e);
}
};
K().get("IS_NODE") && !K().get("IS_BROWSER") && K().setPlatform("node", new rA());
function Ae(e, t = "float32", n) {
return t = t || "float32", fg(e), new Vt(e, t, n);
}
function aA(e, t) {
let n = _(e, "x", "cast");
if (!lk(t))
throw new Error(`Failed to cast to unknown dtype ${t}`);
if (t === "string" && n.dtype !== "string" || t !== "string" && n.dtype === "string")
throw new Error("Only strings can be casted to strings");
let s = { x: n }, r = { dtype: t };
return z.runKernel(Ta, s, r);
}
var le = M({ cast_: aA });
function oA(e) {
let n = { x: _(e, "x", "clone", "string_or_numeric") };
return z.runKernel(Wa, n);
}
var lr = M({ clone_: oA });
function iA(e, t = false) {
console.log(e.toString(t));
}
Ck();
var uA = { buffer: Ae, cast: le, clone: lr, print: iA };
m_(uA);
var An = {};
Ee(An, { browserFiles: () => mA, browserHTTPRequest: () => xA, concatenateArrayBuffers: () => jg, copyModel: () => eA, decodeWeights: () => $k, encodeWeights: () => __, fromMemory: () => kA, fromMemorySync: () => Vk, getLoadHandlers: () => B_, getModelArtifactsForJSON: () => Kg, getModelArtifactsInfoForJSON: () => Ll, getSaveHandlers: () => M_, http: () => Yg, isHTTPScheme: () => vm, listModels: () => Z_, loadWeights: () => gA, moveModel: () => tA, registerLoadRouter: () => L_, registerSaveRouter: () => z_, removeModel: () => J_, weightsLoaderFactory: () => Lk, withSaveHandler: () => SA, withSaveHandlerSync: () => IA });
var lA = "model";
var cA = ".json";
var dA = ".weights.bin";
function wx(e) {
return new Promise((t) => setTimeout(t)).then(e);
}
var ym = class {
constructor(e) {
if (!K().getBool("IS_BROWSER"))
throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");
e.startsWith(ym.URL_SCHEME) && (e = e.slice(ym.URL_SCHEME.length)), (e == null || e.length === 0) && (e = lA), this.modelJsonFileName = e + cA, this.weightDataFileName = e + dA;
}
async save(e) {
if (typeof document == "undefined")
throw new Error("Browser downloads are not supported in this environment since `document` is not present");
let t = window.URL.createObjectURL(new Blob([e.weightData], { type: "application/octet-stream" }));
if (e.modelTopology instanceof ArrayBuffer)
throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");
{
let n = [{ paths: ["./" + this.weightDataFileName], weights: e.weightSpecs }], s = _k(e, n), r = window.URL.createObjectURL(new Blob([JSON.stringify(s)], { type: "application/json" })), a = this.modelJsonAnchor == null ? document.createElement("a") : this.modelJsonAnchor;
if (a.download = this.modelJsonFileName, a.href = r, await wx(() => a.dispatchEvent(new MouseEvent("click"))), e.weightData != null) {
let o = this.weightDataAnchor == null ? document.createElement("a") : this.weightDataAnchor;
o.download = this.weightDataFileName, o.href = t, await wx(() => o.dispatchEvent(new MouseEvent("click")));
}
return { modelArtifactsInfo: Ll(e) };
}
}
};
var Id = ym;
Id.URL_SCHEME = "downloads://";
var pA = class {
constructor(e) {
if (e == null || e.length < 1)
throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);
this.jsonFile = e[0], this.weightsFiles = e.slice(1);
}
async load() {
return new Promise((e, t) => {
let n = new FileReader();
n.onload = (s) => {
let r = JSON.parse(s.target.result), a = r.modelTopology;
if (a == null) {
t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));
return;
}
if (r.weightsManifest == null) {
t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));
return;
}
if (this.weightsFiles.length === 0) {
e({ modelTopology: a });
return;
}
let i = Kg(r, (u) => this.loadWeights(u));
e(i);
}, n.onerror = (s) => t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`), n.readAsText(this.jsonFile);
});
}
loadWeights(e) {
let t = [], n = [];
for (let a of e)
t.push(...a.weights), n.push(...a.paths);
let s = this.checkManifestAndWeightFiles(e), r = n.map((a) => this.loadWeightsFile(a, s[a]));
return Promise.all(r).then((a) => [t, jg(a)]);
}
loadWeightsFile(e, t) {
return new Promise((n, s) => {
let r = new FileReader();
r.onload = (a) => {
let o = a.target.result;
n(o);
}, r.onerror = (a) => s(`Failed to weights data from file of path '${e}'.`), r.readAsArrayBuffer(t);
});
}
checkManifestAndWeightFiles(e) {
let t = [], n = this.weightsFiles.map((r) => xx(r.name)), s = {};
for (let r of e)
r.paths.forEach((a) => {
let o = xx(a);
if (t.indexOf(o) !== -1)
throw new Error(`Duplicate file basename found in weights manifest: '${o}'`);
if (t.push(o), n.indexOf(o) === -1)
throw new Error(`Weight file with basename '${o}' is not provided.`);
s[a] = this.weightsFiles[n.indexOf(o)];
});
if (t.length !== this.weightsFiles.length)
throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);
return s;
}
};
var hA = (e) => K().getBool("IS_BROWSER") && !Array.isArray(e) && e.startsWith(Id.URL_SCHEME) ? fA(e.slice(Id.URL_SCHEME.length)) : null;
wt.registerSaveRouter(hA);
function fA(e = "model") {
return new Id(e);
}
function mA(e) {
return new pA(e);
}
function kx(e, t, n, s) {
o(e), n = n == null ? 0 : n, s = s == null ? 1 : s, i(n, s);
let r = 0, a = (u) => (u.then((l) => {
let c = n + ++r / e.length * (s - n);
return t(c), l;
}), u);
function o(u) {
O(u != null && Array.isArray(u) && u.length > 0, () => "promises must be a none empty array");
}
function i(u, l) {
O(u >= 0 && u <= 1, () => `Progress fraction must be in range [0, 1], but got startFraction ${u}`), O(l >= 0 && l <= 1, () => `Progress fraction must be in range [0, 1], but got endFraction ${l}`), O(l >= u, () => `startFraction must be no more than endFraction, but got startFraction ${u} and endFraction ${l}`);
}
return Promise.all(e.map(a));
}
async function zk(e, t) {
t == null && (t = {});
let n = t.fetchFunc == null ? K().platform.fetch : t.fetchFunc, s = e.map((p) => n(p, t.requestInit, { isBinary: true })), r = 0, a = 0.5, i = (t.onProgress == null ? await Promise.all(s) : await kx(s, t.onProgress, r, a)).map((p) => p.arrayBuffer()), u = 0.5, l = 1;
return t.onProgress == null ? await Promise.all(i) : await kx(i, t.onProgress, u, l);
}
async function gA(e, t = "", n, s) {
return Lk((o) => zk(o, { requestInit: s }))(e, t, n);
}
function Lk(e) {
return async (t, n = "", s) => {
let r = t.map(() => false), a = {}, o = s != null ? s.map(() => false) : [], i = [];
if (t.forEach((h, f) => {
let m = 0;
h.weights.forEach((g) => {
let b = "quantization" in g ? g.quantization.dtype : g.dtype, y = fm[b] * dt(g.shape), v = () => {
r[f] = true, a[f] == null && (a[f] = []), a[f].push({ manifestEntry: g, groupOffset: m, sizeBytes: y });
};
s != null ? s.forEach((x, k) => {
x === g.name && (v(), o[k] = true);
}) : v(), i.push(g.name), m += y;
});
}), !o.every((h) => h)) {
let h = s.filter((f, m) => !o[m]);
throw new Error(`Could not find weights in manifest with names: ${h.join(", ")}.
Manifest JSON has weights with names: ${i.join(", ")}.`);
}
let u = r.reduce((h, f, m) => (f && h.push(m), h), []), l = [];
u.forEach((h) => {
t[h].paths.forEach((f) => {
let m = n + (n.endsWith("/") ? "" : "/") + f;
l.push(m);
});
});
let c = await e(l), p = {}, d = 0;
return u.forEach((h) => {
let f = t[h].paths.length, m = 0;
for (let x = 0; x < f; x++)
m += c[d + x].byteLength;
let g = new ArrayBuffer(m), b = new Uint8Array(g), y = 0;
for (let x = 0; x < f; x++) {
let k = new Uint8Array(c[d + x]);
b.set(k, y), y += k.byteLength;
}
a[h].forEach((x) => {
let k = g.slice(x.groupOffset, x.groupOffset + x.sizeBytes), I = $k(k, [x.manifestEntry]);
for (let $ in I)
p[$] = I[$];
}), d += f;
}), p;
};
}
var bA = "application/octet-stream";
var yA = "application/json";
var Xg = class {
constructor(e, t) {
if (this.DEFAULT_METHOD = "POST", t == null && (t = {}), this.weightPathPrefix = t.weightPathPrefix, this.onProgress = t.onProgress, this.weightUrlConverter = t.weightUrlConverter, t.fetchFunc != null ? (O(typeof t.fetchFunc == "function", () => "Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"), this.fetch = t.fetchFunc) : this.fetch = K().platform.fetch, O(e != null && e.length > 0, () => "URL path for http must not be null, undefined or empty."), Array.isArray(e) && O(e.length === 2, () => `URL paths for http must have a length of 2, (actual length is ${e.length}).`), this.path = e, t.requestInit != null && t.requestInit.body != null)
throw new Error("requestInit is expected to have no pre-existing body, but has one.");
this.requestInit = t.requestInit || {};
}
async save(e) {
if (e.modelTopology instanceof ArrayBuffer)
throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");
let t = Object.assign({ method: this.DEFAULT_METHOD }, this.requestInit);
t.body = new FormData();
let n = [{ paths: ["./model.weights.bin"], weights: e.weightSpecs }], s = _k(e, n);
t.body.append("model.json", new Blob([JSON.stringify(s)], { type: yA }), "model.json"), e.weightData != null && t.body.append("model.weights.bin", new Blob([e.weightData], { type: bA }), "model.weights.bin");
let r = await this.fetch(this.path, t);
if (r.ok)
return { modelArtifactsInfo: Ll(e), responses: [r] };
throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`);
}
async load() {
let e = await this.fetch(this.path, this.requestInit);
if (!e.ok)
throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);
let t;
try {
t = await e.json();
} catch (r) {
let a = `Failed to parse model JSON of response from ${this.path}.`;
throw this.path.endsWith(".pb") ? a += " Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository." : a += " Please make sure the server is serving valid JSON for this request.", new Error(a);
}
let n = t.modelTopology, s = t.weightsManifest;
if (n == null && s == null)
throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);
return Kg(t, (r) => this.loadWeights(r));
}
async loadWeights(e) {
let t = Array.isArray(this.path) ? this.path[1] : this.path, [n, s] = vA(t), r = this.weightPathPrefix || n, a = [];
for (let l of e)
a.push(...l.weights);
let o = [], i = [];
for (let l of e)
for (let c of l.paths)
this.weightUrlConverter != null ? i.push(this.weightUrlConverter(c)) : o.push(r + c + s);
this.weightUrlConverter && o.push(...await Promise.all(i));
let u = await zk(o, { requestInit: this.requestInit, fetchFunc: this.fetch, onProgress: this.onProgress });
return [a, jg(u)];
}
};
Xg.URL_SCHEME_REGEX = /^https?:\/\//;
function vA(e) {
let t = e.lastIndexOf("/"), n = e.lastIndexOf("?"), s = e.substring(0, t), r = n > t ? e.substring(n) : "";
return [s + "/", r];
}
function vm(e) {
return e.match(Xg.URL_SCHEME_REGEX) != null;
}
var Mk = (e, t) => {
if (typeof fetch == "undefined" && (t == null || t.fetchFunc == null))
return null;
{
let n = true;
if (Array.isArray(e) ? n = e.every((s) => vm(s)) : n = vm(e), n)
return Yg(e, t);
}
return null;
};
wt.registerSaveRouter(Mk);
wt.registerLoadRouter(Mk);
function Yg(e, t) {
return new Xg(e, t);
}
function xA(e, t) {
return Yg(e, t);
}
var Xf = class {
constructor(e) {
this.modelArtifacts = e;
}
load() {
return this.modelArtifacts;
}
};
var Bk = class {
constructor(e) {
this.saveHandler = e;
}
save(e) {
return this.saveHandler(e);
}
};
var wA = class {
constructor(e) {
e.load && (this.load = () => Promise.resolve(e.load())), e.save && (this.save = (t) => Promise.resolve(e.save(t)));
}
};
function kA(e, t, n, s) {
let r = arguments;
return new wA(Vk(...r));
}
function Vk(e, t, n, s) {
return arguments.length === 1 ? e.modelTopology != null || e.weightSpecs != null ? new Xf(e) : (console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."), new Xf({ modelTopology: e })) : (console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."), new Xf({ modelTopology: e, weightSpecs: t, weightData: n, trainingConfig: s }));
}
function SA(e) {
return new Bk(e);
}
function IA(e) {
return new Bk(e);
}
var CA = {};
Ee(CA, { confusionMatrix: () => FA });
function NA(e, t, n = false, s = false) {
let r = _(e, "a", "matMul"), a = _(t, "b", "matMul");
[r, a] = xt(r, a);
let o = { a: r, b: a }, i = { transposeA: n, transposeB: s };
return z.runKernel(Na, o, i);
}
var We = M({ matMul_: NA });
function TA(e, t, n = 1, s = 0) {
if (t < 2)
throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);
let a = { indices: _(e, "indices", "oneHot", "int32") }, o = { depth: t, onValue: n, offValue: s };
return z.runKernel(Di, a, o);
}
var Cd = M({ oneHot_: TA });
function Epe() {
K().set("PROD", true);
}
function Rpe() {
K().set("DEBUG", true);
}
function Dpe() {
K().set("DEPRECATION_WARNINGS_ENABLED", false), console.warn("TensorFlow.js deprecation warnings have been disabled.");
}
function Wk(e) {
K().getBool("DEPRECATION_WARNINGS_ENABLED") && console.warn(e + " You can disable deprecation warnings with tf.disableDeprecationWarnings().");
}
g_(Wk);
function Fpe() {
z.disposeVariables();
}
function ds() {
return z;
}
function xm() {
return z.memory();
}
function Ope(e) {
return z.profile(e);
}
function q(e, t) {
return z.tidy(e, t);
}
function De(e) {
Gg(e).forEach((n) => n.dispose());
}
function qt(e) {
return z.keep(e);
}
function Ppe(e) {
return z.time(e);
}
function zpe(e) {
return z.setBackend(e);
}
function Lpe() {
return z.ready();
}
function Mpe() {
return z.backendName;
}
function Bpe(e) {
z.removeBackend(e);
}
function Vpe(e) {
return z.findBackend(e);
}
function Wpe(e) {
return z.findBackendFactory(e);
}
function xp(e, t, n = 1) {
return z.registerBackend(e, t, n);
}
function $A() {
return z.backend;
}
function Upe(e, t) {
K().setPlatform(e, t);
}
function _A(e) {
let n = { input: _(e, "input", "imag") };
return z.runKernel(ip, n);
}
var wp = M({ imag_: _A });
function AA(e) {
let n = { x: _(e, "x", "neg") };
return z.runKernel($i, n);
}
var vt = M({ neg_: AA });
function EA(e) {
let n = { input: _(e, "input", "real") };
return z.runKernel(cp, n);
}
var Xu = M({ real_: EA });
function RA(e, t, n) {
let s = _(e, "x", "transpose");
if (t == null && (t = s.shape.map((o, i) => i).reverse()), O(s.rank === t.length, () => `Error in transpose: rank of input ${s.rank} must match length of perm ${t}.`), t.forEach((o) => {
O(o >= 0 && o < s.rank, () => `All entries in 'perm' must be between 0 and ${s.rank - 1} but got ${t}`);
}), s.rank <= 1)
return s.clone();
let r = { x: s }, a = { perm: t };
return s.dtype === "complex64" ? q(() => {
let o = Xu(s), i = wp(s);
return o = z.runKernel(Hs, { x: o }, a), i = z.runKernel(Hs, { x: i }, a), n && (i = vt(i)), mr(o, i);
}) : z.runKernel(Hs, r, a);
}
var Ge = M({ transpose_: RA });
function DA(e, t, n) {
let s = _(e, "labels", "confusionMatrix"), r = _(t, "predictions", "confusionMatrix");
O(n == null || n > 0 && Number.isInteger(n), () => `If provided, numClasses must be a positive integer, but got ${n}`), O(s.rank === 1, () => `Expected the rank of labels to be 1, but got ${s.rank}`), O(r.rank === 1, () => `Expected the rank of predictions to be 1, but got ${r.rank}`), O(s.shape[0] === r.shape[0], () => `Mismatch in the number of examples: ${s.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`), O(n > 0 && Number.isInteger(n), () => `numClasses is required to be a positive integer, but got ${n}`);
let a = Cd(le(s, "int32"), n), o = Cd(le(r, "int32"), n), i = Ge(a), u = We(i, o);
return le(u, "int32");
}
var FA = M({ confusionMatrix_: DA });
var Qi = {};
Ee(Qi, { assertAndGetBroadcastShape: () => at, getBroadcastDims: () => Uk, getReductionAxes: () => _t });
function Uk(e, t) {
let n = e.length, s = [];
for (let r = 0; r < n; r++) {
let a = n - 1 - r, o = e[a] || 1;
(t[t.length - 1 - r] || 1) > 1 && o === 1 && s.unshift(a);
}
return s;
}
function _t(e, t) {
let n = [];
for (let s = 0; s < t.length; s++) {
let r = e[e.length - s - 1], a = t.length - s - 1, o = t[a];
(r == null || r === 1 && o > 1) && n.unshift(a);
}
return n;
}
function at(e, t) {
let n = [], s = Math.max(e.length, t.length);
for (let r = 0; r < s; r++) {
let a = e[e.length - r - 1];
a == null && (a = 1);
let o = t[t.length - r - 1];
if (o == null && (o = 1), a === 1)
n.unshift(o);
else if (o === 1)
n.unshift(a);
else if (a !== o) {
let i = `Operands could not be broadcast together with shapes ${e} and ${t}.`;
throw Error(i);
} else
n.unshift(a);
}
return n;
}
var Gk = {};
Ee(Gk, { fromPixels: () => WA, fromPixelsAsync: () => BA, toPixels: () => VA });
function OA(e, t, n) {
if (ka(e), t != null && t.length !== 3)
throw new Error("tensor3d() requires shape to have three numbers");
let s = Rs(e, n);
if (s.length !== 3 && s.length !== 1)
throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");
if (s.length === 1 && t == null)
throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");
return $r(e, t, s, n);
}
var Ur;
function Hk(e, t = 3) {
if (t > 4)
throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");
if (e == null)
throw new Error("pixels passed to tf.browser.fromPixels() can not be null");
let n = false, s = false, r = false, a = false, o = false, i = false;
if (e.data instanceof Uint8Array)
n = true;
else if (typeof ImageData != "undefined" && e instanceof ImageData)
s = true;
else if (typeof HTMLVideoElement != "undefined" && e instanceof HTMLVideoElement)
r = true;
else if (typeof HTMLImageElement != "undefined" && e instanceof HTMLImageElement)
a = true;
else if (e.getContext != null)
o = true;
else if (typeof ImageBitmap != "undefined" && e instanceof ImageBitmap)
i = true;
else
throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);
if (r && r && e.readyState < 2)
throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.");
if (lm(xd, z.backendName) != null) {
let f = { pixels: e }, m = { numChannels: t };
return z.runKernel(xd, f, m);
}
let [l, c] = r ? [e.videoWidth, e.videoHeight] : [e.width, e.height], p;
if (o)
p = e.getContext("2d").getImageData(0, 0, l, c).data;
else if (s || n)
p = e.data;
else if (a || r || i) {
if (Ur == null)
if (typeof document == "undefined")
if (typeof OffscreenCanvas != "undefined" && typeof OffscreenCanvasRenderingContext2D != "undefined")
Ur = new OffscreenCanvas(1, 1).getContext("2d");
else
throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");
else {
let f = K().getBool("CANVAS2D_WILL_READ_FREQUENTLY");
Ur = document.createElement("canvas").getContext("2d", { willReadFrequently: f });
}
Ur.canvas.width = l, Ur.canvas.height = c, Ur.drawImage(e, 0, 0, l, c), p = Ur.getImageData(0, 0, l, c).data;
}
let d;
if (t === 4)
d = new Int32Array(p);
else {
let f = l * c;
d = new Int32Array(f * t);
for (let m = 0; m < f; m++)
for (let g = 0; g < t; ++g)
d[m * t + g] = p[m * 4 + g];
}
return OA(d, [c, l, t], "int32");
}
function PA(e) {
return e != null && e.data instanceof Uint8Array;
}
function zA() {
return typeof window != "undefined" && typeof ImageBitmap != "undefined" && window.hasOwnProperty("createImageBitmap");
}
function LA(e) {
return e != null && e.width !== 0 && e.height !== 0;
}
function MA(e) {
return zA() && !(e instanceof ImageBitmap) && LA(e) && !PA(e);
}
async function BA(e, t = 3) {
let n = null;
if (K().getBool("WRAP_TO_IMAGEBITMAP") && MA(e)) {
let s;
try {
s = await createImageBitmap(e, { premultiplyAlpha: "none" });
} catch (r) {
s = null;
}
s != null && s.width === e.width && s.height === e.height ? n = s : n = e;
} else
n = e;
return Hk(n, t);
}
async function VA(e, t) {
let n = _(e, "img", "toPixels");
if (!(e instanceof et)) {
let l = n;
n = le(l, "int32"), l.dispose();
}
if (n.rank !== 2 && n.rank !== 3)
throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${n.rank}.`);
let [s, r] = n.shape.slice(0, 2), a = n.rank === 2 ? 1 : n.shape[2];
if (a > 4 || a === 2)
throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${a}`);
if (n.dtype !== "float32" && n.dtype !== "int32")
throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);
let o = await n.data(), i = n.dtype === "float32" ? 255 : 1, u = new Uint8ClampedArray(r * s * 4);
for (let l = 0; l < s * r; ++l) {
let c = [0, 0, 0, 255];
for (let d = 0; d < a; d++) {
let h = o[l * a + d];
if (n.dtype === "float32") {
if (h < 0 || h > 1)
throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${h}.`);
} else if (n.dtype === "int32" && (h < 0 || h > 255))
throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${h}.`);
a === 1 ? (c[0] = h * i, c[1] = h * i, c[2] = h * i) : c[d] = h * i;
}
let p = l * 4;
u[p + 0] = Math.round(c[0]), u[p + 1] = Math.round(c[1]), u[p + 2] = Math.round(c[2]), u[p + 3] = Math.round(c[3]);
}
if (t != null) {
t.width = r, t.height = s;
let l = t.getContext("2d"), c = new ImageData(u, r, s);
l.putImageData(c, 0, 0);
}
return n !== e && n.dispose(), u;
}
var WA = M({ fromPixels_: Hk });
var qk = {};
Ee(qk, { prepareAndValidate: () => jk });
function jk(e, t) {
let n = e.shape.length, s = t.shape.length;
if (n < 1)
throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);
if (s < 1)
throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${s}.`);
if (t.dtype !== "int32")
throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);
if (t.shape[s - 1] > n)
throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[s - 1]} vs. ${n}`);
if (dt(e.shape) === 0)
throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);
let r = t.shape, a = r[r.length - 1], o = 1;
for (let p = 0; p < r.length - 1; ++p)
o *= r[p];
let i = e.shape, u = r.slice();
u.pop();
let l = 1;
for (let p = a; p < n; ++p)
l *= i[p], u.push(i[p]);
let c = [...ci(e.shape).map((p) => p / l), 1].slice(0, a);
return [u, o, l, c];
}
var Kk = {};
Ee(Kk, { calculateShapes: () => Xk, validateInput: () => Zg, validateUpdateShape: () => Qg });
function Qg(e, t, n) {
let s = t.rank > 1 ? t.shape[t.rank - 1] : 1, r = t.rank > 1 ? t.rank - 1 : 1, a = `Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${s}, and batchDim: ${r}.`;
if (n.rank < r)
throw new Error(a + ` update.rank < ${r}. `);
if (e.length < s + (n.rank - r))
throw new Error(a + ` Output shape length < ${s + (n.rank - r)}`);
if (n.rank !== r + e.length - s)
throw new Error(a + ` update.rank != ${r + e.length - s}`);
for (let o = 0; o < r; ++o)
if (n.shape[o] !== t.shape[o])
throw new Error(a + ` updates.shape[${o}] (${n.shape[o]}) != indices.shape[${o}] (${t.shape[o]}).`);
for (let o = 0; o < n.rank - r; ++o)
if (n.shape[o + r] !== e[o + s])
throw new Error(a + ` updates.shape[${o + r}] (${n.shape[o + r]}) != shape[${o + r}] (${e[o + r]})`);
}
function Zg(e, t, n) {
if (t.rank < 1)
throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);
if (e.rank < 1)
throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);
if (t.dtype !== "int32")
throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);
if (n.length < 1)
throw new Error(`Output rank must be greater or equal to 1, but got shape: ${n}`);
if (n.length === 0) {
if (t.size === 0)
throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);
if (e.size === 0)
throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`);
}
Qg(n, t, e);
}
function Xk(e, t, n) {
let s = t.shape.length, r = s > 1 ? t.shape[s - 1] : 1, a = n.length, o = 1;
for (let p = r; p < a; ++p)
o *= n[p];
let i = r < 1 ? 1 : r, u = dt(t.shape) / i, l = [...ci(n.slice(0, r)), 1], c = dt(n);
return { sliceRank: r, numUpdates: u, sliceSize: o, strides: l, outputSize: c };
}
var kt = {};
Ee(kt, { assertParamsValid: () => GA, computeFlatOffset: () => XA, computeOutShape: () => qA, getNormalizedAxes: () => jA, isSliceContinous: () => KA, maskToAxes: () => HA, parseSliceParams: () => rS, sliceInfo: () => YA, startForAxis: () => nS, startIndicesWithElidedDims: () => Jk, stopForAxis: () => sS, stopIndicesWithElidedDims: () => eS, stridesForAxis: () => tS, stridesWithElidedDims: () => Yk });
var wm = -2;
var UA = -1;
function GA(e, t, n) {
let s = e.shape.length;
O(s === t.length, () => `Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`), O(s === n.length, () => `Error in slice${s}D: Length of size ${n} must match the rank of the array (${s}).`);
for (let r = 0; r < s; ++r)
O(t[r] + n[r] <= e.shape[r], () => `Error in slice${s}D: begin[${r}] + size[${r}] (${t[r] + n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`);
}
function HA(e) {
let t = [], n = 0;
for (; e > 0; )
e & 1 && t.push(n), e /= 2, n++;
return t;
}
function qA(e, t, n) {
let s = [];
for (let r = 0; r < e.length; r++)
s[r] = Math.ceil((t[r] - e[r]) / n[r]);
return s;
}
function Yk(e, t, n, s) {
let r = [...e];
for (let a = r.length; a < s.length; a++)
r.push(1);
for (let a = 0; a < n; a++)
a === 0 ? r[t] = 1 : (r.splice(t, 0, 1), r.pop());
return r;
}
function Qk(e, t, n) {
return n <= e ? n : n - (t - 1);
}
function Zk(e, t) {
let n = [];
for (let s = 0; s < e; s++)
n.push(t + s);
return n;
}
function jA(e, t, n, s, r, a, o, i, u) {
let l = e.length, c = new Array(l), p = new Array(l), d = new Array(l);
if (t.length && n > 0) {
let h = t[0], f = n + 1;
c = Jk(o, h, f, s, e), p = eS(i, h, f, r, e), d = Yk(a, h, f, e);
} else
for (let h = 0; h < l; h++)
c[h] = nS(o, s, a, e, h, u), p[h] = sS(i, r, a, e, h, u), d[h] = tS(a, h, u);
return { begin: c, end: p, strides: d };
}
function Jk(e, t, n, s, r) {
let a = [...r], o = Zk(n, t);
for (let i = 0; i < a.length; i++)
if (o.indexOf(i) > -1)
a[i] = 0;
else {
let u = Qk(t, n, i), l = s[u];
e & 1 << u && (l = 0), a[i] = l;
}
return a;
}
function eS(e, t, n, s, r) {
let a = [...r], o = Zk(n, t);
for (let i = 0; i < a.length; i++)
if (o.indexOf(i) > -1)
a[i] = Number.MAX_SAFE_INTEGER;
else {
let u = Qk(t, n, i), l = s[u];
e & 1 << u && (l = Number.MAX_SAFE_INTEGER), a[i] = l;
}
for (let i = 0; i < a.length; i++) {
let u = r[i];
a[i] < 0 && (a[i] += u), a[i] = Hu(0, a[i], r[i]);
}
return a;
}
function tS(e, t, n) {
let s = e[t];
return (n & 1 << t || s == null) && (s = 1), s;
}
function nS(e, t, n, s, r, a) {
let o = t[r], i = n[r] || 1;
(e & 1 << r || a & 1 << r || o == null) && (i > 0 ? o = Number.MIN_SAFE_INTEGER : o = Number.MAX_SAFE_INTEGER);
let u = s[r];
return o < 0 && (o += u), o = Hu(0, o, u - 1), o;
}
function sS(e, t, n, s, r, a) {
let o = t[r], i = n[r] || 1;
(e & 1 << r || a & 1 << r || o == null) && (i > 0 ? o = Number.MAX_SAFE_INTEGER : o = Number.MIN_SAFE_INTEGER);
let u = s[r];
return o < 0 && (o += u), i > 0 ? o = Hu(0, o, u) : o = Hu(-1, o, u - 1), o;
}
function KA(e, t, n) {
let s = n.length;
for (let r = 0; r < n.length; r++)
if (n[r] > 1) {
s = r;
break;
}
for (let r = s + 1; r < n.length; r++)
if (t[r] > 0 || n[r] !== e[r])
return false;
return true;
}
function XA(e, t) {
let n = e.length > 0 ? e[e.length - 1] : 1;
for (let s = 0; s < e.length - 1; s++)
n += e[s] * t[s];
return n;
}
function rS(e, t, n) {
let s, r = e.shape.length;
typeof t == "number" ? s = [t, ...new Array(r - 1).fill(0)] : t.length < r ? s = t.concat(new Array(r - t.length).fill(0)) : s = t.slice(), s.forEach((o) => {
O(o !== -1, () => "slice() does not support negative begin indexing.");
});
let a;
return n == null ? a = new Array(r).fill(-1) : typeof n == "number" ? a = [n, ...new Array(r - 1).fill(-1)] : n.length < r ? a = n.concat(new Array(r - n.length).fill(-1)) : a = n, a = a.map((o, i) => o >= 0 ? o : (O(o === -1, () => `Negative size values should be exactly -1 but got ${o} for the slice() size at index ${i}.`), e.shape[i] - s[i])), [s, a];
}
function YA(e, t, n, s, r, a, o, i, u) {
let l;
if (s == null ? (l = new Array(t.length), l.fill(1)) : l = s, o != null && (o & o - 1) !== 0)
throw new Error("Multiple ellipses in slice is not allowed.");
let c = false, p = { dims: l.length, numAddAxisAfterEllipsis: 0, begin: t.slice(), end: n.slice(), strides: l.slice(), beginMask: r, endMask: a, ellipsisMask: o, newAxisMask: i, shrinkAxisMask: u };
for (let v = 0; v < p.dims; v++)
c && (1 << v & i) !== 0 && p.numAddAxisAfterEllipsis++, 1 << v & o && (c = true);
c || (p.ellipsisMask |= 1 << p.dims, p.dims++);
let d = { dims: e.length, beginMask: 0, endMask: 0, beginValid: false, endValid: false };
QA(p, d);
let h = true, f = true, m = true, g = [], b = [];
for (let v = 0; v < e.length; ++v) {
if (d.strides[v] === 0)
throw Error(`strides[${v}] must be non-zero`);
let x = !!(d.shrinkAxisMask & 1 << v), k = e[v];
if (k === -1) {
g.push(x ? 1 : -1);
continue;
}
let I = [d.beginMask & 1 << v, d.endMask & 1 << v], $ = [d.strides[v] > 0 ? 0 : -1, d.strides[v] > 0 ? k : k - 1];
if (x && d.strides[v] <= 0)
throw Error("only stride 1 allowed on non-range indexing.");
m = m && d.strides[v] === 1;
let R = !!(d.beginMask & 1 << v && d.endMask & 1 << v);
if (d.beginValid && d.endValid) {
if (x) {
let D = d.begin[v] < 0 ? k + d.begin[v] : d.begin[v];
if (d.begin[v] = D, d.end[v] = d.begin[v] + 1, D < 0 || D >= k)
throw Error(`slice index ${d.begin[v]} of dimension ${v} out of bounds.`);
} else
d.begin[v] = Sx(d.begin[v], 0, d.strides[v], k, I, $), d.end[v] = Sx(d.end[v], 1, d.strides[v], k, I, $);
let A = d.strides[v] === 1 && d.begin[v] === 0 && d.end[v] === k;
h = h && A, f = f && (v === 0 && d.strides[v] === 1 || A);
} else
h = h && d.strides[v] === 1 && R, f = f && (v === 0 && d.strides[v] === 1 || R);
let E, P = false;
if (d.beginValid && d.endValid ? (E = d.end[v] - d.begin[v], P = true) : x ? (E = 1, P = true) : R && k >= 0 && (d.strides[v] < 0 ? E = -k : E = k, P = true), P) {
let A;
E === 0 || E < 0 != d.strides[v] < 0 ? A = 0 : A = Math.trunc(E / d.strides[v]) + (E % d.strides[v] !== 0 ? 1 : 0), g.push(A);
} else
g.push(-1);
}
for (let v = 0; v < d.finalShapeGatherIndices.length; ++v) {
let x = d.finalShapeGatherIndices[v];
x >= 0 ? b.push(g[x]) : x === wm && b.push(1);
}
return { finalShapeSparse: b.filter((v, x) => d.finalShapeGatherIndices[x] !== wm), finalShape: b, isIdentity: h, sliceDim0: f, isSimpleSlice: m, begin: d.begin, end: d.end, strides: d.strides };
}
function QA(e, t) {
t.beginMask = 0, t.endMask = 0, t.shrinkAxisMask = 0;
let n = 0;
t.beginValid = e.begin != null, t.endValid = e.end != null, t.begin = new Array(t.dims), t.end = new Array(t.dims), t.strides = new Array(t.dims), t.finalShapeGatherIndices = [], t.finalShapeGatherIndicesSparse = [], t.inputShapeGatherIndicesSparse = new Array(t.dims);
for (let s = 0; s < e.dims; s++)
if (1 << s & e.ellipsisMask) {
let r = Math.min(t.dims - (e.dims - s) + 1 + e.numAddAxisAfterEllipsis, t.dims);
for (; n < r; n++)
t.begin[n] = 0, t.end[n] = 0, t.strides[n] = 1, t.beginMask |= 1 << n, t.endMask |= 1 << n, t.finalShapeGatherIndices.push(n), t.finalShapeGatherIndicesSparse.push(-1), t.inputShapeGatherIndicesSparse[n] = s;
} else if (1 << s & e.newAxisMask)
t.finalShapeGatherIndices.push(wm), t.finalShapeGatherIndicesSparse.push(-1);
else {
if (n === t.begin.length)
throw Error(`Index out of range using input dim ${n}; input has only ${t.dims} dims, ${t.begin.length}.`);
e.begin != null && (t.begin[n] = e.begin[s]), e.end != null && (t.end[n] = e.end[s]), t.strides[n] = e.strides[s], e.beginMask & 1 << s && (t.beginMask |= 1 << n), e.endMask & 1 << s && (t.endMask |= 1 << n), e.shrinkAxisMask & 1 << s ? (t.finalShapeGatherIndices.push(UA), t.finalShapeGatherIndicesSparse.push(-1), t.shrinkAxisMask |= 1 << n) : (t.finalShapeGatherIndices.push(n), t.finalShapeGatherIndicesSparse.push(s)), t.inputShapeGatherIndicesSparse[n] = s, n++;
}
}
function Sx(e, t, n, s, r, a) {
if (r[t])
return n > 0 ? a[t] : a[t + 1 & 1];
{
let o = e < 0 ? s + e : e;
return o < a[0] ? a[0] : o > a[1] ? a[1] : o;
}
}
var re = {};
Ee(re, { Serializable: () => aS, SerializationMap: () => Xr, registerClass: () => _r });
var aS = class {
getClassName() {
return this.constructor.className;
}
static fromConfig(e, t) {
return new e(t);
}
};
var Xr = class {
constructor() {
this.classNameMap = {};
}
static getMap() {
return Xr.instance == null && (Xr.instance = new Xr()), Xr.instance;
}
static register(e) {
Xr.getMap().classNameMap[e.className] = [e, e.fromConfig];
}
};
function _r(e) {
O(e.className != null, () => "Class being registered does not have the static className property defined."), O(typeof e.className == "string", () => "className is required to be a string, but got type " + typeof e.className), O(e.className.length > 0, () => "Class being registered has an empty-string as its className, which is disallowed."), Xr.register(e);
}
var ZA = {};
Ee(ZA, { TEST_EPSILON_FLOAT16: () => oS, encodeStrings: () => iS, expectArrayBuffersEqual: () => aE, expectArraysClose: () => eE, expectArraysEqual: () => nE, expectNumbersClose: () => sE, expectPromiseToFail: () => tE, expectValuesInRange: () => rE, testEpsilon: () => Jg });
var JA = 1e-3;
var oS = 0.1;
function eE(e, t, n) {
return n == null && (n = Jg()), km(e, t, (s, r) => eb(s, r, n));
}
function Jg() {
return z.backend.floatPrecision() === 32 ? JA : oS;
}
function km(e, t, n) {
let s = true;
if ((Qt(e) || Qt(t)) && (s = false), Qt(e) && Qt(t) && (s = true), s) {
let o = e.constructor.name, i = t.constructor.name;
if (o !== i)
throw new Error(`Arrays are of different type. Actual: ${o}. Expected: ${i}`);
}
if (Array.isArray(e) && Array.isArray(t)) {
let o = Rs(e), i = Rs(t);
if (!Ir(o, i))
throw new Error(`Arrays have different shapes. Actual: [${o}]. Expected: [${i}]`);
}
let r = Qt(e) ? e : aa(e), a = Qt(t) ? t : aa(t);
if (r.length !== a.length)
throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${a.length}.
Actual: ${r}.
Expected: ${a}.`);
for (let o = 0; o < a.length; ++o) {
let i = r[o], u = a[o];
if (!n(i, u))
throw new Error(`Arrays differ: actual[${o}] = ${i}, expected[${o}] = ${u}.
Actual: ${r}.
Expected: ${a}.`);
}
}
function tE(e, t) {
e().then(() => t.fail(), () => t());
}
function nE(e, t) {
let n = typeof t == "string" || typeof t == "number" || typeof t == "boolean" ? [t] : t;
return or(e) || or(e[0]) || or(t) || or(t[0]) ? km(e, n, (s, r) => s == r) : km(e, t, (s, r) => eb(s, r, 0));
}
function sE(e, t, n) {
if (n == null && (n = Jg()), !eb(e, t, n))
throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`);
}
function eb(e, t, n) {
return !isFinite(e) && !isFinite(t) ? true : !(isNaN(e) || isNaN(t) || Math.abs(e - t) > n);
}
function rE(e, t, n) {
for (let s = 0; s < e.length; s++)
if (e[s] < t || e[s] > n)
throw new Error(`Value out of range:${e[s]} low: ${t}, high: ${n}`);
}
function aE(e, t) {
let n = new Float32Array(e), s = new Float32Array(t);
if (n.length !== s.length)
throw new Error(`Expected ArrayBuffer to be of length ${s.length}, but it was ${n.length}`);
for (let r = 0; r < s.length; r++)
if (n[r] !== s[r])
throw new Error(`Expected ArrayBuffer value at ${r} to be ${s[r]} but got ${n[r]} instead`);
}
function iS(e) {
for (let t = 0; t < e.length; t++) {
let n = e[t];
Array.isArray(n) ? iS(n) : e[t] = zl(n);
}
return e;
}
var Gpe = "0.0.0";
function oE(e, t) {
let n = _(e, "a", "add"), s = _(t, "b", "add");
[n, s] = xt(n, s);
let r = { a: n, b: s };
return z.runKernel(Cr, r);
}
var oe = M({ add_: oE });
function iE(e, t) {
let n = _(e, "a", "floorDiv"), s = _(t, "b", "floorDiv");
[n, s] = xt(n, s);
let r = { a: n, b: s };
return z.runKernel(Ma, r);
}
var uS = M({ floorDiv_: iE });
function uE(e, t) {
let n = _(e, "a", "div"), s = _(t, "b", "div");
if ([n, s] = xt(n, s), n.dtype === "int32" && s.dtype === "int32")
return uS(n, s);
let r = { a: n, b: s }, a = {};
return z.runKernel(Oa, r, a);
}
var xe = M({ div_: uE });
function lE(e, t) {
let n = _(e, "a", "mul"), s = _(t, "b", "mul");
[n, s] = xt(n, s);
let r = { a: n, b: s };
return z.runKernel(Za, r);
}
var V = M({ mul_: lE });
function cE(e) {
let t = _(e, "x", "abs");
if (t.dtype === "complex64") {
let n = { x: t };
return z.runKernel(sp, n);
} else {
let n = { x: t };
return z.runKernel(di, n);
}
}
var Lt = M({ abs_: cE });
function dE(e) {
let n = { x: _(e, "x", "acos") };
return z.runKernel(ul, n);
}
var pE = M({ acos_: dE });
function hE(e) {
let n = { x: _(e, "x", "acosh") };
return z.runKernel(ll, n);
}
var fE = M({ acosh_: hE });
function mE(e) {
O(Array.isArray(e), () => "The argument passed to tf.addN() must be a list of tensors"), O(e.length >= 1, () => `Must pass at least one tensor to tf.addN(), but got ${e.length}`);
let t = e.map((r, a) => _(r, `tensors${a}`, "addN")), n = t[0];
t.forEach((r) => {
if (r.dtype !== n.dtype)
throw new Error("All tensors passed to tf.addN() must have the same dtype");
}), t.forEach((r) => {
if (!Ir(r.shape, n.shape))
throw new Error("All tensors passed to tf.addN() must have the same shape");
});
let s = t;
return z.runKernel(Sa, s);
}
var gE = M({ addN_: mE });
function bE(e, t = null, n = false) {
let r = { x: _(e, "x", "all", "bool") }, a = { axis: t, keepDims: n };
return z.runKernel(cl, r, a);
}
var lS = M({ all_: bE });
function yE(e, t = null, n = false) {
let r = { x: _(e, "x", "any", "bool") }, a = { axis: t, keepDims: n };
return z.runKernel(dl, r, a);
}
var Sm = M({ any_: yE });
function vE(e, t = 0) {
let s = { x: _(e, "x", "argMax") }, r = { axis: t };
return z.runKernel(Ia, s, r);
}
var Yu = M({ argMax_: vE });
function xE(e, t = 0) {
let s = { x: _(e, "x", "argMin") }, r = { axis: t };
return z.runKernel(pl, s, r);
}
var wE = M({ argMin_: xE });
function kE(e) {
let n = { x: _(e, "x", "asin") };
return z.runKernel(hl, n);
}
var SE = M({ asin_: kE });
function IE(e) {
let n = { x: _(e, "x", "asinh") };
return z.runKernel(fl, n);
}
var CE = M({ asinh_: IE });
function NE(e) {
let n = { x: _(e, "x", "atan") };
return z.runKernel(ml, n);
}
var TE = M({ atan_: NE });
function $E(e, t) {
let n = _(e, "a", "atan2"), s = _(t, "b", "atan2");
[n, s] = xt(n, s);
let r = { a: n, b: s };
return z.runKernel(bl, r);
}
var _E = M({ atan2_: $E });
function AE(e) {
let n = { x: _(e, "x", "atanh") };
return z.runKernel(gl, n);
}
var EE = M({ atanh_: AE });
function RE(e, t, n, s, r = "NHWC", a) {
let o = e[3], i = [...t, o], u = pS(r);
return Ml(e, i, n, a, s, null, null, u);
}
function cS(e, t, n, s, r, a, o = "channelsLast") {
let [i, u] = Nd(t), l;
if (o === "channelsLast")
l = [i, u, e[3], e[3]];
else if (o === "channelsFirst")
l = [i, u, e[1], e[1]];
else
throw new Error(`Unknown dataFormat ${o}`);
return Ml(e, l, n, s, r, a, false, o);
}
function DE(e, t, n, s, r, a, o = "NDHWC") {
let [i, u, l] = Im(t), c, p;
if (o === "NDHWC")
p = "channelsLast", c = [i, u, l, e[4], e[4]];
else if (o === "NCDHW")
p = "channelsFirst", c = [i, u, l, e[1], e[1]];
else
throw new Error(`Unknown dataFormat ${o}`);
return dS(e, c, n, s, r, false, p, a);
}
function Ml(e, t, n, s, r, a, o = false, i = "channelsLast") {
let [u, l, c, p] = [-1, -1, -1, -1];
if (i === "channelsLast")
[u, l, c, p] = e;
else if (i === "channelsFirst")
[u, p, l, c] = e;
else
throw new Error(`Unknown dataFormat ${i}`);
let [d, h, , f] = t, [m, g] = Nd(n), [b, y] = Nd(s), v = Qo(d, b), x = Qo(h, y), { padInfo: k, outHeight: I, outWidth: $ } = PE(r, l, c, m, g, v, x, a, i), R = o ? f * p : f, E;
return i === "channelsFirst" ? E = [u, R, I, $] : i === "channelsLast" && (E = [u, I, $, R]), { batchSize: u, dataFormat: i, inHeight: l, inWidth: c, inChannels: p, outHeight: I, outWidth: $, outChannels: R, padInfo: k, strideHeight: m, strideWidth: g, filterHeight: d, filterWidth: h, effectiveFilterHeight: v, effectiveFilterWidth: x, dilationHeight: b, dilationWidth: y, inShape: e, outShape: E, filterShape: t };
}
function dS(e, t, n, s, r, a = false, o = "channelsLast", i) {
let [u, l, c, p, d] = [-1, -1, -1, -1, -1];
if (o === "channelsLast")
[u, l, c, p, d] = e;
else if (o === "channelsFirst")
[u, d, l, c, p] = e;
else
throw new Error(`Unknown dataFormat ${o}`);
let [h, f, m, , g] = t, [b, y, v] = Im(n), [x, k, I] = Im(s), $ = Qo(h, x), R = Qo(f, k), E = Qo(m, I), { padInfo: P, outDepth: A, outHeight: D, outWidth: T } = zE(r, l, c, p, b, y, v, $, R, E, i), L = a ? g * d : g, W;
return o === "channelsFirst" ? W = [u, L, A, D, T] : o === "channelsLast" && (W = [u, A, D, T, L]), { batchSize: u, dataFormat: o, inDepth: l, inHeight: c, inWidth: p, inChannels: d, outDepth: A, outHeight: D, outWidth: T, outChannels: L, padInfo: P, strideDepth: b, strideHeight: y, strideWidth: v, filterDepth: h, filterHeight: f, filterWidth: m, effectiveFilterDepth: $, effectiveFilterHeight: R, effectiveFilterWidth: E, dilationDepth: x, dilationHeight: k, dilationWidth: I, inShape: e, outShape: W, filterShape: t };
}
function FE(e, t, n, s, r) {
s == null && (s = tb(e, t, n));
let a = e[0], o = e[1], i = ta((a - t + 2 * s) / n + 1, r), u = ta((o - t + 2 * s) / n + 1, r);
return [i, u];
}
function OE(e, t, n, s, r, a) {
r == null && (r = tb(e, t, s));
let o = e[0], i = e[1], u = e[2], l = ta((o - t + 2 * r) / s + 1, a), c = ta((i - t + 2 * r) / s + 1, a), p = ta((u - t + 2 * r) / s + 1, a);
return [l, c, p, n];
}
function tb(e, t, n, s = 1) {
let r = Qo(t, s);
return Math.floor((e[0] * (n - 1) - n + r) / 2);
}
function Nd(e) {
return typeof e == "number" ? [e, e, e] : e.length === 2 ? [e[0], e[1], 1] : e;
}
function Im(e) {
return typeof e == "number" ? [e, e, e] : e;
}
function Qo(e, t) {
return t <= 1 ? e : e + (e - 1) * (t - 1);
}
function PE(e, t, n, s, r, a, o, i, u) {
let l, c, p;
if (typeof e == "number") {
l = { top: e, bottom: e, left: e, right: e, type: e === 0 ? "VALID" : "NUMBER" };
let h = FE([t, n], a, s, e, i);
c = h[0], p = h[1];
} else if (e === "same") {
c = Math.ceil(t / s), p = Math.ceil(n / r);
let d = Math.max(0, (c - 1) * s + a - t), h = Math.max(0, (p - 1) * r + o - n), f = Math.floor(d / 2), m = d - f, g = Math.floor(h / 2), b = h - g;
l = { top: f, bottom: m, left: g, right: b, type: "SAME" };
} else if (e === "valid")
l = { top: 0, bottom: 0, left: 0, right: 0, type: "VALID" }, c = Math.ceil((t - a + 1) / s), p = Math.ceil((n - o + 1) / r);
else if (typeof e == "object") {
let d = u === "channelsLast" ? e[1][0] : e[2][0], h = u === "channelsLast" ? e[1][1] : e[2][1], f = u === "channelsLast" ? e[2][0] : e[3][0], m = u === "channelsLast" ? e[2][1] : e[3][1];
l = { top: d, bottom: h, left: f, right: m, type: d === 0 && h === 0 && f === 0 && m === 0 ? "VALID" : "EXPLICIT" }, c = ta((t - a + d + h) / s + 1, i), p = ta((n - o + f + m) / r + 1, i);
} else
throw Error(`Unknown padding parameter: ${e}`);
return { padInfo: l, outHeight: c, outWidth: p };
}
function zE(e, t, n, s, r, a, o, i, u, l, c) {
let p, d, h, f;
if (typeof e == "number") {
p = { top: e, bottom: e, left: e, right: e, front: e, back: e, type: e === 0 ? "VALID" : "NUMBER" };
let g = OE([t, n, s, 1], i, 1, r, e, c);
d = g[0], h = g[1], f = g[2];
} else if (e === "same") {
d = Math.ceil(t / r), h = Math.ceil(n / a), f = Math.ceil(s / o);
let m = (d - 1) * r + i - t, g = (h - 1) * a + u - n, b = (f - 1) * o + l - s, y = Math.floor(m / 2), v = m - y, x = Math.floor(g / 2), k = g - x, I = Math.floor(b / 2), $ = b - I;
p = { top: x, bottom: k, left: I, right: $, front: y, back: v, type: "SAME" };
} else if (e === "valid")
p = { top: 0, bottom: 0, left: 0, right: 0, front: 0, back: 0, type: "VALID" }, d = Math.ceil((t - i + 1) / r), h = Math.ceil((n - u + 1) / a), f = Math.ceil((s - l + 1) / o);
else
throw Error(`Unknown padding parameter: ${e}`);
return { padInfo: p, outDepth: d, outHeight: h, outWidth: f };
}
function ta(e, t) {
if (!t)
return Math.trunc(e);
switch (t) {
case "round":
return Math.round(e);
case "ceil":
return Math.ceil(e);
case "floor":
return Math.floor(e);
default:
throw new Error(`Unknown roundingMode ${t}`);
}
}
function gr(e) {
let [t, n, s] = Nd(e);
return t === 1 && n === 1 && s === 1;
}
function Ps(e, t) {
return gr(e) || gr(t);
}
function pS(e) {
if (e === "NHWC")
return "channelsLast";
if (e === "NCHW")
return "channelsFirst";
throw new Error(`Unknown dataFormat ${e}`);
}
function fn(e, t, n) {
if (n != null) {
if (typeof t == "string")
throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);
if (typeof t == "number")
O(ei(t), () => `Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);
else if (typeof t == "object")
t.forEach((s) => {
s.forEach((r) => {
O(ei(r), () => `Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${r}.`);
});
});
else
throw Error(`Error in ${e}: Unknown padding parameter: ${t}`);
}
}
function LE(e, t) {
let s = { x: _(e, "x", "reshape", "string_or_numeric") }, r = { shape: t };
return z.runKernel(Oi, s, r);
}
var U = M({ reshape_: LE });
function ME(e, t, n, s, r) {
let a = _(e, "x", "avgPool", "float32"), o = 1;
O(Ps(n, o), () => `Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);
let i = a, u = false;
a.rank === 3 && (u = true, i = U(a, [1, a.shape[0], a.shape[1], a.shape[2]])), O(i.rank === 4, () => `Error in avgPool: x must be rank 4 but got rank ${i.rank}.`), fn("avgPool", s, r);
let l = { x: i }, c = { filterSize: t, strides: n, pad: s, dimRoundingMode: r }, p = z.runKernel(Ca, l, c);
return p = le(p, a.dtype), u ? U(p, [p.shape[1], p.shape[2], p.shape[3]]) : p;
}
var nb = M({ avgPool_: ME });
function BE(e, t, n, s, r, a = "NDHWC") {
let o = _(e, "x", "avgPool3d", "float32"), i = o, u = false;
o.rank === 4 && (u = true, i = U(o, [1, o.shape[0], o.shape[1], o.shape[2], o.shape[3]])), O(i.rank === 5, () => `Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`), O(a === "NDHWC", () => `Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`), fn("avgPool3d", s, r);
let l = { x: i }, c = { filterSize: t, strides: n, pad: s, dimRoundingMode: r, dataFormat: a }, p = z.runKernel(tp, l, c);
return p = le(p, i.dtype), u ? U(p, [p.shape[1], p.shape[2], p.shape[3], p.shape[4]]) : p;
}
var hS = M({ avgPool3d_: BE });
function VE(e, t = 0) {
O(e.length >= 1, () => "Pass at least one tensor to concat");
let n = Ku(e, "tensors", "concat", "string_or_numeric");
if (n[0].dtype === "complex64" && n.forEach((a) => {
if (a.dtype !== "complex64")
throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${a.dtype}. `);
}), n.length === 1)
return lr(n[0]);
let s = n, r = { axis: t };
return z.runKernel(hi, s, r);
}
var Ft = M({ concat_: VE });
function WE(e) {
let n = { x: _(e, "x", "sigmoid", "float32") };
return z.runKernel(uo, n);
}
var qs = M({ sigmoid_: WE });
function UE(e, t, n) {
let s = _(e, "x", "slice", "string_or_numeric");
if (s.rank === 0)
throw new Error("Slicing scalar is not possible");
let r = { x: s }, a = { begin: t, size: n };
return z.runKernel(Bi, r, a);
}
var qe = M({ slice_: UE });
function GE(e) {
let n = { x: _(e, "x", "tanh", "float32") };
return z.runKernel(mo, n);
}
var Qu = M({ tanh_: GE });
function HE(e, t, n, s, r, a) {
let o = _(e, "forgetBias", "basicLSTMCell"), i = _(t, "lstmKernel", "basicLSTMCell"), u = _(n, "lstmBias", "basicLSTMCell"), l = _(s, "data", "basicLSTMCell"), c = _(r, "c", "basicLSTMCell"), p = _(a, "h", "basicLSTMCell"), d = Ft([l, p], 1), h = We(d, i), f = oe(h, u), m = f.shape[0], g = f.shape[1] / 4, b = [m, g], y = qe(f, [0, 0], b), v = qe(f, [0, g], b), x = qe(f, [0, g * 2], b), k = qe(f, [0, g * 3], b), I = oe(V(qs(y), Qu(v)), V(c, qs(oe(o, x)))), $ = V(Qu(I), qs(k));
return [I, $];
}
var Hpe = M({ basicLSTMCell_: HE });
function qE(e, t, n) {
let s = _(e, "x", "batchToSpaceND"), r = t.reduce((i, u) => i * u);
O(s.rank >= 1 + t.length, () => `input rank is ${s.rank} but should be > than blockShape.length ${t.length}`), O(n.length === t.length, () => `crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`), O(s.shape[0] % r === 0, () => `input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);
let a = { x: s }, o = { blockShape: t, crops: n };
return z.runKernel(pi, a, o);
}
var sb = M({ batchToSpaceND_: qE });
function jE(e) {
let t;
return e.rank === 0 || e.rank === 1 ? t = U(e, [1, 1, 1, e.size]) : e.rank === 2 ? t = U(e, [1, 1, e.shape[0], e.shape[1]]) : e.rank === 3 ? t = U(e, [1, e.shape[0], e.shape[1], e.shape[2]]) : t = e, t;
}
function KE(e, t, n, s, r, a) {
a == null && (a = 1e-3);
let o = _(e, "x", "batchNorm"), i = _(t, "mean", "batchNorm"), u = _(n, "variance", "batchNorm"), l;
r != null && (l = _(r, "scale", "batchNorm"));
let c;
s != null && (c = _(s, "offset", "batchNorm")), O(i.rank === u.rank, () => "Batch normalization gradient requires mean and variance to have equal ranks."), O(c == null || i.rank === c.rank, () => "Batch normalization gradient requires mean and offset to have equal ranks."), O(l == null || i.rank === l.rank, () => "Batch normalization gradient requires mean and scale to have equal ranks.");
let d = { x: jE(o), scale: l, offset: c, mean: i, variance: u }, h = { varianceEpsilon: a }, f = z.runKernel(Ba, d, h);
return U(f, o.shape);
}
var Zu = M({ batchNorm_: KE });
function XE(e, t, n, s, r, a) {
let o = _(e, "x", "batchNorm"), i = _(t, "mean", "batchNorm"), u = _(n, "variance", "batchNorm"), l;
r != null && (l = _(r, "scale", "batchNorm"));
let c;
return s != null && (c = _(s, "offset", "batchNorm")), O(o.rank === 2, () => `Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`), O(i.rank === 2 || i.rank === 1, () => `Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`), O(u.rank === 2 || u.rank === 1, () => `Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${u.rank}.`), l != null && O(l.rank === 2 || l.rank === 1, () => `Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${l.rank}.`), c != null && O(c.rank === 2 || c.rank === 1, () => `Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`), Zu(o, i, u, c, l, a);
}
var YE = M({ batchNorm2d_: XE });
function QE(e, t, n, s, r, a) {
let o = _(e, "x", "batchNorm"), i = _(t, "mean", "batchNorm"), u = _(n, "variance", "batchNorm"), l;
r != null && (l = _(r, "scale", "batchNorm"));
let c;
return s != null && (c = _(s, "offset", "batchNorm")), O(o.rank === 3, () => `Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`), O(i.rank === 3 || i.rank === 1, () => `Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`), O(u.rank === 3 || u.rank === 1, () => `Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${u.rank}.`), l != null && O(l.rank === 3 || l.rank === 1, () => `Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${l.rank}.`), c != null && O(c.rank === 3 || c.rank === 1, () => `Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`), Zu(o, i, u, c, l, a);
}
var ZE = M({ batchNorm3d_: QE });
function JE(e, t, n, s, r, a) {
let o = _(e, "x", "batchNorm"), i = _(t, "mean", "batchNorm"), u = _(n, "variance", "batchNorm"), l;
r != null && (l = _(r, "scale", "batchNorm"));
let c;
return s != null && (c = _(s, "offset", "batchNorm")), O(o.rank === 4, () => `Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`), O(i.rank === 4 || i.rank === 1, () => `Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`), O(u.rank === 4 || u.rank === 1, () => `Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${u.rank}.`), l != null && O(l.rank === 4 || l.rank === 1, () => `Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${l.rank}.`), c != null && O(c.rank === 4 || c.rank === 1, () => `Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`), Zu(o, i, u, c, l, a);
}
var eR = M({ batchNorm4d_: JE });
function tR(e, t, n) {
let s = _(e, "x", "bincount"), r = _(t, "weights", "bincount");
O(s.dtype === "int32", () => `Error in bincount: input dtype must be int32, but got ${s.dtype}`), O(n >= 0, () => `size must be non-negative, but got ${n}.`), O(r.size === s.size || r.size === 0, () => `Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${r.shape}.`);
let a = { x: s, weights: r }, o = { size: n };
return z.runKernel(vg, a, o);
}
var fS = M({ bincount_: tR });
function nR(e, t) {
let n = _(e, "s0", "broadcastArgs", "int32"), s = _(t, "s1", "broadcastArgs", "int32");
if (n.rank !== 1)
throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);
if (s.rank !== 1)
throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${s.rank}`);
let r = { s0: n, s1: s };
return z.runKernel(xg, r);
}
var sR = M({ broadcastArgs_: nR });
function rR(e, t) {
let n = _(e, "broadcastTo", "x"), s = n.shape;
if (t.some((l) => !(l > 0) || l % 1 !== 0))
throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);
if (t.length < n.rank)
throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);
if (t.length > n.rank) {
let l = n.shape.slice();
for (; l.length < t.length; )
l.unshift(1);
n = U(n, l);
}
let r = n.shape, a = Array.from(t);
for (let l = t.length - 1; l >= 0; l--)
if (r[l] === t[l])
a[l] = 1;
else if (n.shape[l] !== 1)
throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);
if (a.map((l, c) => l > 1 ? c : -1).filter((l) => l >= 0).length === 0)
return lr(n);
let i = { x: n }, u = { reps: a };
return z.runKernel(Tr, i, u);
}
var id = M({ broadcastTo_: rR });
function aR(e) {
let n = { x: _(e, "x", "ceil", "float32") };
return z.runKernel($a, n);
}
var oR = M({ ceil_: aR });
function iR(e, t, n) {
let s = _(e, "x", "clipByValue");
O(t <= n, () => `Error in clip: min (${t}) must be less than or equal to max (${n}).`);
let r = { x: s }, a = { clipValueMin: t, clipValueMax: n };
return z.runKernel(Nr, r, a);
}
var Wn = M({ clipByValue_: iR });
function uR(e) {
return Ft(e, 0);
}
var lR = M({ concat1d_: uR });
function cR(e, t) {
return Ft(e, t);
}
var dR = M({ concat2d_: cR });
function pR(e, t) {
return Ft(e, t);
}
var hR = M({ concat3d_: pR });
function fR(e, t) {
return Ft(e, t);
}
var mR = M({ concat4d_: fR });
function gR(e, t, n, s, r = "NHWC", a = [1, 1], o) {
let i = _(e, "x", "conv2d", "float32"), u = _(t, "filter", "conv2d", "float32"), l = i, c = false;
i.rank === 3 && (c = true, l = U(i, [1, i.shape[0], i.shape[1], i.shape[2]])), O(l.rank === 4, () => `Error in conv2d: input must be rank 4, but got rank ${l.rank}.`), O(u.rank === 4, () => `Error in conv2d: filter must be rank 4, but got rank ${u.rank}.`), fn("conv2d", s, o);
let p = r === "NHWC" ? l.shape[3] : l.shape[1];
O(p === u.shape[2], () => `Error in conv2d: depth of input (${p}) must match input depth for filter ${u.shape[2]}.`), O(Ps(n, a), () => `Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);
let d = { x: l, filter: u }, h = { strides: n, pad: s, dataFormat: r, dilations: a, dimRoundingMode: o }, f = z.runKernel(_a, d, h);
return c ? U(f, [f.shape[1], f.shape[2], f.shape[3]]) : f;
}
var da = M({ conv2d_: gR });
function bR(e, t, n, s, r = "NWC", a = 1, o) {
let i = _(e, "x", "conv1d"), u = _(t, "filter", "conv1d"), l = i, c = false;
i.rank === 2 && (c = true, l = U(i, [1, i.shape[0], i.shape[1]])), O(l.rank === 3, () => `Error in conv1d: input must be rank 3, but got rank ${l.rank}.`), O(u.rank === 3, () => `Error in conv1d: filter must be rank 3, but got rank ${u.rank}.`), fn("conv1d", s, o), O(l.shape[2] === u.shape[1], () => `Error in conv1d: depth of input (${l.shape[2]}) must match input depth for filter ${u.shape[1]}.`), O(Ps(n, a), () => `Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`), O(r === "NWC", () => `Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);
let p = U(u, [1, u.shape[0], u.shape[1], u.shape[2]]), d = U(l, [l.shape[0], 1, l.shape[1], l.shape[2]]), g = da(d, p, [1, n], s, "NHWC", [1, a], o);
return c ? U(g, [g.shape[2], g.shape[3]]) : U(g, [g.shape[0], g.shape[2], g.shape[3]]);
}
var mS = M({ conv1d_: bR });
function yR(e, t, n, s, r, a = "NHWC", o) {
O(e.length === t.rank, () => `Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);
let i = e, u = t, l = false;
t.rank === 3 && (l = true, u = U(t, [1, t.shape[0], t.shape[1], t.shape[2]]), i = [1, e[0], e[1], e[2]]), O(i.length === 4, () => `Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`), O(u.rank === 4, () => `Error in conv2dDerInput: dy must be rank 4, but got rank ${u.rank}`), O(n.rank === 4, () => `Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);
let c = a === "NHWC" ? i[3] : i[1], p = a === "NHWC" ? u.shape[3] : u.shape[1];
O(c === n.shape[2], () => `Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[2]}.`), O(p === n.shape[3], () => `Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[3]}.`), fn("conv2dDerInput", r, o);
let d = { dy: u, filter: n }, h = { strides: s, pad: r, dataFormat: a, dimRoundingMode: o, inputShape: i }, f = z.runKernel(Aa, d, h);
return l ? U(f, [f.shape[1], f.shape[2], f.shape[3]]) : f;
}
var rb = M({ conv2DBackpropInput_: yR });
function vR(e, t, n, s, r, a) {
let o = _(e, "x", "conv2dTranspose"), i = _(t, "filter", "conv2dTranspose");
return rb(n, o, i, s, r, "NHWC", a);
}
var gS = M({ conv2dTranspose_: vR });
function xR(e, t, n, s, r = "NDHWC", a = [1, 1, 1]) {
let o = _(e, "x", "conv3d"), i = _(t, "filter", "conv3d"), u = o, l = false;
o.rank === 4 && (l = true, u = U(o, [1, o.shape[0], o.shape[1], o.shape[2], o.shape[3]])), O(u.rank === 5, () => `Error in conv3d: input must be rank 5, but got rank ${u.rank}.`), O(i.rank === 5, () => `Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`), O(u.shape[4] === i.shape[3], () => `Error in conv3d: depth of input (${u.shape[4]}) must match input depth for filter ${i.shape[3]}.`), O(Ps(n, a), () => `Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`), O(r === "NDHWC", () => `Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);
let c = { x: u, filter: i }, p = { strides: n, pad: s, dataFormat: r, dilations: a }, d = z.runKernel(rp, c, p);
return l ? U(d, [d.shape[1], d.shape[2], d.shape[3], d.shape[4]]) : d;
}
var bS = M({ conv3d_: xR });
function wR(e, t, n, s, r) {
O(e.length === t.rank, () => `Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);
let a = e, o = t, i = false;
t.rank === 4 && (i = true, o = U(t, [1, t.shape[0], t.shape[1], t.shape[2], t.shape[3]]), a = [1, e[0], e[1], e[2], e[3]]);
let u = a[4], l = o.shape[4];
O(a.length === 5, () => `Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`), O(o.rank === 5, () => `Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`), O(n.rank === 5, () => `Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`), O(u === n.shape[3], () => `Error in conv3dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[3]}.`), O(l === n.shape[4], () => `Error in conv3dDerInput: depth of output (${l}) must match output depth for filter ${n.shape[4]}.`);
let c = { dy: o, filter: n }, p = { pad: r, strides: s, inputShape: a }, d = z.runKernel(Sg, c, p);
return i ? U(d, [d.shape[1], d.shape[2], d.shape[3], d.shape[4]]) : d;
}
var yS = M({ conv3DBackpropInput_: wR });
function kR(e, t, n, s, r) {
let a = _(e, "x", "conv3dTranspose"), o = _(t, "filter", "conv3dTranspose");
return yS(n, a, o, s, r);
}
var SR = M({ conv3dTranspose_: kR });
function IR(e) {
let n = { x: _(e, "x", "cos", "float32") };
return z.runKernel(Ea, n);
}
var ab = M({ cos_: IR });
function CR(e) {
let n = { x: _(e, "x", "cosh", "float32") };
return z.runKernel(Ra, n);
}
var vS = M({ cosh_: CR });
function NR(e, t = 0, n = false, s = false) {
let a = { x: _(e, "x", "cumprod") }, o = { axis: t, exclusive: n, reverse: s };
return z.runKernel(fi, a, o);
}
var Cm = M({ cumprod_: NR });
function TR(e, t = 0, n = false, s = false) {
let a = { x: _(e, "x", "cumsum") }, o = { axis: t, exclusive: n, reverse: s };
return z.runKernel(Da, a, o);
}
var xS = M({ cumsum_: TR });
function $R(e, t, n, s = false) {
let r = _(e, "x", "denseBincount"), a = _(t, "weights", "denseBincount");
O(r.dtype === "int32", () => `Error in denseBincount: input dtype must be int32, but got ${r.dtype}`), O(r.rank <= 2, () => `Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`), O(n >= 0, () => `size must be non-negative, but got ${n}.`), O(a.size === r.size || a.size === 0, () => `Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${a.shape}.`);
let o = { x: r, weights: a }, i = { size: n, binaryOutput: s };
return z.runKernel(Ig, o, i);
}
var _R = M({ denseBincount_: $R });
function AR(e, t, n = "NHWC") {
let s = _(e, "x", "depthToSpace", "float32"), r = n === "NHWC" ? s.shape[1] : s.shape[2], a = n === "NHWC" ? s.shape[2] : s.shape[3], o = n === "NHWC" ? s.shape[3] : s.shape[1];
O(t > 1, () => `blockSize should be > 1 for depthToSpace, but was: ${t}`), O(r * t >= 0, () => `Negative dimension size caused by overflow when multiplying
${r} and ${t} for depthToSpace with input shape
${s.shape}`), O(a * t >= 0, () => `Negative dimension size caused by overflow when multiplying
${a} and ${t} for depthToSpace with input shape
${s.shape}`), O(o % (t * t) === 0, () => `Dimension size must be evenly divisible by ${t * t} but is ${o} for depthToSpace with input shape ${s.shape}`);
let i = { x: s }, u = { blockSize: t, dataFormat: n };
return z.runKernel(gi, i, u);
}
var ER = M({ depthToSpace_: AR });
function RR(e, t, n, s, r = "NHWC", a = [1, 1], o) {
let i = _(e, "x", "depthwiseConv2d", "float32"), u = _(t, "filter", "depthwiseConv2d", "float32"), l = i, c = false;
i.rank === 3 && (c = true, l = U(i, [1, i.shape[0], i.shape[1], i.shape[2]])), O(l.rank === 4, () => `Error in depthwiseConv2d: input must be rank 4, but got rank ${l.rank}.`), O(u.rank === 4, () => `Error in depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`), O(l.shape[3] === u.shape[2], () => `Error in depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`), fn("depthwiseConv2d", s, o);
let p = { x: l, filter: u }, d = { strides: n, pad: s, dataFormat: r, dilations: a, dimRoundingMode: o }, h = z.runKernel(Fa, p, d);
return c ? U(h, [h.shape[1], h.shape[2], h.shape[3]]) : h;
}
var kp = M({ depthwiseConv2d_: RR });
function DR(e) {
let n = { x: _(e, "x", "diag") };
return z.runKernel(Tg, n);
}
var qpe = M({ diag_: DR });
function FR(e, t, n, s, r = [1, 1], a = "NHWC") {
let o = _(e, "x", "dilation2d"), i = _(t, "filter", "dilation2d");
O(o.rank === 3 || o.rank === 4, () => `Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`), O(i.rank === 3, () => `Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`), O(a === "NHWC", () => `Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);
let u = o, l = false;
o.rank === 3 && (u = U(o, [1, o.shape[0], o.shape[1], o.shape[2]]), l = true);
let c = { x: u, filter: i }, p = { strides: n, pad: s, dilations: r }, d = z.runKernel(ap, c, p);
return l ? U(d, [d.shape[1], d.shape[2], d.shape[3]]) : d;
}
var OR = M({ dilation2d_: FR });
function PR(e, t) {
let n = _(e, "a", "equal", "string_or_numeric"), s = _(t, "b", "equal", "string_or_numeric");
[n, s] = xt(n, s), at(n.shape, s.shape);
let r = { a: n, b: s };
return z.runKernel(bi, r);
}
var Xn = M({ equal_: PR });
function zR(e, t, n) {
let s = _(t, "a", "where"), r = _(n, "b", "where"), a = _(e, "condition", "where", "bool"), o = at(at(a.shape, s.shape), r.shape), i = id(a, o), u = id(s, o), l = id(r, o), c = { condition: i, t: u, e: l };
return z.runKernel(Mi, c);
}
var vn = M({ where_: zR });
function LR(e) {
let n = { x: _(e, "x", "zerosLike") };
return z.runKernel(Xi, n);
}
var je = M({ zerosLike_: LR });
function MR(e, t) {
let n = _(e, "a", "div"), s = _(t, "b", "div");
[n, s] = xt(n, s);
let r = xe(n, s), a = je(r), o = Xn(s, a);
return vn(o, a, r);
}
var BR = M({ divNoNan_: MR });
function VR(e, t) {
let n = _(e, "t1", "dot"), s = _(t, "t2", "dot");
O((n.rank === 1 || n.rank === 2) && (s.rank === 1 || s.rank === 2), () => `Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`);
let r = n.rank === 1 ? n.size : n.shape[1], a = s.rank === 1 ? s.size : s.shape[0];
if (O(r === a, () => `Error in dot: inner dimensions of inputs must match, but got ${r} and ${a}.`), n.rank === 1 && s.rank === 1) {
let o = U(n, [1, -1]), i = U(s, [-1, 1]), u = We(o, i);
return U(u, []);
} else if (n.rank === 1 && s.rank === 2) {
let o = U(n, [1, -1]), i = U(s, [s.shape[0], s.shape[1]]), u = We(o, i);
return U(u, [u.size]);
} else if (n.rank === 2 && s.rank === 1) {
let o = U(s, [-1, 1]), i = We(n, o);
return U(i, [i.size]);
} else {
let o = U(s, [s.shape[0], s.shape[1]]);
return We(n, o);
}
}
var jpe = M({ dot_: VR });
function WR(e, ...t) {
let n = t.map((r, a) => _(r, `tensors${a}`, "einsum")), s = { equation: e };
return z.runKernel(op, n, s);
}
var UR = M({ einsum_: WR });
function GR(e) {
let n = { x: _(e, "x", "elu", "float32") };
return z.runKernel(Pa, n);
}
var Sp = M({ elu_: GR });
function HR(e) {
let t = _(e, "x", "erf");
O(t.dtype === "int32" || t.dtype === "float32", () => "Input dtype must be `int32` or `float32`."), t.dtype === "int32" && (t = le(t, "float32"));
let n = { x: t };
return z.runKernel(yl, n);
}
var qR = M({ erf_: HR });
function ob(e, t) {
for (let n = 0; n < e.length; ++n)
if (e[e.length - n - 1] !== t - 1 - n)
return false;
return true;
}
function wS(e, t, n) {
let s = e.length + t.length, r = [], a = 0, o = 0;
for (let i = 0; i < s; i++)
n.indexOf(i) === -1 ? r.push(e[a++]) : r.push(t[o++]);
return r;
}
function kS(e, t) {
let n = [], s = e.length;
for (let a = 0; a < s; a++)
t.indexOf(a) === -1 && n.push(e[a]);
let r = t.map((a) => e[a]);
return [n, r];
}
function pa(e, t) {
let n = t.map((s) => 1);
return wS(e, n, t);
}
function jR(e, t, n) {
O(ob(t, n), () => `${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`);
}
function SS(e, t) {
if (ob(e, t))
return null;
let n = [];
for (let s = 0; s < t; ++s)
e.indexOf(s) === -1 && n.push(s);
return e.forEach((s) => n.push(s)), n;
}
function ib(e) {
return e.map((t, n) => [n, t]).sort((t, n) => t[1] - n[1]).map((t) => t[0]);
}
function KR(e, t) {
let n = [];
for (let s = t - e; s < t; ++s)
n.push(s);
return n;
}
function XR(e, t = null, n = false) {
let r = { x: _(e, "x", "max") }, a = { reductionIndices: t, keepDims: n };
return z.runKernel(Ha, r, a);
}
var As = M({ max_: XR });
function YR(e, t = null, n = false) {
let r = { x: _(e, "x", "min") }, a = { axis: t, keepDims: n };
return z.runKernel(Xa, r, a);
}
var Nm = M({ min_: YR });
function QR(e, t) {
let n = _(e, "base", "pow"), s = _(t, "exp", "pow");
[n, s] = xt(n, s);
let r = { a: n, b: s };
return z.runKernel(eo, r);
}
var ha = M({ pow_: QR });
function we(e, t) {
if ((Qt(e) && t !== "string" || Array.isArray(e)) && t !== "complex64")
throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");
if (t === "string" && Qt(e) && !(e instanceof Uint8Array))
throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");
return $r(e, [], [], t);
}
function ZR(e) {
let n = { x: _(e, "x", "sqrt", "float32") };
return z.runKernel(lo, n);
}
var dn = M({ sqrt_: ZR });
function JR(e) {
let t = _(e, "x", "square"), n = {};
return z.runKernel("Square", { x: t }, n);
}
var ct = M({ square_: JR });
function eD(e, t = null, n = false) {
let s = _(e, "x", "sum");
s.dtype === "bool" && (s = le(s, "int32"));
let r = { x: s }, a = { axis: t, keepDims: n };
return z.runKernel(co, r, a);
}
var ve = M({ sum_: eD });
function tD(e, t = "euclidean", n = null, s = false) {
e = _(e, "x", "norm");
let r = IS(e, t, n), a = r.shape;
if (s) {
let o = ts(n, e.shape);
a = pa(r.shape, o);
}
return U(r, a);
}
function IS(e, t, n = null) {
if (e.rank === 0)
return Lt(e);
if (e.rank !== 1 && n === null)
return IS(U(e, [-1]), t, n);
if (e.rank === 1 || typeof n == "number" || Array.isArray(n) && n.length === 1) {
if (t === 1)
return ve(Lt(e), n);
if (t === 1 / 0)
return As(Lt(e), n);
if (t === -1 / 0)
return Nm(Lt(e), n);
if (t === "euclidean" || t === 2)
return dn(ve(ha(Lt(e), we(2, "int32")), n));
throw new Error(`Error in norm: invalid ord value: ${t}`);
}
if (Array.isArray(n) && n.length === 2) {
if (t === 1)
return As(ve(Lt(e), n[0]), n[1] - 1);
if (t === 1 / 0)
return As(ve(Lt(e), n[1]), n[0]);
if (t === -1 / 0)
return Nm(ve(Lt(e), n[1]), n[0]);
if (t === "fro" || t === "euclidean")
return dn(ve(ct(e), n));
throw new Error(`Error in norm: invalid ord value: ${t}`);
}
throw new Error(`Error in norm: invalid axis: ${n}`);
}
var ub = M({ norm_: tD });
function nD(e, t = null, n = false) {
return ub(e, "euclidean", t, n);
}
var sD = M({ euclideanNorm_: nD });
function rD(e) {
let n = { x: _(e, "x", "exp") };
return z.runKernel(za, n);
}
var Yn = M({ exp_: rD });
function aD(e, t = 0) {
let n = _(e, "x", "expandDims", "string_or_numeric");
O(t <= n.rank, () => "Axis must be <= rank of the tensor");
let s = { input: n }, r = { dim: t };
return z.runKernel(yi, s, r);
}
var Pn = M({ expandDims_: aD });
function oD(e) {
let n = { x: _(e, "x", "expm1") };
return z.runKernel(vi, n);
}
var iD = M({ expm1_: oD });
function uD(e, t) {
let n = _(e, "x", "tile", "string_or_numeric");
O(n.rank === t.length, () => `Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);
let s = { x: n }, r = { reps: t };
return z.runKernel(Tr, s, r);
}
var hs = M({ tile_: uD });
function lD(e, t, n, s = "float32") {
t == null && (t = e);
let r = Ae([e, t], s), a = e <= t ? e : t;
for (let i = 0; i < a; ++i)
r.set(1, i, i);
let o = U(r.toTensor(), [e, t]);
if (n == null)
return o;
if (n.length === 1)
return hs(Pn(o, 0), [n[0], 1, 1]);
if (n.length === 2)
return hs(Pn(Pn(o, 0), 0), [n[0], n[1], 1, 1]);
if (n.length === 3)
return hs(Pn(Pn(Pn(o, 0), 0), 0), [n[0], n[1], n[2], 1, 1]);
throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`);
}
var CS = M({ eye_: lD });
function Bl(e, t, n) {
let s = { shape: e, value: t, dtype: n };
return z.runKernel(vl, {}, s);
}
function cD(e) {
let n = { x: _(e, "x", "floor", "float32") };
return z.runKernel(La, n);
}
var Ip = M({ floor_: cD });
function dD(e, t, n = 0, s = 0) {
let r = _(e, "x", "gather"), a = _(t, "indices", "gather", "int32"), o = { x: r, indices: a }, i = { axis: n, batchDims: s };
return z.runKernel(wi, o, i);
}
var Ju = M({ gather_: dD });
function pD(e, t) {
let n = _(e, "a", "greater", "string_or_numeric"), s = _(t, "b", "greater", "string_or_numeric");
[n, s] = xt(n, s), at(n.shape, s.shape);
let r = { a: n, b: s };
return z.runKernel(Si, r);
}
var Gn = M({ greater_: pD });
function hD(e, t) {
let n = _(e, "a", "greaterEqual", "string_or_numeric"), s = _(t, "b", "greaterEqual", "string_or_numeric");
[n, s] = xt(n, s), at(n.shape, s.shape);
let r = { a: n, b: s };
return z.runKernel(Va, r);
}
var Zi = M({ greaterEqual_: hD });
function fD(e) {
let n = { x: _(e, "x", "isFinite") };
return z.runKernel(xl, n);
}
var Kpe = M({ isFinite_: fD });
function mD(e) {
let n = { x: _(e, "x", "isInf") };
return z.runKernel(wl, n);
}
var Xpe = M({ isInf_: mD });
function gD(e) {
let n = { x: _(e, "x", "isNaN") };
return z.runKernel(kl, n);
}
var bD = M({ isNaN_: gD });
function yD(e, t = 0.2) {
let s = { x: _(e, "x", "leakyRelu") }, r = { alpha: t };
return z.runKernel(Ua, s, r);
}
var lb = M({ leakyRelu_: yD });
function vD(e, t) {
let n = _(e, "a", "less", "string_or_numeric"), s = _(t, "b", "less", "string_or_numeric");
[n, s] = xt(n, s), at(n.shape, s.shape);
let r = { a: n, b: s };
return z.runKernel(Ii, r);
}
var NS = M({ less_: vD });
function xD(e, t) {
let n = _(e, "a", "lessEqual", "string_or_numeric"), s = _(t, "b", "lessEqual", "string_or_numeric");
[n, s] = xt(n, s), at(n.shape, s.shape);
let r = { a: n, b: s };
return z.runKernel(Ci, r);
}
var Ji = M({ lessEqual_: xD });
function wD(e, t, n) {
if (n <= 0)
throw new Error("The number of values should be positive.");
let s = { start: e, stop: t, num: n };
return z.runKernel(Eg, {}, s);
}
function kD(e, t = 5, n = 1, s = 1, r = 0.5) {
let a = _(e, "x", "localResponseNormalization");
O(a.rank === 4 || a.rank === 3, () => `Error in localResponseNormalization: x must be rank 3 or 4 but got
rank ${a.rank}.`), O(ei(t), () => `Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);
let o = a, i = false;
a.rank === 3 && (i = true, o = U(a, [1, a.shape[0], a.shape[1], a.shape[2]]));
let u = { x: o }, l = { depthRadius: t, bias: n, alpha: s, beta: r }, c = z.runKernel(up, u, l);
return i ? U(c, [c.shape[1], c.shape[2], c.shape[3]]) : c;
}
var SD = M({ localResponseNormalization_: kD });
function ID(e) {
let n = { x: _(e, "x", "log", "float32") };
return z.runKernel(Ga, n);
}
var Qn = M({ log_: ID });
function CD(e) {
let n = { x: _(e, "x", "log1p") };
return z.runKernel(Sl, n);
}
var cb = M({ log1p_: CD });
function Ype(e) {
return O(fr(e), () => "The f passed in grad(f) must be a function"), (t, n) => {
let s = _(t, "x", "tf.grad", "string_or_numeric"), r = n != null ? _(n, "dy", "tf.grad") : null;
return z.tidy(() => {
let { value: a, grads: o } = z.gradients(() => e(s), [s], r);
return r != null && hn(a.shape, r.shape, "The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"), Cp(o), o[0];
});
};
}
function Qpe(e) {
return O(fr(e), () => "The f passed in grads(f) must be a function"), (t, n) => {
O(Array.isArray(t), () => "The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");
let s = Ku(t, "args", "tf.grads", "string_or_numeric"), r = n != null ? _(n, "dy", "tf.grads") : null;
return z.tidy(() => {
let { value: a, grads: o } = z.gradients(() => e(...s), s, r);
return r != null && hn(a.shape, r.shape, "The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"), Cp(o), o;
});
};
}
function Zpe(e) {
return O(fr(e), () => "The f passed in valueAndGrad(f) must be a function"), (t, n) => {
O(t instanceof et, () => "The x passed in valueAndGrad(f)(x) must be a tensor"), O(n == null || n instanceof et, () => "The dy passed in valueAndGrad(f)(x, dy) must be a tensor");
let { grads: s, value: r } = z.gradients(() => e(t), [t], n);
return Cp(s), { grad: s[0], value: r };
};
}
function Jpe(e) {
return O(fr(e), () => "The f passed in valueAndGrads(f) must be a function"), (t, n) => {
O(Array.isArray(t) && t.every((r) => r instanceof et), () => "The args passed in valueAndGrads(f)(args) must be array of tensors"), O(n == null || n instanceof et, () => "The dy passed in valueAndGrads(f)(args, dy) must be a tensor");
let s = z.gradients(() => e(...t), t, n);
return n != null && hn(s.value.shape, n.shape, "The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"), Cp(s.grads), s;
};
}
function ND(e, t) {
O(fr(e), () => "The f passed in variableGrads(f) must be a function"), O(t == null || Array.isArray(t) && t.every((l) => l instanceof kd), () => "The varList passed in variableGrads(f, varList) must be an array of variables");
let n = t != null;
if (!n) {
t = [];
for (let l in z.registeredVariables)
t.push(z.registeredVariables[l]);
}
let s = n ? t.filter((l) => !l.trainable) : null, r = t.length;
t = t.filter((l) => l.trainable), O(t.length > 0, () => `variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);
let a = true, { value: o, grads: i } = z.gradients(e, t, null, a);
O(i.some((l) => l != 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()."), O(o.rank === 0, () => `The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);
let u = {};
return t.forEach((l, c) => {
i[c] != null && (u[l.name] = i[c]);
}), s != null && s.forEach((l) => u[l.name] = null), { value: o, grads: u };
}
function js(e) {
return z.customGrad(e);
}
function Cp(e) {
if (e.filter((n) => n == null).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.`);
}
function TD(e) {
let n = { x: _(e, "x", "softplus") };
return z.runKernel(Rl, n);
}
var Vl = M({ softplus_: TD });
function $D(e) {
let t = _(e, "x", "logSigmoid");
return js((s) => ({ value: vt(Vl(vt(s))), gradFunc: (o) => V(o, qs(vt(s))) }))(t);
}
var ehe = M({ logSigmoid_: $D });
function _D(e, t) {
let n = _(e, "a", "sub"), s = _(t, "b", "sub");
[n, s] = xt(n, s);
let r = { a: n, b: s };
return z.runKernel(fo, r);
}
var ge = M({ sub_: _D });
function AD(e, t = -1) {
let n = _(e, "logits", "logSoftmax");
if (t === -1 && (t = n.rank - 1), t !== n.rank - 1)
throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);
return js((r, a) => {
let i = As(r, t, true), u = ge(r, i), l = ge(le(u, "float32"), Qn(ve(Yn(u), t, true)));
return a([l]), { value: l, gradFunc: (p, d) => {
let [h] = d, f = true, m = Yn(h);
return ge(p, V(ve(p, t, f), m));
} };
})(n);
}
var TS = M({ logSoftmax_: AD });
function ED(e, t = null, n = false) {
let s = _(e, "x", "logSumExp"), r = ts(t, s.shape), a = As(s, r, true), o = ge(s, a), i = Yn(o), u = ve(i, r), l = Qn(u), c = oe(U(a, l.shape), l);
if (n) {
let p = pa(c.shape, r);
return U(c, p);
}
return c;
}
var RD = M({ logSumExp_: ED });
function DD(e, t) {
let n = _(e, "a", "logicalAnd", "bool"), s = _(t, "b", "logicalAnd", "bool");
at(n.shape, s.shape);
let r = { a: n, b: s };
return z.runKernel(Ni, r);
}
var Ds = M({ logicalAnd_: DD });
function FD(e) {
let n = { x: _(e, "x", "logicalNot", "bool") };
return z.runKernel(Ti, n);
}
var db = M({ logicalNot_: FD });
function OD(e, t) {
let n = _(e, "a", "logicalOr", "bool"), s = _(t, "b", "logicalOr", "bool");
at(n.shape, s.shape);
let r = { a: n, b: s };
return z.runKernel(Il, r);
}
var $S = M({ logicalOr_: OD });
function PD(e, t) {
let n = _(e, "a", "logicalXor", "bool"), s = _(t, "b", "logicalXor", "bool");
return at(n.shape, s.shape), Ds($S(e, t), db(Ds(e, t)));
}
var the = M({ logicalXor_: PD });
var qc = 2147483648;
function zD(e, t, n = "left") {
let s = _(e, "sortedSequence", "searchSorted"), r = _(t, "values", "searchSorted"), a = s.shape[s.shape.length - 1], o = r.shape[r.shape.length - 1], i = U(s, [-1, a]), u = U(r, [-1, o]);
if (i.rank < 2)
throw new Error("Sorted input argument must be at least 2-dimensional");
if (i.shape[0] !== u.shape[0])
throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");
if (dt(u.shape) >= qc)
throw new Error(`values tensor size must less than ${qc}`);
if (i.shape[1] >= qc)
throw new Error(`trailing dim_size must less than ${qc} for int32 output type, was ${i.shape[1]}`);
let l = { sortedSequence: i, values: u }, c = { side: n };
return z.runKernel(Mg, l, c);
}
var _S = M({ searchSorted_: zD });
function LD(e, t) {
return _S(e, t, "left");
}
function MD(e, t, n, s, r) {
let a = _(e, "x", "maxPool"), o = 1, i = a, u = false;
a.rank === 3 && (u = true, i = U(a, [1, a.shape[0], a.shape[1], a.shape[2]])), O(i.rank === 4, () => `Error in maxPool: input must be rank 4 but got rank ${i.rank}.`), O(Ps(n, o), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`), fn("maxPool", s, r);
let l = { x: i }, c = { filterSize: t, strides: n, pad: s, dimRoundingMode: r }, p = z.runKernel(ja, l, c);
return u ? U(p, [p.shape[1], p.shape[2], p.shape[3]]) : p;
}
var pb = M({ maxPool_: MD });
function BD(e, t = [1, 1, 1], n, s, r, a = "NDHWC") {
let o = _(e, "x", "maxPool3d"), i = o, u = false;
o.rank === 4 && (u = true, i = U(o, [1, o.shape[0], o.shape[1], o.shape[2], o.shape[3]])), O(i.rank === 5, () => `Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`), O(a === "NDHWC", () => `Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`), fn("maxPool3d", s, r);
let l = { x: i }, c = { filterSize: t, strides: n, pad: s, dimRoundingMode: r, dataFormat: a }, p = z.runKernel(lp, l, c);
return u ? U(p, [p.shape[1], p.shape[2], p.shape[3], p.shape[4]]) : p;
}
var AS = M({ maxPool3d_: BD });
function VD(e, t, n, s, r = false) {
let o = { x: _(e, "x", "maxPoolWithArgmax") }, i = { filterSize: t, strides: n, pad: s, includeBatchInIndex: r }, u = z.runKernel(Og, o, i);
return { result: u[0], indexes: u[1] };
}
var WD = M({ maxPoolWithArgmax_: VD });
function UD(e, t) {
let n = _(e, "a", "maximum"), s = _(t, "b", "maximum");
[n, s] = xt(n, s), n.dtype === "bool" && (n = le(n, "int32"), s = le(s, "int32")), at(n.shape, s.shape);
let r = { a: n, b: s };
return z.runKernel(qa, r);
}
var Ar = M({ maximum_: UD });
function GD(e, t = null, n = false) {
let r = { x: _(e, "x", "mean") }, a = { axis: t, keepDims: n };
return z.runKernel(Ka, r, a);
}
var It = M({ mean_: GD });
function $t(e, t = "float32") {
if (t === "complex64") {
let s = $t(e, "float32"), r = $t(e, "float32");
return mr(s, r);
}
let n = ep(dt(e), t);
return z.makeTensor(n, e, t);
}
function Ln(e, t = "float32") {
if (t === "complex64") {
let s = Ln(e, "float32"), r = $t(e, "float32");
return mr(s, r);
}
let n = hg(dt(e), t);
return z.makeTensor(n, e, t);
}
function nhe(e, t, { indexing: n = "xy" } = {}) {
if (n !== "xy" && n !== "ij")
throw new TypeError(`${n} is not a valid third argument to meshgrid`);
if (e === void 0)
return [];
let s = _(e, "x", "meshgrid", e instanceof et ? e.dtype : "float32");
if (t === void 0)
return [s];
let r = _(t, "y", "meshgrid", t instanceof et ? t.dtype : "float32"), a = dt(s.shape), o = dt(r.shape);
return n === "xy" ? (s = U(s, [1, -1]), r = U(r, [-1, 1]), [We(Ln([o, 1], s.dtype), s), We(r, Ln([1, a], r.dtype))]) : (s = U(s, [-1, 1]), r = U(r, [1, -1]), [We(s, Ln([1, o], s.dtype)), We(Ln([a, 1], r.dtype), r)]);
}
function HD(e, t) {
let n = _(e, "a", "minimum"), s = _(t, "b", "minimum");
[n, s] = xt(n, s), n.dtype === "bool" && (n = le(n, "int32"), s = le(s, "int32")), at(n.shape, s.shape);
let r = { a: n, b: s };
return z.runKernel(Ya, r);
}
var Np = M({ minimum_: HD });
function qD(e, t, n) {
O(n === "reflect" || n === "symmetric", () => `Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);
let s = _(e, "x", "mirrorPad");
if (s.rank === 0)
throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");
O(t.length === s.rank, () => `Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`);
let r = n === "reflect" ? 1 : 0;
for (let i = 0; i < s.rank; i++)
O(t[i].length === 2, () => "Invalid number of paddings. Must be length of 2 each."), O(t[i][0] >= 0 && t[i][0] <= s.shape[i] - r && t[i][1] >= 0 && t[i][1] <= s.shape[i] - r, () => `Padding in dimension ${i} cannot be greater than or equal to ${s.shape[i] - r} or less than 0 for input of shape ${s.shape}`);
let a = { paddings: t, mode: n }, o = { x: s };
return z.runKernel(Qa, o, a);
}
var jD = M({ mirrorPad_: qD });
function KD(e, t) {
let n = _(e, "a", "mod"), s = _(t, "b", "mod");
[n, s] = xt(n, s);
let r = { a: n, b: s };
return z.runKernel(Cl, r);
}
var XD = M({ mod_: KD });
function YD(e, t = null, n = false) {
e = _(e, "x", "moments");
let s = ts(t, e.shape), r = It(e, s, n), a = r.shape;
n || (a = pa(r.shape, s));
let o = ct(ge(le(e, "float32"), U(r, a))), i = It(o, s, n);
return { mean: r, variance: i };
}
var hb = M({ moments_: YD });
function QD(e, t, n, s) {
let r = _(t, "data", "multiRNNCell"), a = Ku(n, "c", "multiRNNCell"), o = Ku(s, "h", "multiRNNCell"), i = r, u = [];
for (let p = 0; p < e.length; p++) {
let d = e[p](i, a[p], o[p]);
u.push(d[0]), u.push(d[1]), i = d[1];
}
let l = [], c = [];
for (let p = 0; p < u.length; p += 2)
l.push(u[p]), c.push(u[p + 1]);
return [l, c];
}
var she = M({ multiRNNCell_: QD });
function ZD(e, t, n, s = false) {
let r = _(e, "logits", "multinomial"), a = r.size, o = r.rank;
if (a < 2)
throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${a}.`);
if (o > 2)
throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);
n = n || Math.random();
let u = { logits: o === 1 ? U(r, [1, -1]) : r }, l = { numSamples: t, seed: n, normalized: s }, c = z.runKernel(Pg, u, l);
return o === 1 ? U(c, [c.size]) : c;
}
var JD = M({ multinomial_: ZD });
function e3(e, t) {
let n = _(e, "a", "notEqual", "string_or_numeric"), s = _(t, "b", "notEqual", "string_or_numeric");
[n, s] = xt(n, s), at(n.shape, s.shape);
let r = { a: n, b: s };
return z.runKernel(_i, r);
}
var el = M({ notEqual_: e3 });
function t3(e) {
let n = { x: _(e, "x", "onesLike") };
return z.runKernel(Ri, n);
}
var Zn = M({ onesLike_: t3 });
function n3(e, t) {
let n = _(e, "v1", "outerProduct"), s = _(t, "v2", "outerProduct");
O(n.rank === 1 && s.rank === 1, () => `Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${s.rank}.`);
let r = U(n, [-1, 1]), a = U(s, [1, -1]);
return We(r, a);
}
var rhe = M({ outerProduct_: n3 });
function s3(e, t, n = 0) {
let s = _(e, "x", "pad");
if (s.rank === 0)
throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");
let r = { paddings: t, constantValue: n }, a = { x: s };
return z.runKernel(Ja, a, r);
}
var bo = M({ pad_: s3 });
function r3(e, t, n = 0) {
return O(t.length === 2, () => "Invalid number of paddings. Must be length of 2."), bo(e, [t], n);
}
var ahe = M({ pad1d_: r3 });
function a3(e, t, n = 0) {
return O(t.length === 2 && t[0].length === 2 && t[1].length === 2, () => "Invalid number of paddings. Must be length of 2 each."), bo(e, t, n);
}
var ohe = M({ pad2d_: a3 });
function o3(e, t, n = 0) {
return O(t.length === 3 && t[0].length === 2 && t[1].length === 2 && t[2].length === 2, () => "Invalid number of paddings. Must be length of 2 each."), bo(e, t, n);
}
var ihe = M({ pad3d_: o3 });
function i3(e, t, n = 0) {
return O(t.length === 4 && t[0].length === 2 && t[1].length === 2 && t[2].length === 2 && t[3].length === 2, () => "Invalid number of paddings. Must be length of 2 each."), bo(e, t, n);
}
var uhe = M({ pad4d_: i3 });
function u3(e, t, n) {
let s = _(e, "x", "spaceToBatchND");
O(s.rank >= 1 + t.length, () => `input rank ${s.rank} should be > than [blockShape] ${t.length}`), O(n.length === t.length, () => `paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`), O(s.shape.reduce((o, i, u) => u > 0 && u <= t.length ? o && (i + n[u - 1][0] + n[u - 1][1]) % t[u - 1] === 0 : o, true), () => `input spatial dimensions ${s.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);
let r = { x: s }, a = { blockShape: t, paddings: n };
return z.runKernel(Wi, r, a);
}
var fb = M({ spaceToBatchND_: u3 });
function l3(e, t, n, s, r, a, o) {
r == null && (r = [1, 1]), a == null && (a = 1), s === 0 && (s = "valid");
let i = _(e, "x", "maxPool"), u = i, l = false;
i.rank === 3 && (l = true, u = U(i, [1, i.shape[0], i.shape[1], i.shape[2]])), O(Ps(a, r), () => `Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${r}'`);
let c = cS(u.shape, t, a, r, s), p = [c.dilationHeight, c.dilationWidth], d;
s === "same" ? d = d3([c.filterHeight, c.filterWidth], p) : d = [[0, 0], [0, 0]];
let h = p[0] === 1 && p[1] === 1, [f, m] = c3([c.inHeight, c.inWidth], p, d), g = h ? s : "valid", b = h ? u : fb(u, p, f), v = (n === "avg" ? () => nb(b, t, a, g, o) : () => pb(b, t, a, g, o))(), x = h ? v : sb(v, p, m);
return l ? U(x, [x.shape[1], x.shape[2], x.shape[3]]) : x;
}
function c3(e, t, n) {
let s = n.map((c) => c[0]), r = n.map((c) => c[1]), a = e.concat(s, r), o = t.map((c, p) => (c - a[p] % c) % c), i = r.map((c, p) => c + o[p]), u = t.map((c, p) => [s[p], i[p]]), l = t.map((c, p) => [0, o[p]]);
return [u, l];
}
function d3(e, t) {
let s = e.map((o, i) => o + (o - 1) * (t[i] - 1)).map((o) => o - 1), r = s.map((o) => Math.floor(o / 2)), a = s.map((o, i) => o - r[i]);
return s.map((o, i) => [r[i], a[i]]);
}
var lhe = M({ pool_: l3 });
function p3(e, t) {
let n = _(e, "x", "prelu"), s = _(t, "alpha", "prelu"), r = { x: n, alpha: s };
return z.runKernel(to, r);
}
var mb = M({ prelu_: p3 });
function h3(e, t = null, n = false) {
let s = _(e, "x", "prod");
s.dtype === "bool" && (s = le(s, "int32"));
let r = { x: s }, a = { axis: t, keepDims: n };
return z.runKernel(no, r, a);
}
var ES = M({ prod_: h3 });
function f3(e, t, n) {
let s = dt(e), r = null;
if (n == null || n === "float32")
r = new Float32Array(s);
else if (n === "int32")
r = new Int32Array(s);
else if (n === "bool")
r = new Uint8Array(s);
else
throw new Error(`Unknown data type ${n}`);
for (let a = 0; a < s; a++)
r[a] = t();
return z.makeTensor(r, e, n);
}
var che = M({ rand_: f3 });
var gb = wa(Qd());
var bb = class {
constructor(e, t, n, s, r) {
this.mean = e, this.stdDev = t, this.dtype = n, this.nextVal = NaN, this.truncated = s, this.truncated && (this.upper = this.mean + this.stdDev * 2, this.lower = this.mean - this.stdDev * 2);
let a = r || Math.random();
this.random = gb.alea(a.toString());
}
nextValue() {
if (!isNaN(this.nextVal)) {
let s = this.nextVal;
return this.nextVal = NaN, s;
}
let e, t, n = false;
for (; !n; ) {
let s, r, a;
do
s = 2 * this.random() - 1, r = 2 * this.random() - 1, a = s * s + r * r;
while (a >= 1 || a === 0);
let o = Math.sqrt(-2 * Math.log(a) / a);
e = this.mean + this.stdDev * s * o, t = this.mean + this.stdDev * r * o, (!this.truncated || this.isValidTruncated(e)) && (n = true);
}
return (!this.truncated || this.isValidTruncated(t)) && (this.nextVal = this.convertValue(t)), this.convertValue(e);
}
convertValue(e) {
return this.dtype == null || this.dtype === "float32" ? e : Math.round(e);
}
isValidTruncated(e) {
return e <= this.upper && e >= this.lower;
}
};
var m3 = class {
constructor(e, t, n, s) {
this.alpha = e, this.beta = 1 / t, this.dtype = n;
let r = s || Math.random();
this.randu = gb.alea(r.toString()), this.randn = new bb(0, 1, n, false, this.randu()), e < 1 ? this.d = e + 2 / 3 : this.d = e - 1 / 3, this.c = 1 / Math.sqrt(9 * this.d);
}
nextValue() {
let e, t, n, s, r, a;
for (; ; ) {
do
s = this.randn.nextValue(), a = 1 + this.c * s;
while (a <= 0);
if (a *= a * a, e = s * s, t = 1 - 0.331 * e * e, n = 0.5 * e + this.d * (1 - a + Math.log(a)), r = this.randu(), r < t || Math.log(r) < n)
break;
}
return a = 1 / this.beta * this.d * a, this.alpha < 1 && (a *= Math.pow(this.randu(), 1 / this.alpha)), this.convertValue(a);
}
convertValue(e) {
return this.dtype === "float32" ? e : Math.round(e);
}
};
var g3 = class {
constructor(e = 0, t = 1, n, s) {
if (this.canReturnFloat = () => this.dtype == null || this.dtype === "float32", this.min = e, this.range = t - e, this.dtype = n, s == null && (s = Math.random()), typeof s == "number" && (s = s.toString()), !this.canReturnFloat() && this.range <= 1)
throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);
this.random = gb.alea(s);
}
convertValue(e) {
return this.canReturnFloat() ? e : Math.round(e);
}
nextValue() {
return this.convertValue(this.min + this.range * this.random());
}
};
function b3(e, t, n = 1, s = "float32", r) {
if (n == null && (n = 1), s == null && (s = "float32"), s !== "float32" && s !== "int32")
throw new Error(`Unsupported data type ${s}`);
let a = new m3(t, n, s, r), o = Ae(e, s);
for (let i = 0; i < o.values.length; i++)
o.values[i] = a.nextValue();
return o.toTensor();
}
var dhe = M({ randomGamma_: b3 });
function y3(e, t = 0, n = 1, s, r) {
if (s != null && s === "bool")
throw new Error(`Unsupported data type ${s}`);
let a = new bb(t, n, s, false, r), o = Ae(e, s);
for (let i = 0; i < o.values.length; i++)
o.values[i] = a.nextValue();
return o.toTensor();
}
var v3 = M({ randomNormal_: y3 });
function x3(e, t = 0, n = 1, s = "float32", r) {
let a = Ae(e, s), o = new g3(t, n, null, r);
for (let i = 0; i < a.values.length; i++)
a.values[i] = o.nextValue();
return a.toTensor();
}
var Wl = M({ randomUniform_: x3 });
function tl(e, t, n = 1, s = "float32") {
if (n === 0)
throw new Error("Cannot have a step of zero");
let r = { start: e, stop: t, step: n, dtype: s };
return z.runKernel(Tl, {}, r);
}
function w3(e) {
let n = { x: _(e, "x", "reciprocal") };
return z.runKernel($l, n);
}
var k3 = M({ reciprocal_: w3 });
function S3(e) {
let n = { x: _(e, "x", "relu") };
return z.runKernel(so, n);
}
var Xs = M({ relu_: S3 });
function I3(e) {
let n = { x: _(e, "x", "relu6") };
return z.runKernel(ao, n);
}
var RS = M({ relu6_: I3 });
function C3(e, t) {
let s = { x: _(e, "x", "reverse") }, r = { dims: t };
return z.runKernel(Pi, s, r);
}
var Jn = M({ reverse_: C3 });
function N3(e) {
let t = _(e, "x", "reverse");
return O(t.rank === 1, () => `Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`), Jn(t, 0);
}
var phe = M({ reverse1d_: N3 });
function T3(e, t) {
let n = _(e, "x", "reverse");
return O(n.rank === 2, () => `Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`), Jn(n, t);
}
var hhe = M({ reverse2d_: T3 });
function $3(e, t) {
let n = _(e, "x", "reverse");
return O(n.rank === 3, () => `Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`), Jn(n, t);
}
var fhe = M({ reverse3d_: $3 });
function _3(e, t) {
let n = _(e, "x", "reverse");
return O(n.rank === 4, () => `Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`), Jn(n, t);
}
var mhe = M({ reverse4d_: _3 });
function A3(e) {
let n = { x: _(e, "x", "round") };
return z.runKernel(zi, n);
}
var DS = M({ round_: A3 });
function E3(e) {
let n = { x: _(e, "x", "rsqrt", "float32") };
return z.runKernel(oo, n);
}
var FS = M({ rsqrt_: E3 });
function R3(e) {
let n = { x: _(e, "x", "selu") };
return z.runKernel(Al, n);
}
var OS = M({ selu_: R3 });
function D3(e, t, n, s, r, a = [1, 1], o = "NHWC") {
let i = _(e, "x", "separableConv2d"), u = _(t, "depthwiseFilter", "separableConv2d"), l = _(n, "pointwiseFilter", "separableConv2d"), c = i, p = false;
if (i.rank === 3 && (p = true, c = U(i, [1, i.shape[0], i.shape[1], i.shape[2]])), o === "NCHW")
throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");
O(c.rank === 4, () => `Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`), O(u.rank === 4, () => `Error in separableConv2d: depthwise filter must be rank 4, but got rank ${u.rank}.`), O(l.rank === 4, () => `Error in separableConv2d: pointwise filter must be rank 4, but got rank ${u.rank}.`), O(l.shape[0] === 1, () => `Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${l.shape[0]}.`), O(l.shape[1] === 1, () => `Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${l.shape[1]}.`);
let d = u.shape[2], h = u.shape[3];
O(l.shape[2] === d * h, () => `Error in separableConv2d: the third dimension of pointwise filter must be ${d * h}, but got ${l.shape[2]}.`);
let f = kp(c, u, s, r, o, a), g = da(f, l, 1, "valid", o);
return p ? U(g, [g.shape[1], g.shape[2], g.shape[3]]) : g;
}
var F3 = M({ separableConv2d_: D3 });
async function O3(e, t) {
let n = _(e, "x", "setdiff1d"), s = _(t, "y", "setdiff1d");
O(n.dtype === s.dtype, () => `x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`), O(n.rank === 1, () => `x should be 1D tensor, but got x (${n.shape}).`), O(s.rank === 1, () => `y should be 1D tensor, but got y (${s.shape}).`);
let r = await n.data(), a = await s.data(), o = new Set(a), i = 0;
for (let c = 0; c < r.length; c++)
o.has(r[c]) || i++;
let u = new Vt([i], n.dtype), l = new Vt([i], "int32");
for (let c = 0, p = 0; c < r.length; c++)
o.has(r[c]) || (u.values[p] = r[c], l.values[p] = c, p++);
return [u.toTensor(), l.toTensor()];
}
var P3 = O3;
function z3(e) {
let n = { x: _(e, "x", "sign") };
return z.runKernel(El, n);
}
var L3 = M({ sign_: z3 });
function M3(e) {
let n = { x: _(e, "x", "sin", "float32") };
return z.runKernel(io, n);
}
var PS = M({ sin_: M3 });
function B3(e) {
let n = { x: _(e, "x", "sinh") };
return z.runKernel(Vi, n);
}
var zS = M({ sinh_: B3 });
function V3(e, t, n) {
let s = _(e, "x", "slice1d");
return O(s.rank === 1, () => `slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`), qe(s, [t], [n]);
}
var yb = M({ slice1d_: V3 });
function W3(e, t, n) {
let s = _(e, "x", "slice2d");
return O(s.rank === 2, () => `slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`), qe(s, t, n);
}
var LS = M({ slice2d_: W3 });
function U3(e, t, n) {
let s = _(e, "x", "slice3d");
return O(s.rank === 3, () => `slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`), qe(s, t, n);
}
var vb = M({ slice3d_: U3 });
function G3(e, t, n) {
let s = _(e, "x", "slice4d");
return O(s.rank === 4, () => `slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`), qe(s, t, n);
}
var Td = M({ slice4d_: G3 });
function H3(e, t = -1) {
let n = _(e, "logits", "softmax", "float32");
if (t === -1 && (t = n.rank - 1), t !== n.rank - 1)
throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);
let s = { logits: n }, r = { dim: t };
return z.runKernel(po, s, r);
}
var xb = M({ softmax_: H3 });
function q3(e) {
O(e.dtype === "complex64", () => `The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);
let t = { input: e };
return z.runKernel(_g, t);
}
var wb = M({ fft_: q3 });
function j3(e) {
O(e.dtype === "complex64", () => `The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);
let t = { input: e };
return z.runKernel(Ag, t);
}
var $d = M({ ifft_: j3 });
function K3(e) {
let t = e.shape[e.shape.length - 1], n = e.size / t, s;
if (t <= 2) {
let r = U(e, [n, t]);
s = $d(r);
} else {
let r = [n, 2 * (t - 1)], a = U(Xu(e), [n, t]), o = U(wp(e), [n, t]), i = Jn(qe(a, [0, 1], [n, t - 2]), 1), u = V(Jn(qe(o, [0, 1], [n, t - 2]), 1), we(-1)), l = Ft([a, i], 1), c = Ft([o, u], 1), p = U(mr(l, c), [r[0], r[1]]);
s = $d(p);
}
if (s = Xu(s), e.rank === 3 && e.shape[0] !== 0) {
let r = s, a = e.shape[0];
s = U(s, [a, s.shape[0] / a, s.shape[1]]), r.dispose();
}
return s;
}
var MS = M({ irfft_: K3 });
function X3(e, t, n = 0) {
let r = { x: _(e, "x", "split") }, a = { numOrSizeSplits: t, axis: n };
return z.runKernel(Ui, r, a);
}
var Bn = M({ split_: X3 });
function Y3(e, t) {
O(e.dtype === "float32", () => `The dtype for rfft() must be real value but got ${e.dtype}`);
let n = e.shape[e.shape.length - 1], s = e.size / n, r;
if (t != null && t < n) {
let f = e.shape.map((g) => 0), m = e.shape.map((g) => g);
m[e.shape.length - 1] = t, r = qe(e, f, m), n = t;
} else if (t != null && t > n) {
let f = e.shape.map((m) => m);
f[e.shape.length - 1] = t - n, r = Ft([e, $t(f)], e.shape.length - 1), n = t;
} else
r = e;
let a = je(r), o = U(mr(r, a), [s, n]), i = wb(o), u = Math.floor(n / 2) + 1, l = Xu(i), c = wp(i), p = Bn(l, [u, n - u], l.shape.length - 1), d = Bn(c, [u, n - u], c.shape.length - 1), h = r.shape.slice();
return h[r.shape.length - 1] = u, U(mr(p[0], d[0]), h);
}
var kb = M({ rfft_: Y3 });
function Q3(e, t) {
let n = _(e, "a", "squaredDifference"), s = _(t, "b", "squaredDifference");
[n, s] = xt(n, s), at(n.shape, s.shape);
let r = { a: n, b: s }, a = {};
return z.runKernel(ho, r, a);
}
var BS = M({ squaredDifference_: Q3 });
function Z3(e, t) {
let n = _(e, "x", "squeeze");
return U(n, ak(n.shape, t).newShape);
}
var br = M({ squeeze_: Z3 });
function J3(e, t = 0) {
let n = Ku(e, "tensors", "stack", "string_or_numeric");
O(n.length >= 1, () => "Pass at least one tensor to tf.stack"), n.length > 0 && O(t <= n[0].rank, () => "Axis must be <= rank of the tensor");
let s = n, r = { axis: t };
return z.runKernel(Fi, s, r);
}
var es = M({ stack_: J3 });
function eF(e, t = 0) {
let s = { x: _(e, "x", "step") }, r = { alpha: t };
return z.runKernel(go, s, r);
}
var Tp = M({ step_: eF });
function tF(e, t, n, s, r = 0, a = 0, o = 0, i = 0, u = 0) {
let c = { x: _(e, "x", "stridedSlice", "string_or_numeric") }, p = { begin: t, end: n, strides: s, beginMask: r, endMask: a, ellipsisMask: o, newAxisMask: i, shrinkAxisMask: u };
return z.runKernel(Gi, c, p);
}
var nF = M({ stridedSlice_: tF });
function sF(e) {
let n = { x: _(e, "x", "tan", "float32") };
return z.runKernel(Hi, n);
}
var rF = M({ tan_: sF });
function Zt(e, t) {
ka(e);
let n = Rs(e, t);
if (n.length !== 1)
throw new Error("tensor1d() requires values to be a flat/TypedArray");
return $r(e, null, n, t);
}
function Zo(e, t, n) {
if (ka(e), t != null && t.length !== 2)
throw new Error("tensor2d() requires shape to have two numbers");
let s = Rs(e, n);
if (s.length !== 2 && s.length !== 1)
throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");
if (s.length === 1 && t == null)
throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");
return $r(e, t, s, n);
}
function ghe(e, t, n) {
if (ka(e), t != null && t.length !== 4)
throw new Error("tensor4d() requires shape to have four numbers");
let s = Rs(e, n);
if (s.length !== 4 && s.length !== 1)
throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");
if (s.length === 1 && t == null)
throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");
return $r(e, t, s, n);
}
function bhe(e, t, n) {
if (ka(e), t != null && t.length !== 5)
throw new Error("tensor5d() requires shape to have five numbers");
let s = Rs(e, n);
if (s.length !== 5 && s.length !== 1)
throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");
if (s.length === 1 && t == null)
throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");
return $r(e, t, s, n);
}
function yhe(e, t, n) {
if (ka(e), t != null && t.length !== 6)
throw new Error("tensor6d() requires shape to have six numbers");
let s = Rs(e, n);
if (s.length !== 6 && s.length !== 1)
throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");
if (s.length === 1 && t == null)
throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");
return t = t || s, $r(e, t, s, n);
}
function aF(e, t = 1, n = true) {
let s = _(e, "x", "topk");
if (s.rank === 0)
throw new Error("topk() expects the input to be of rank 1 or higher");
let r = s.shape[s.shape.length - 1];
if (t < 0)
throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);
if (t > r)
throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);
let a = { x: s }, o = { k: t, sorted: n }, [i, u] = z.runKernel(qi, a, o);
return { values: i, indices: u };
}
var oF = M({ topk_: aF });
function iF(e, t = 0, n = 1, s, r) {
if (s != null && s === "bool")
throw new Error("Unsupported data type $ { dtype }");
let a = new bb(t, n, s, true, r), o = Ae(e, s);
for (let i = 0; i < o.values.length; i++)
o.values[i] = a.nextValue();
return o.toTensor();
}
var Sb = M({ truncatedNormal_: iF });
function uF(e, t = 0) {
let n = _(e, "x", "unique", "string_or_numeric");
O(n.rank > 0, () => "The input tensor must be at least 1D");
let s = { x: n }, r = { axis: t }, [a, o] = z.runKernel(Wg, s, r);
return { values: a, indices: o };
}
var Ix = M({ unique_: uF });
function lF(e, t, n) {
let s = _(e, "x", "unsortedSegmentSum"), r = _(t, "segmentIds", "unsortedSegmentSum", "int32");
O(ei(n), () => "numSegments must be of dtype int");
let a = { x: s, segmentIds: r }, o = { numSegments: n };
return z.runKernel(gp, a, o);
}
var cF = M({ unsortedSegmentSum_: lF });
function dF(e, t = 0) {
let n = _(e, "x", "unstack", "string_or_numeric");
O(t >= -n.shape.length && t < n.shape.length, () => `Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);
let s = { value: n }, r = { axis: t };
return z.runKernel(Ki, s, r);
}
var Fs = M({ unstack_: dF });
function pF(e, t) {
return _S(e, t, "right");
}
function hF(e, t = true, n, s) {
return z.makeVariable(e, t, n, s);
}
function VS(e, t) {
let n = [];
for (let a = 0; a < t.length; a++)
t[a] && n.push(a);
let s = Ae(e, "int32"), r = Ae([n.length, e.length], "int32");
for (let a = 0; a < n.length; a++) {
let o = s.indexToLoc(n[a]), i = a * e.length;
r.values.set(o, i);
}
return r.toTensor();
}
async function fF(e) {
let t = _(e, "condition", "whereAsync", "bool"), n = await t.data(), s = VS(t.shape, n);
return e !== t && t.dispose(), s;
}
var WS = fF;
async function mF(e, t, n) {
let s = _(e, "tensor", "boolMask"), r = _(t, "mask", "boolMask", "bool"), a = n == null ? 0 : n, o = r.rank, i = s.shape;
O(o > 0, () => "mask cannot be scalar"), hn(i.slice(a, a + o), r.shape, "mask's shape must match the first K dimensions of tensor's shape,");
let u = 1;
for (let m = a; m < a + o; m++)
u *= i[m];
let l = i.slice(0, a).concat([u], i.slice(a + o)), c = U(s, l), p = U(r, [-1]), d = await WS(p), h = br(d, [1]), f = Ju(c, h, a);
return e !== s && s.dispose(), t !== r && r.dispose(), h.dispose(), c.dispose(), p.dispose(), d.dispose(), f;
}
var vhe = mF;
function gF(e, t, n, s, r = true) {
let a = _(e, "v", "movingAverage"), o = _(t, "x", "movingAverage"), i = _(n, "decay", "movingAverage");
Sk(a, o), O(Ir(a.shape, o.shape), () => "Shape mismatch in v and x");
let u = we(1), l = ge(u, i), c = V(ge(o, a), l);
if (r) {
O(s != null, () => "When using zeroDebias: true, step is required.");
let p = _(s, "step", "movingAverage");
c = xe(c, ge(u, ha(i, p)));
}
return oe(a, c);
}
var xhe = M({ movingAverage_: gF });
function bF(e, t, n) {
let s = _(e, "indices", "scatterND", "int32"), r = _(t, "updates", "scatterND");
Zg(r, s, n);
let a = { indices: s, updates: r }, o = { shape: n };
return z.runKernel(Li, a, o);
}
var yF = M({ scatterND_: bF });
function vF(e, t, n, s) {
if (e.dtype !== "int32")
throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);
if (e.rank > 2)
throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);
let r = e.rank > 0 ? e.shape[0] : 1, a = e.rank > 1 ? e.shape[1] : 1;
if (n.length !== a)
throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${a}.`);
let o = t.size;
if (!(t.rank === 0 || t.rank === 1 && o === r))
throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${r}]`);
if (t.dtype !== s.dtype)
throw new Error("sparseValues.dtype must match defaultValues.dtype");
}
function xF(e, t, n, s = 0) {
let r = _(e, "sparseIndices", "sparseToDense", "int32"), a = _(t, "sparseValues", "sparseToDense", "string_or_numeric"), o = _(s, "defaultValue", "sparseToDense", a.dtype);
vF(r, a, n, o);
let i = { sparseIndices: r, sparseValues: a, defaultValue: o }, u = { outputShape: n };
return z.runKernel(fp, i, u);
}
var US = M({ sparseToDense_: xF });
function wF(e, t) {
let n = _(t, "indices", "gatherND", "int32"), r = { params: _(e, "x", "gatherND", "string_or_numeric"), indices: n };
return z.runKernel(ki, r);
}
var kF = M({ gatherND_: wF });
function SF(e, t) {
if (t == null)
return e.shape.slice();
if (Ir(e.shape, t))
return t;
if (e.shape.length === t.length) {
let n = [];
for (let s = 0; s < e.shape.length; s++)
t[s] == null && e.shape[s] != null ? n.push(e.shape[s]) : n.push(t[s]);
return n;
}
return t;
}
function IF(e, t, n, s) {
let r = _(e, "x", "dropout");
if (O(r.dtype === "float32", () => `x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`), O(t >= 0 && t < 1, () => `rate must be a float in the range [0, 1), but got ${t}.`), t === 0)
return e instanceof et ? r.clone() : r;
let a = SF(r, n), o = 1 - t, i = xe(Ip(oe(Wl(a, 0, 1, "float32", s), o)), o);
return V(r, i);
}
var CF = M({ dropout_: IF });
function NF(e) {
return Math.floor(Math.pow(2, Math.ceil(Math.log(e) / Math.log(2))));
}
function GS(e, t, n) {
let s = 1 - e % 2, r = new Float32Array(e);
for (let a = 0; a < e; ++a) {
let o = 2 * Math.PI * a / (e + s - 1);
r[a] = t - n * Math.cos(o);
}
return Zt(r, "float32");
}
async function TF(e, t, n = 1) {
let s = _(e, "predictions", "inTopK"), r = _(t, "targets", "inTopK");
O(s.rank > 1, () => `inTopK() expects the predictions to be of rank 2 or higher, but got ${s.rank}`), O(s.rank - 1 === r.rank, () => `predictions rank should be 1 larger than targets rank, but got predictions rank ${s.rank} and targets rank ${r.rank}`), hn(s.shape.slice(0, s.shape.length - 1), r.shape, "predictions's shape should be align with the targets' shape, except the last dimension.");
let a = s.shape[s.shape.length - 1];
O(n > 0 && n <= a, () => `'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`);
let o = await s.data(), i = await r.data(), [u, l] = [o.length / a, a], c = ok("bool", u);
for (let p = 0; p < u; p++) {
let d = p * l, h = o.subarray(d, d + l), f = [];
for (let m = 0; m < h.length; m++)
f.push({ value: h[m], index: m });
f.sort((m, g) => g.value - m.value), c[p] = 0;
for (let m = 0; m < n; m++)
if (f[m].index === i[p]) {
c[p] = 1;
break;
}
}
return e !== s && s.dispose(), t !== r && r.dispose(), ms(c, r.shape, "bool");
}
var whe = TF;
var fa = {};
Ee(fa, { conv2d: () => AF, depthwiseConv2d: () => FF, matMul: () => PF });
function $F(e, t, n, s, r, a = "NHWC", o) {
let i = e;
e.rank === 3 && (i = U(e, [1, e.shape[0], e.shape[1], e.shape[2]]));
let u = t;
u.rank === 3 && (u = U(t, [1, t.shape[0], t.shape[1], t.shape[2]])), O(i.rank === 4, () => `Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`), O(u.rank === 4, () => `Error in conv2dDerFilter: dy must be rank 4, but got shape ${u.shape}.`), O(n.length === 4, () => `Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);
let l = a === "NHWC" ? i.shape[3] : i.shape[1], c = a === "NHWC" ? u.shape[3] : u.shape[1];
O(l === n[2], () => `Error in conv2dDerFilter: depth of input ${l}) must match input depth in filter (${n[2]}.`), O(c === n[3], () => `Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${n[3]}).`), fn("conv2dDerFilter", r, o);
let p = { x: i, dy: u }, d = { strides: s, pad: r, dataFormat: a, dimRoundingMode: o, filterShape: n };
return z.runKernel(wg, p, d);
}
var Ib = M({ conv2DBackpropFilter_: $F });
function $p(e, t, n) {
if (n == null || n === "linear")
return e;
if (n === "relu")
return V(e, Tp(t));
throw new Error(`Cannot compute gradient for fused activation ${n}.`);
}
function _p(e, t) {
let n = t, s = _t(e.shape, t.shape);
return s.length > 0 && (n = ve(n, s)), U(n, e.shape);
}
function Ap(e, t, n, s) {
if (t === "linear")
return e;
if (t === "relu")
return Xs(e);
if (t === "elu")
return Sp(e);
if (t === "relu6")
return RS(e);
if (t === "prelu")
return mb(e, n);
if (t === "leakyrelu")
return lb(e, s);
if (t === "sigmoid")
return qs(e);
throw new Error(`Unknown fused activation ${t}.`);
}
var Ep = (e, t) => !(e > 0) || t === "linear";
function _F({ x: e, filter: t, strides: n, pad: s, dataFormat: r = "NHWC", dilations: a = [1, 1], dimRoundingMode: o, bias: i, activation: u = "linear", preluActivationWeights: l, leakyreluAlpha: c }) {
if (u = u || "linear", Ep(z.state.gradientDepth, u) === false) {
O(r === "NHWC", () => `Error in fused conv2d: got dataFormat of ${r} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);
let I = da(e, t, n, s, r, a, o);
return i != null && (I = oe(I, i)), Ap(I, u, l, c);
}
let p = _(e, "x", "conv2d", "float32"), d = _(t, "filter", "conv2d", "float32"), h = p, f = false;
p.rank === 3 && (f = true, h = U(p, [1, p.shape[0], p.shape[1], p.shape[2]])), O(h.rank === 4, () => `Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`), O(d.rank === 4, () => `Error in fused conv2d: filter must be rank 4, but got rank ${d.rank}.`), fn("fused conv2d", s, o);
let m = r === "NHWC" ? h.shape[3] : h.shape[1];
O(d.shape[2] === m, () => `Error in conv2d: depth of input (${m}) must match input depth for filter ${d.shape[2]}.`), O(Ps(n, a), () => `Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);
let g = Ml(h.shape, d.shape, n, a, s, o), b;
i != null && (b = _(i, "bias", "fused conv2d"), [b] = xt(b, p), r === "NHWC" ? at(g.outShape, b.shape) : (O(b.shape.length <= 1, () => `Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${b.shape.length}.`), O(b.shape.length === 0 || b.shape[0] === g.outChannels || b.shape[0] === 1, () => `Error in fused conv2d: bias shape (${b.shape}) is not compatible with the number of output channels (${g.outChannels})`)));
let y;
if (l != null) {
let I = l.shape;
if (O(I.length <= 1 || I.length === 3, () => `Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${I.length}.`), I.length === 1)
O(I[0] === 1 || I[0] === g.outChannels, () => `Error in fused conv2d: PReLU activation weights (${I}) is not compatible with the number of output channels (${g.outChannels}).`);
else if (I.length === 3)
try {
at(I, g.outShape);
} catch ($) {
let R = `Error in fused conv2d: PReLU activation weights (${I}) is not compatible with the output shape of the conv2d (${g.outShape}).`;
throw Error(R);
}
y = _(l, "prelu weights", "fused conv2d");
}
let v = (I, $) => {
O(r === "NHWC", () => `Error in gradient of fused conv2D: got dataFormat of ${r} but only NHWC is currently supported.`);
let [R, E, P, A] = $, D = $p(I, P, u);
O(gr(a), () => `Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);
let T = rb(E.shape, D, R, n, s), L = Ib(E, D, R.shape, n, s), W = [T, L];
if (A != null) {
let j = _p(A, D);
W.push(j);
}
return W;
}, x = { x: h, filter: d, bias: b, preluActivationWeights: y }, k = { strides: n, pad: s, dataFormat: r, dilations: a, dimRoundingMode: o, activation: u, leakyreluAlpha: c };
return i == null ? js(($, R, E) => {
let P = z.runKernel(ia, x, k);
return E([R, $, P]), f && (P = U(P, [P.shape[1], P.shape[2], P.shape[3]])), { value: P, gradFunc: v };
})(h, d) : js(($, R, E, P) => {
let A = z.runKernel(ia, x, k);
return P([R, $, A, E]), f && (A = U(A, [A.shape[1], A.shape[2], A.shape[3]])), { value: A, gradFunc: v };
})(h, d, b);
}
var AF = M({ fusedConv2d_: _F });
function EF(e, t, n, s, r, a = [1, 1], o) {
let i = e;
e.rank === 3 && (i = U(e, [1, e.shape[0], e.shape[1], e.shape[2]]));
let u = t;
u.rank === 3 && (u = U(t, [1, t.shape[0], t.shape[1], t.shape[2]]));
let l = { x: i, dy: u }, c = { strides: s, pad: r, dimRoundingMode: o, dilations: a, filterShape: n };
return z.runKernel(Cg, l, c);
}
var HS = M({ depthwiseConv2dNativeBackpropFilter_: EF });
function RF(e, t, n, s, r, a = [1, 1], o) {
let i = t, u = false;
t.rank === 3 && (u = true, i = U(t, [1, t.shape[0], t.shape[1], t.shape[2]]));
let l = { dy: i, filter: n }, c = { strides: s, pad: r, dimRoundingMode: o, dilations: a, inputShape: e }, p = z.runKernel(Ng, l, c);
return u ? U(p, [p.shape[1], p.shape[2], p.shape[3]]) : p;
}
var qS = M({ depthwiseConv2dNativeBackpropInput_: RF });
function DF({ x: e, filter: t, strides: n, pad: s, dataFormat: r = "NHWC", dilations: a = [1, 1], dimRoundingMode: o, bias: i, activation: u = "linear", preluActivationWeights: l, leakyreluAlpha: c }) {
if (Ep(z.state.gradientDepth, u) === false) {
let k = kp(e, t, n, s, r, a, o);
return i != null && (k = oe(k, i)), Ap(k, u, l, c);
}
let p = _(e, "x", "depthwiseConv2d", "float32"), d = _(t, "filter", "depthwiseConv2d", "float32"), h = p, f = false;
p.rank === 3 && (f = true, h = U(p, [1, p.shape[0], p.shape[1], p.shape[2]])), O(h.rank === 4, () => `Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`), O(d.rank === 4, () => `Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${d.rank}.`), O(h.shape[3] === d.shape[2], () => `Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${d.shape[2]}.`), a == null && (a = [1, 1]), O(Ps(n, a), () => `Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`), fn("fused depthwiseConv2d", s, o);
let m = Ml(h.shape, d.shape, n, a, s, o, true), g;
i != null && (g = _(i, "bias", "fused conv2d"), [g] = xt(g, p), at(m.outShape, g.shape));
let b;
l != null && (b = _(l, "prelu weights", "fused depthwiseConv2d"));
let y = (k, I) => {
O(gr(a), () => `Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);
let [$, R, E, P] = I, A = $p(k, E, u), D = qS(R.shape, A, $, n, s, a, o), T = HS(R, A, $.shape, n, s, a, o);
if (P != null) {
let L = _p(g, A);
return [D, T, L];
}
return [D, T];
}, v = { x: h, filter: d, bias: g, preluActivationWeights: b }, x = { strides: n, pad: s, dataFormat: r, dilations: a, dimRoundingMode: o, activation: u, leakyreluAlpha: c };
return i == null ? js((I, $, R) => {
let E = z.runKernel(ua, v, x);
return R([$, I, E]), f && (E = U(E, [E.shape[1], E.shape[2], E.shape[3]])), { value: E, gradFunc: y };
})(h, d) : js((I, $, R, E) => {
let P = z.runKernel(ua, v, x);
return E([$, I, P, R]), f && (P = U(P, [P.shape[1], P.shape[2], P.shape[3]])), { value: P, gradFunc: y };
})(h, d, g);
}
var FF = M({ fusedDepthwiseConv2d_: DF });
function OF({ a: e, b: t, transposeA: n = false, transposeB: s = false, bias: r, activation: a = "linear", preluActivationWeights: o, leakyreluAlpha: i = 0.2 }) {
if (Ep(z.state.gradientDepth, a) === false) {
let A = We(e, t, n, s);
return r != null && (A = oe(A, r)), Ap(A, a, o, i);
}
let u = _(e, "a", "fused matMul"), l = _(t, "b", "fused matMul");
[u, l] = xt(u, l);
let c = n ? u.shape[u.rank - 2] : u.shape[u.rank - 1], p = s ? l.shape[l.rank - 1] : l.shape[l.rank - 2], d = n ? u.shape[u.rank - 1] : u.shape[u.rank - 2], h = s ? l.shape[l.rank - 2] : l.shape[l.rank - 1], f = u.shape.slice(0, -2), m = l.shape.slice(0, -2), g = dt(f), b = dt(m);
O(c === p, () => `Error in fused matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${u.shape} and ${l.shape} and transposeA=${n} and transposeB=${s} must match.`);
let v = at(u.shape.slice(0, -2), l.shape.slice(0, -2)).concat([d, h]), x = n ? U(u, [g, c, d]) : U(u, [g, d, c]), k = s ? U(l, [b, h, p]) : U(l, [b, p, h]), I;
r != null && (I = _(r, "bias", "fused matMul"), [I] = xt(I, u), at(v, I.shape));
let $;
o != null && ($ = _(o, "prelu weights", "fused matMul"));
let R = (A, D) => {
let [T, L, W, j] = D, Y = $p(U(A, W.shape), W, a), X, Z;
if (!n && !s ? (X = We(Y, L, false, true), Z = We(T, Y, true, false)) : !n && s ? (X = We(Y, L, false, false), Z = We(Y, T, true, false)) : n && !s ? (X = We(L, Y, false, true), Z = We(T, Y, false, false)) : (X = We(L, Y, true, true), Z = We(Y, T, true, true)), r != null) {
let ne = _p(j, Y);
return [X, Z, ne];
} else
return [X, Z];
}, E = { a: x, b: k, bias: I, preluActivationWeights: $ }, P = { transposeA: n, transposeB: s, activation: a, leakyreluAlpha: i };
return r == null ? js((D, T, L) => {
let W = z.runKernel(oa, E, P);
return L([D, T, W]), { value: U(W, v), gradFunc: R };
})(x, k) : js((D, T, L, W) => {
let j = z.runKernel(oa, E, P);
return W([D, T, j, L]), { value: U(j, v), gradFunc: R };
})(x, k, I);
}
var PF = M({ fusedMatMul_: OF });
function zF(e) {
return GS(e, 0.54, 0.46);
}
var LF = M({ hammingWindow_: zF });
function MF(e) {
return GS(e, 0.5, 0.5);
}
var jS = M({ hannWindow_: MF });
function BF(e, t, n, s = false, r = 0) {
let a = 0, o = [];
for (; a + t <= e.size; )
o.push(qe(e, a, t)), a += n;
if (s)
for (; a < e.size; ) {
let i = a + t - e.size, u = Ft([qe(e, a, t - i), Bl([i], r)]);
o.push(u), a += n;
}
return o.length === 0 ? Zo([], [0, t]) : U(Ft(o), [o.length, t]);
}
var KS = M({ frame_: BF });
function VF(e, t, n, s, r = jS) {
s == null && (s = NF(t));
let a = KS(e, t, n), o = V(a, r(t));
return kb(o, s);
}
var WF = M({ stft_: VF });
function UF(e, t, n, s, r = "bilinear", a = 0) {
let o = _(e, "image", "cropAndResize"), i = _(t, "boxes", "cropAndResize", "float32"), u = _(n, "boxInd", "cropAndResize", "int32"), l = i.shape[0];
O(o.rank === 4, () => `Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`), O(i.rank === 2 && i.shape[1] === 4, () => `Error in cropAndResize: boxes must be have size [${l},4] but had shape ${i.shape}.`), O(u.rank === 1 && u.shape[0] === l, () => `Error in cropAndResize: boxInd must be have size [${l}] but had shape ${i.shape}.`), O(s.length === 2, () => `Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`), O(s[0] >= 1 && s[1] >= 1, () => `cropSize must be atleast [1,1], but was ${s}`), O(r === "bilinear" || r === "nearest", () => `method must be bilinear or nearest, but was ${r}`);
let c = { image: o, boxes: i, boxInd: u }, p = { method: r, extrapolationValue: a, cropSize: s };
return z.runKernel(mi, c, p);
}
var GF = M({ cropAndResize_: UF });
function HF(e) {
let t = _(e, "image", "flipLeftRight", "float32");
O(t.rank === 4, () => `Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);
let n = { image: t };
return z.runKernel(xi, n, {});
}
var qF = M({ flipLeftRight_: HF });
function jF(e) {
let t = _(e, "image", "grayscaleToRGB"), n = t.rank - 1, s = t.shape[n];
O(t.rank >= 2, () => `Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`), O(s === 1, () => `Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`);
let r = new Array(t.rank);
return r.fill(1, 0, n), r[n] = 3, hs(t, r);
}
var KF = M({ grayscaleToRGB_: jF });
function XF(e, t, n = 0, s = 0.5) {
let r = _(e, "image", "rotateWithOffset", "float32");
O(r.rank === 4, () => `Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);
let a = { image: r }, o = { radians: t, fillValue: n, center: s };
return z.runKernel(Yi, a, o);
}
var YF = M({ rotateWithOffset_: XF });
function eu(e, t, n, s, r, a) {
s == null && (s = 0.5), r == null && (r = Number.NEGATIVE_INFINITY), a == null && (a = 0);
let o = e.shape[0];
return n = Math.min(n, o), O(0 <= s && s <= 1, () => `iouThreshold must be in [0, 1], but was '${s}'`), O(e.rank === 2, () => `boxes must be a 2D tensor, but was of rank '${e.rank}'`), O(e.shape[1] === 4, () => `boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`), O(t.rank === 1, () => "scores must be a 1D tensor"), O(t.shape[0] === o, () => `scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`), O(0 <= a && a <= 1, () => `softNmsSigma must be in [0, 1], but was '${a}'`), { maxOutputSize: n, iouThreshold: s, scoreThreshold: r, softNmsSigma: a };
}
function QF(e, t, n, s = 0.5, r = Number.NEGATIVE_INFINITY) {
let a = _(e, "boxes", "nonMaxSuppression", "float32"), o = _(t, "scores", "nonMaxSuppression", "float32"), i = eu(a, o, n, s, r);
n = i.maxOutputSize, s = i.iouThreshold, r = i.scoreThreshold;
let u = { maxOutputSize: n, iouThreshold: s, scoreThreshold: r };
return z.runKernel(Ai, { boxes: a, scores: o }, u);
}
var ZF = M({ nonMaxSuppression_: QF });
function JF(e, t, n) {
let s = eO(e, t, n), r = s < 0 ? -(s + 1) : s;
e.splice(r, 0, t);
}
function eO(e, t, n) {
return nO(e, t, n || tO);
}
function tO(e, t) {
return e > t ? 1 : e < t ? -1 : 0;
}
function nO(e, t, n) {
let s = 0, r = e.length, a = 0, o = false;
for (; s < r; ) {
a = s + (r - s >>> 1);
let i = n(t, e[a]);
i > 0 ? s = a + 1 : (r = a, o = !i);
}
return o ? s : -s - 1;
}
function XS(e, t, n, s, r) {
return Cb(e, t, n, s, r, 0);
}
function YS(e, t, n, s, r, a) {
return Cb(e, t, n, s, r, 0, false, a, true);
}
function QS(e, t, n, s, r, a) {
return Cb(e, t, n, s, r, a, true);
}
function Cb(e, t, n, s, r, a, o = false, i = false, u = false) {
let l = [];
for (let g = 0; g < t.length; g++)
t[g] > r && l.push({ score: t[g], boxIndex: g, suppressBeginIndex: 0 });
l.sort(Cx);
let c = a > 0 ? -0.5 / a : 0, p = [], d = [];
for (; p.length < n && l.length > 0; ) {
let g = l.pop(), { score: b, boxIndex: y, suppressBeginIndex: v } = g;
if (b < r)
break;
let x = false;
for (let k = p.length - 1; k >= v; --k) {
let I = sO(e, y, p[k]);
if (I >= s) {
x = true;
break;
}
if (g.score = g.score * rO(s, c, I), g.score <= r)
break;
}
g.suppressBeginIndex = p.length, x || (g.score === b ? (p.push(y), d.push(g.score)) : g.score > r && JF(l, g, Cx));
}
let h = p.length, f = n - h;
i && f > 0 && (p.push(...new Array(f).fill(0)), d.push(...new Array(f).fill(0)));
let m = { selectedIndices: p };
return o && (m.selectedScores = d), u && (m.validOutputs = h), m;
}
function sO(e, t, n) {
let s = e.subarray(t * 4, t * 4 + 4), r = e.subarray(n * 4, n * 4 + 4), a = Math.min(s[0], s[2]), o = Math.min(s[1], s[3]), i = Math.max(s[0], s[2]), u = Math.max(s[1], s[3]), l = Math.min(r[0], r[2]), c = Math.min(r[1], r[3]), p = Math.max(r[0], r[2]), d = Math.max(r[1], r[3]), h = (i - a) * (u - o), f = (p - l) * (d - c);
if (h <= 0 || f <= 0)
return 0;
let m = Math.max(a, l), g = Math.max(o, c), b = Math.min(i, p), y = Math.min(u, d), v = Math.max(b - m, 0) * Math.max(y - g, 0);
return v / (h + f - v);
}
function rO(e, t, n) {
let s = Math.exp(t * n * n);
return n <= e ? s : 0;
}
function Cx(e, t) {
return e.score - t.score || e.score === t.score && t.boxIndex - e.boxIndex;
}
async function aO(e, t, n, s = 0.5, r = Number.NEGATIVE_INFINITY) {
let a = _(e, "boxes", "nonMaxSuppressionAsync"), o = _(t, "scores", "nonMaxSuppressionAsync"), i = eu(a, o, n, s, r);
n = i.maxOutputSize, s = i.iouThreshold, r = i.scoreThreshold;
let u = await Promise.all([a.data(), o.data()]), l = u[0], c = u[1], { selectedIndices: p } = XS(l, c, n, s, r);
return a !== e && a.dispose(), o !== t && o.dispose(), Zt(p, "int32");
}
var oO = aO;
function iO(e, t, n, s = 0.5, r = Number.NEGATIVE_INFINITY, a = 0) {
let o = _(e, "boxes", "nonMaxSuppression"), i = _(t, "scores", "nonMaxSuppression"), u = eu(o, i, n, s, r, a);
n = u.maxOutputSize, s = u.iouThreshold, r = u.scoreThreshold, a = u.softNmsSigma;
let l = { boxes: o, scores: i }, c = { maxOutputSize: n, iouThreshold: s, scoreThreshold: r, softNmsSigma: a }, p = z.runKernel(Ei, l, c);
return { selectedIndices: p[0], selectedScores: p[1] };
}
var uO = M({ nonMaxSuppressionWithScore_: iO });
async function lO(e, t, n, s = 0.5, r = Number.NEGATIVE_INFINITY, a = 0) {
let o = _(e, "boxes", "nonMaxSuppressionAsync"), i = _(t, "scores", "nonMaxSuppressionAsync"), u = eu(o, i, n, s, r, a);
n = u.maxOutputSize, s = u.iouThreshold, r = u.scoreThreshold, a = u.softNmsSigma;
let l = await Promise.all([o.data(), i.data()]), c = l[0], p = l[1], { selectedIndices: d, selectedScores: h } = QS(c, p, n, s, r, a);
return o !== e && o.dispose(), i !== t && i.dispose(), { selectedIndices: Zt(d, "int32"), selectedScores: Zt(h) };
}
var cO = lO;
function dO(e, t, n, s = 0.5, r = Number.NEGATIVE_INFINITY, a = false) {
let o = _(e, "boxes", "nonMaxSuppression"), i = _(t, "scores", "nonMaxSuppression"), u = eu(o, i, n, s, r, null), l = u.maxOutputSize, c = u.iouThreshold, p = u.scoreThreshold, d = { boxes: o, scores: i }, h = { maxOutputSize: l, iouThreshold: c, scoreThreshold: p, padToMaxOutputSize: a }, f = z.runKernel(Nl, d, h);
return { selectedIndices: f[0], validOutputs: f[1] };
}
var pO = M({ nonMaxSuppressionPadded_: dO });
async function hO(e, t, n, s = 0.5, r = Number.NEGATIVE_INFINITY, a = false) {
let o = _(e, "boxes", "nonMaxSuppressionAsync"), i = _(t, "scores", "nonMaxSuppressionAsync"), u = eu(o, i, n, s, r, null), l = u.maxOutputSize, c = u.iouThreshold, p = u.scoreThreshold, [d, h] = await Promise.all([o.data(), i.data()]), { selectedIndices: f, validOutputs: m } = YS(d, h, l, c, p, a);
return o !== e && o.dispose(), i !== t && i.dispose(), { selectedIndices: Zt(f, "int32"), validOutputs: we(m, "int32") };
}
var fO = hO;
function mO(e, t, n = false, s = false) {
let r = _(e, "images", "resizeBilinear");
O(r.rank === 3 || r.rank === 4, () => `Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`), O(t.length === 2, () => `Error in resizeBilinear: new shape must 2D, but got shape ${t}.`), O(s === false || n === false, () => "Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");
let a = r, o = false;
r.rank === 3 && (o = true, a = U(r, [1, r.shape[0], r.shape[1], r.shape[2]]));
let [] = t, i = { images: a }, u = { alignCorners: n, halfPixelCenters: s, size: t }, l = z.runKernel(ro, i, u);
return o ? U(l, [l.shape[1], l.shape[2], l.shape[3]]) : l;
}
var gO = M({ resizeBilinear_: mO });
function bO(e, t, n = false, s = false) {
let r = _(e, "images", "resizeNearestNeighbor");
O(r.rank === 3 || r.rank === 4, () => `Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`), O(t.length === 2, () => `Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`), O(r.dtype === "float32" || r.dtype === "int32", () => "`images` must have `int32` or `float32` as dtype"), O(s === false || n === false, () => "Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");
let a = r, o = false;
r.rank === 3 && (o = true, a = U(r, [1, r.shape[0], r.shape[1], r.shape[2]]));
let [] = t, i = { images: a }, u = { alignCorners: n, halfPixelCenters: s, size: t }, l = z.runKernel(_l, i, u);
return o ? U(l, [l.shape[1], l.shape[2], l.shape[3]]) : l;
}
var yO = M({ resizeNearestNeighbor_: bO });
function vO(e, t = "binary", n = false, s = 0.5) {
let r = _(e, "image", "threshold"), a = 0.2989, o = 0.587, i = 0.114, u = r.shape[0] * r.shape[1], l = V(Zt([s]), 255), c, p, d, h;
if (O(r.rank === 3, () => `Error in threshold: image must be rank 3,but got rank ${r.rank}.`), O(r.shape[2] === 3 || r.shape[2] === 1, () => `Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`), O(r.dtype === "int32" || r.dtype === "float32", () => `Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`), O(t === "otsu" || t === "binary", () => `Method must be binary or otsu, but was ${t}`), r.shape[2] === 3) {
[c, p, d] = Bn(r, [1, 1, 1], -1);
let g = V(c, a), b = V(p, o), y = V(d, i);
h = oe(oe(g, b), y);
} else
h = e;
if (t === "otsu") {
let g = fS(le(DS(h), "int32"), ms([]), 256);
l = xO(g, u);
}
let f = n ? Ji(h, l) : Gn(h, l);
return le(V(f, 255), "int32");
}
function xO(e, t) {
let n = Zt([-1]), s = Zt([0]), r = Zt([0]), a, o, i, u, l, c;
for (let p = 0; p < e.size - 1; p++) {
a = qe(e, 0, p + 1), o = qe(e, p + 1), l = xe(ve(a), t), c = xe(ve(o), t);
let d = ve(V(a, tl(0, a.size)));
i = xe(d, ve(a));
let h = Bl(o.shape, a.size), f = oe(tl(0, o.size), h), m = V(o, f);
u = xe(ve(m), ve(o));
let g = ge(i, u), b = ge(i, u), y = V(l, c);
r = V(V(y, g), b);
let v = Gn(r, s);
s = vn(v, r, s), n = vn(v, Zt([p]), n);
}
return n;
}
var wO = M({ threshold_: vO });
function kO(e, t, n = "nearest", s = "constant", r = 0, a) {
let o = _(e, "image", "transform", "float32"), i = _(t, "transforms", "transform", "float32");
O(o.rank === 4, () => `Error in transform: image must be rank 4,but got rank ${o.rank}.`), O(i.rank === 2 && (i.shape[0] === o.shape[0] || i.shape[0] === 1) && i.shape[1] === 8, () => "Error in transform: Input transform should be batch x 8 or 1 x 8"), O(a == null || a.length === 2, () => `Error in transform: outputShape must be [height, width] or null, but got ${a}.`);
let u = { image: o, transforms: i }, l = { interpolation: n, fillMode: s, fillValue: r, outputShape: a };
return z.runKernel(ji, u, l);
}
var SO = M({ transform_: kO });
function IO(e, t, n) {
O(t % 1 === 0, () => `bandPart(): numLower must be an integer, got ${t}.`), O(n % 1 === 0, () => `bandPart(): numUpper must be an integer, got ${n}.`);
let s = _(e, "a", "bandPart");
O(s.rank >= 2, () => `bandPart(): Rank must be at least 2, got ${s.rank}.`);
let r = s.shape, [a, o] = s.shape.slice(-2);
if (!(t <= a))
throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`);
if (!(n <= o))
throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`);
t < 0 && (t = a), n < 0 && (n = o);
let i = U(tl(0, a, 1, "int32"), [-1, 1]), u = tl(0, o, 1, "int32"), l = ge(i, u), c = Ds(Ji(l, we(+t, "int32")), Zi(l, we(-n, "int32"))), p = $t([a, o], s.dtype);
return U(es(Fs(U(s, [-1, a, o])).map((d) => vn(c, d, p))), r);
}
var CO = M({ bandPart_: IO });
function NO(e) {
let t;
if (Array.isArray(e)) {
t = false, O(e != null && e.length > 0, () => "Gram-Schmidt process: input must not be null, undefined, or empty");
let r = e[0].shape[0];
for (let a = 1; a < e.length; ++a)
O(e[a].shape[0] === r, () => `Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[a].shape[0]} vs. ${r})`);
} else
t = true, e = Bn(e, e.shape[0], 0).map((r) => br(r, [0]));
O(e.length <= e[0].shape[0], () => `Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);
let n = [], s = e;
for (let r = 0; r < e.length; ++r)
n.push(z.tidy(() => {
let a = s[r];
if (r > 0)
for (let o = 0; o < r; ++o) {
let i = V(ve(V(n[o], a)), n[o]);
a = ge(a, i);
}
return xe(a, ub(a, "euclidean"));
}));
return t ? es(n, 0) : n;
}
var TO = M({ gramSchmidt_: NO });
function $O(e, t = false) {
if (O(e.rank >= 2, () => `qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`), e.rank === 2)
return Nx(e, t);
{
let n = e.shape.slice(0, e.shape.length - 2).reduce((u, l) => u * l), s = Fs(U(e, [n, e.shape[e.shape.length - 2], e.shape[e.shape.length - 1]]), 0), r = [], a = [];
s.forEach((u) => {
let [l, c] = Nx(u, t);
r.push(l), a.push(c);
});
let o = U(es(r, 0), e.shape), i = U(es(a, 0), e.shape);
return [o, i];
}
}
function Nx(e, t = false) {
return z.tidy(() => {
O(e.shape.length === 2, () => `qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);
let n = e.shape[0], s = e.shape[1], r = CS(n), a = lr(e), o = Zo([[1]], [1, 1]), i = lr(o), u = n >= s ? s : n;
for (let l = 0; l < u; ++l) {
let c = a, p = i, d = r;
[i, a, r] = z.tidy(() => {
let h = qe(a, [l, l], [n - l, 1]), f = ub(h), m = qe(a, [l, l], [1, 1]), g = vn(Gn(m, 0), Zo([[-1]]), Zo([[1]])), b = ge(m, V(g, f)), y = xe(h, b);
y.shape[0] === 1 ? i = lr(o) : i = Ft([o, qe(y, [1, 0], [y.shape[0] - 1, y.shape[1]])], 0);
let v = vt(xe(We(g, b), f)), x = qe(a, [l, 0], [n - l, s]), k = V(v, i), I = Ge(i);
if (l === 0)
a = ge(x, We(k, We(I, x)));
else {
let E = ge(x, We(k, We(I, x)));
a = Ft([qe(a, [0, 0], [l, s]), E], 0);
}
let $ = Ge(k), R = qe(r, [0, l], [n, r.shape[1] - l]);
if (l === 0)
r = ge(R, We(We(R, i), $));
else {
let E = ge(R, We(We(R, i), $));
r = Ft([qe(r, [0, 0], [n, l]), E], 1);
}
return [i, a, r];
}), De([c, p, d]);
}
return !t && n > s && (r = qe(r, [0, 0], [n, s]), a = qe(a, [0, 0], [s, s])), [r, a];
});
}
var _O = M({ qr_: $O });
var AO = ((e) => (e[e.NONE = 0] = "NONE", e[e.MEAN = 1] = "MEAN", e[e.SUM = 2] = "SUM", e[e.SUM_BY_NONZERO_WEIGHTS = 3] = "SUM_BY_NONZERO_WEIGHTS", e))(AO || {});
function EO(e, t, n = 3) {
let s = _(e, "losses", "computeWeightedLoss"), r = null;
t != null && (r = _(t, "weights", "computeWeightedLoss"));
let a = r == null ? s : V(s, r);
if (n === 0)
return a;
if (n === 2)
return ve(a);
if (n === 1) {
if (r == null)
return It(a);
{
let o = s.size / r.size, i = xe(ve(a), ve(r));
return o > 1 ? xe(i, we(o)) : i;
}
}
if (n === 3) {
if (r == null)
return xe(ve(a), we(s.size));
{
let o = V(r, Ln(s.shape)), i = le(ve(el(o, we(0))), "float32");
return xe(ve(a), i);
}
}
throw Error(`Unknown reduction: ${n}`);
}
var Ys = M({ computeWeightedLoss_: EO });
function RO(e, t, n, s = 3) {
let r = _(e, "labels", "absoluteDifference"), a = _(t, "predictions", "absoluteDifference"), o = null;
n != null && (o = _(n, "weights", "absoluteDifference")), hn(r.shape, a.shape, "Error in absoluteDifference: ");
let i = Lt(ge(r, a));
return Ys(i, o, s);
}
var DO = M({ absoluteDifference_: RO });
function FO(e, t, n, s, r = 3) {
let a = _(e, "labels", "cosineDistance"), o = _(t, "predictions", "cosineDistance"), i = null;
s != null && (i = _(s, "weights", "cosineDistance")), hn(a.shape, o.shape, "Error in cosineDistance: ");
let u = we(1), l = ge(u, ve(V(a, o), n, true));
return Ys(l, i, r);
}
var OO = M({ cosineDistance_: FO });
function PO(e, t, n, s = 3) {
let r = _(e, "labels", "hingeLoss"), a = _(t, "predictions", "hingeLoss"), o = null;
n != null && (o = _(n, "weights", "hingeLoss")), hn(r.shape, a.shape, "Error in hingeLoss: ");
let i = we(1);
r = ge(V(we(2), r), i);
let u = Xs(ge(i, V(r, a)));
return Ys(u, o, s);
}
var zO = M({ hingeLoss_: PO });
function LO(e, t, n, s = 1, r = 3) {
let a = _(e, "labels", "huberLoss"), o = _(t, "predictions", "huberLoss"), i = null;
n != null && (i = _(n, "weights", "huberLoss")), hn(a.shape, o.shape, "Error in huberLoss: ");
let u = we(s), l = Lt(ge(o, a)), c = Np(l, u), p = ge(l, c), d = oe(V(we(0.5), ct(c)), V(u, p));
return Ys(d, i, r);
}
var MO = M({ huberLoss_: LO });
function BO(e, t, n, s = 1e-7, r = 3) {
let a = _(e, "labels", "logLoss"), o = _(t, "predictions", "logLoss"), i = null;
n != null && (i = _(n, "weights", "logLoss")), hn(a.shape, o.shape, "Error in logLoss: ");
let u = we(1), l = we(s), c = vt(V(a, Qn(oe(o, l)))), p = V(ge(u, a), Qn(oe(ge(u, o), l))), d = ge(c, p);
return Ys(d, i, r);
}
var VO = M({ logLoss_: BO });
function WO(e, t, n, s = 3) {
let r = _(e, "labels", "meanSquaredError"), a = _(t, "predictions", "meanSquaredError"), o = null;
n != null && (o = _(n, "weights", "meanSquaredError")), hn(r.shape, a.shape, "Error in meanSquaredError: ");
let i = BS(r, a);
return Ys(i, o, s);
}
var UO = M({ meanSquaredError_: WO });
function GO(e, t) {
let n = _(e, "labels", "sigmoidCrossEntropyWithLogits"), s = _(t, "logits", "sigmoidCrossEntropyWithLogits");
hn(n.shape, s.shape, "Error in sigmoidCrossEntropyWithLogits: ");
let r = Xs(s), a = V(s, n), o = cb(Yn(vt(Lt(s))));
return oe(ge(r, a), o);
}
function HO(e, t, n, s = 0, r = 3) {
let a = _(e, "multiClassLabels", "sigmoidCrossEntropy"), o = _(t, "logits", "sigmoidCrossEntropy"), i = null;
if (n != null && (i = _(n, "weights", "sigmoidCrossEntropy")), hn(a.shape, o.shape, "Error in sigmoidCrossEntropy: "), s > 0) {
let l = we(s), c = we(1), p = we(0.5);
a = oe(V(a, ge(c, l)), V(p, l));
}
let u = GO(a, o);
return Ys(u, i, r);
}
var qO = M({ sigmoidCrossEntropy_: HO });
function jO(e, t, n = -1) {
if (n === -1 && (n = t.rank - 1), n !== t.rank - 1)
throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);
return js((r, a, o) => {
let u = RD(a, [n], true), l = ge(le(a, "float32"), u);
o([r, l]);
let c = vt(V(l, r));
return { value: ve(c, [n]), gradFunc: (h, f) => {
let [m, g] = f, b = pa(h.shape, [n]);
return [V(U(h, b), ge(le(m, "float32"), Yn(g))), V(U(h, b), ge(Yn(g), le(m, "float32")))];
} };
})(e, t);
}
function KO(e, t, n, s = 0, r = 3) {
let a = _(e, "onehotLabels", "softmaxCrossEntropy"), o = _(t, "logits", "softmaxCrossEntropy"), i = null;
if (n != null && (i = _(n, "weights", "softmaxCrossEntropy")), hn(a.shape, o.shape, "Error in softmaxCrossEntropy: "), s > 0) {
let l = we(s), c = we(1), p = we(a.shape[1]);
a = oe(V(a, ge(c, l)), xe(l, p));
}
let u = jO(a, o);
return Ys(u, i, r);
}
var XO = M({ softmaxCrossEntropy_: KO });
function YO(e, t, n, s) {
let r = _(e, "indices", "sparseFillEmptyRows", "int32"), a = _(t, "values", "sparseFillEmptyRows"), o = _(n, "denseShape", "sparseFillEmptyRows", "int32"), i = _(s, "defaultValue", "sparseFillEmptyRows", a.dtype);
if (r.rank !== 2)
throw new Error(`Indices should be Tensor2D but received shape
${r.shape}`);
if (a.rank !== 1)
throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);
if (o.rank !== 1)
throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);
if (i.rank !== 0)
throw new Error(`Default value should be a scalar but received shape ${i.shape}`);
let u = { indices: r, values: a, denseShape: o, defaultValue: i }, l = z.runKernel(dp, u);
return { outputIndices: l[0], outputValues: l[1], emptyRowIndicator: l[2], reverseIndexMap: l[3] };
}
var QO = M({ sparseFillEmptyRows_: YO });
function ZO(e, t, n) {
let s = _(e, "inputIndices", "sparseReshape", "int32"), r = _(t, "inputShape", "sparseReshape", "int32"), a = _(n, "newShape", "sparseReshape", "int32");
if (s.rank !== 2)
throw new Error(`Input indices should be Tensor2D but received shape
${s.shape}`);
if (r.rank !== 1)
throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);
if (a.rank !== 1)
throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);
let o = { inputIndices: s, inputShape: r, newShape: a }, i = z.runKernel(Dl, o);
return { outputIndices: i[0], outputShape: i[1] };
}
var JO = M({ sparseReshape_: ZO });
function eP(e, t, n) {
let s = _(e, "data", "sparseSegmentMean"), r = _(t, "indices", "sparseSegmentMean", "int32"), a = _(n, "segmentIds", "sparseSegmentMean", "int32");
if (s.rank < 1)
throw new Error("Data should be at least 1 dimensional but received scalar");
if (r.rank !== 1)
throw new Error(`Indices should be Tensor1D but received shape
${r.shape}`);
if (a.rank !== 1)
throw new Error(`Segment ids should be Tensor1D but received shape
${a.shape}`);
let o = { data: s, indices: r, segmentIds: a };
return z.runKernel(pp, o);
}
var tP = M({ sparseSegmentMean_: eP });
function nP(e, t, n) {
let s = _(e, "data", "sparseSegmentSum"), r = _(t, "indices", "sparseSegmentSum", "int32"), a = _(n, "segmentIds", "sparseSegmentSum", "int32");
if (s.rank < 1)
throw new Error("Data should be at least 1 dimensional but received scalar");
if (r.rank !== 1)
throw new Error(`Indices should be Tensor1D but received shape
${r.shape}`);
if (a.rank !== 1)
throw new Error(`Segment ids should be Tensor1D but received shape
${a.shape}`);
let o = { data: s, indices: r, segmentIds: a };
return z.runKernel(hp, o);
}
var sP = M({ sparseSegmentSum_: nP });
function rP(e, t, n, s, r, a, o, i) {
let u = _(e, "data", "stringNGrams", "string");
if (u.dtype !== "string")
throw new Error("Data must be of datatype string");
if (u.shape.length !== 1)
throw new Error(`Data must be a vector, saw: ${u.shape}`);
let l = _(t, "dataSplits", "stringNGrams");
if (l.dtype !== "int32")
throw new Error("Data splits must be of datatype int32");
let c = { separator: n, nGramWidths: s, leftPad: r, rightPad: a, padWidth: o, preserveShortSequences: i }, p = { data: u, dataSplits: l }, d = z.runKernel(mp, p, c);
return { nGrams: d[0], nGramsSplits: d[1] };
}
var aP = M({ stringNGrams_: rP });
function oP(e, t, n = true) {
let s = _(e, "input", "stringSplit", "string"), r = _(t, "delimiter", "stringSplit", "string");
if (s.rank !== 1)
throw new Error(`Input should be Tensor1D but received shape ${s.shape}`);
if (r.rank !== 0)
throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);
let a = { skipEmpty: n }, o = { input: s, delimiter: r }, i = z.runKernel(Bg, o, a);
return { indices: i[0], values: i[1], shape: i[2] };
}
var iP = M({ stringSplit_: oP });
function uP(e, t) {
let n = _(e, "input", "stringToHashBucketFast", "string"), s = { numBuckets: t };
if (t <= 0)
throw new Error("Number of buckets must be at least 1");
let r = { input: n };
return z.runKernel(Vg, r, s);
}
var lP = M({ stringToHashBucketFast_: uP });
var khe = { fft: wb, ifft: $d, rfft: kb, irfft: MS };
var She = { hammingWindow: LF, hannWindow: jS, frame: KS, stft: WF };
var Kn = { flipLeftRight: qF, grayscaleToRGB: KF, resizeNearestNeighbor: yO, resizeBilinear: gO, rotateWithOffset: YF, cropAndResize: GF, nonMaxSuppression: ZF, nonMaxSuppressionAsync: oO, nonMaxSuppressionWithScore: uO, nonMaxSuppressionWithScoreAsync: cO, nonMaxSuppressionPadded: pO, nonMaxSuppressionPaddedAsync: fO, threshold: wO, transform: SO };
var cP = { bandPart: CO, gramSchmidt: TO, qr: _O };
var Ihe = { absoluteDifference: DO, computeWeightedLoss: Ys, cosineDistance: OO, hingeLoss: zO, huberLoss: MO, logLoss: VO, meanSquaredError: UO, sigmoidCrossEntropy: qO, softmaxCrossEntropy: XO };
var jc = { sparseFillEmptyRows: QO, sparseReshape: JO, sparseSegmentMean: tP, sparseSegmentSum: sP };
var Yf = { stringNGrams: aP, stringSplit: iP, stringToHashBucketFast: lP };
var Er = class extends aS {
minimize(e, t = false, n) {
let { value: s, grads: r } = this.computeGradients(e, n);
if (n != null) {
let a = n.map((o) => ({ name: o.name, tensor: r[o.name] }));
this.applyGradients(a);
} else
this.applyGradients(r);
return De(r), t ? s : (s.dispose(), null);
}
get iterations() {
return this.iterations_ == null && (this.iterations_ = 0), this.iterations_;
}
incrementIterations() {
this.iterations_ = this.iterations + 1;
}
computeGradients(e, t) {
return ND(e, t);
}
dispose() {
this.iterations_ != null && De(this.iterations_);
}
async saveIterations() {
return this.iterations_ == null && (this.iterations_ = 0), { name: "iter", tensor: we(this.iterations_, "int32") };
}
async getWeights() {
throw new Error("getWeights() is not implemented for this optimizer yet.");
}
async setWeights(e) {
throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`);
}
async extractIterations(e) {
return this.iterations_ = (await e[0].tensor.data())[0], e.slice(1);
}
};
Object.defineProperty(Er, Symbol.hasInstance, { value: (e) => e.minimize != null && e.computeGradients != null && e.applyGradients != null });
var Nb = class extends Er {
constructor(e, t, n = null) {
super(), this.learningRate = e, this.rho = t, this.epsilon = n, this.accumulatedGrads = [], this.accumulatedUpdates = [], n == null && (this.epsilon = z.backend.epsilon());
}
applyGradients(e) {
(Array.isArray(e) ? e.map((n) => n.name) : Object.keys(e)).forEach((n, s) => {
let r = z.registeredVariables[n], a = false;
this.accumulatedGrads[s] == null && (this.accumulatedGrads[s] = { originalName: `${n}/accum_grad`, variable: q(() => je(r).variable(a)) }), this.accumulatedUpdates[s] == null && (this.accumulatedUpdates[s] = { originalName: `${n}/accum_var`, variable: q(() => je(r).variable(a)) });
let o = Array.isArray(e) ? e[s].tensor : e[n];
if (o == null)
return;
let i = this.accumulatedGrads[s].variable, u = this.accumulatedUpdates[s].variable;
q(() => {
let l = oe(V(i, this.rho), V(ct(o), 1 - this.rho)), c = V(xe(dn(oe(u, this.epsilon)), dn(oe(i, this.epsilon))), o), p = oe(V(u, this.rho), V(ct(c), 1 - this.rho));
i.assign(l), u.assign(p);
let d = oe(V(c, -this.learningRate), r);
r.assign(d);
});
}), this.incrementIterations();
}
dispose() {
this.accumulatedUpdates != null && (De(this.accumulatedGrads.map((e) => e.variable)), De(this.accumulatedUpdates.map((e) => e.variable)));
}
async getWeights() {
let e = [...this.accumulatedGrads, ...this.accumulatedUpdates];
return [await this.saveIterations()].concat(e.map((t) => ({ name: t.originalName, tensor: t.variable })));
}
async setWeights(e) {
e = await this.extractIterations(e);
let t = e.length / 2, n = false;
this.accumulatedGrads = e.slice(0, t).map((s) => ({ originalName: s.name, variable: s.tensor.variable(n) })), this.accumulatedUpdates = e.slice(t, t * 2).map((s) => ({ originalName: s.name, variable: s.tensor.variable(n) }));
}
getConfig() {
return { learningRate: this.learningRate, rho: this.rho, epsilon: this.epsilon };
}
static fromConfig(e, t) {
return new e(t.learningRate, t.rho, t.epsilon);
}
};
Nb.className = "Adadelta";
_r(Nb);
var Tb = class extends Er {
constructor(e, t = 0.1) {
super(), this.learningRate = e, this.initialAccumulatorValue = t, this.accumulatedGrads = [];
}
applyGradients(e) {
(Array.isArray(e) ? e.map((n) => n.name) : Object.keys(e)).forEach((n, s) => {
let r = z.registeredVariables[n];
this.accumulatedGrads[s] == null && (this.accumulatedGrads[s] = { originalName: `${n}/accumulator`, variable: q(() => Bl(r.shape, this.initialAccumulatorValue).variable(false)) });
let a = Array.isArray(e) ? e[s].tensor : e[n];
if (a == null)
return;
let o = this.accumulatedGrads[s].variable;
q(() => {
let i = oe(o, ct(a));
o.assign(i);
let u = oe(V(xe(a, dn(oe(i, z.backend.epsilon()))), -this.learningRate), r);
r.assign(u);
});
}), this.incrementIterations();
}
dispose() {
this.accumulatedGrads != null && De(this.accumulatedGrads.map((e) => e.variable));
}
async getWeights() {
return [await this.saveIterations()].concat(this.accumulatedGrads.map((e) => ({ name: e.originalName, tensor: e.variable })));
}
async setWeights(e) {
e = await this.extractIterations(e);
let t = false;
this.accumulatedGrads = e.map((n) => ({ originalName: n.name, variable: n.tensor.variable(t) }));
}
getConfig() {
return { learningRate: this.learningRate, initialAccumulatorValue: this.initialAccumulatorValue };
}
static fromConfig(e, t) {
return new e(t.learningRate, t.initialAccumulatorValue);
}
};
Tb.className = "Adagrad";
_r(Tb);
var $b = class extends Er {
constructor(e, t, n, s = null) {
super(), this.learningRate = e, this.beta1 = t, this.beta2 = n, this.epsilon = s, this.accumulatedFirstMoment = [], this.accumulatedSecondMoment = [], q(() => {
this.accBeta1 = we(t).variable(), this.accBeta2 = we(n).variable();
}), s == null && (this.epsilon = z.backend.epsilon());
}
applyGradients(e) {
let t = Array.isArray(e) ? e.map((n) => n.name) : Object.keys(e);
q(() => {
let n = ge(1, this.accBeta1), s = ge(1, this.accBeta2);
t.forEach((r, a) => {
let o = z.registeredVariables[r], i = false;
this.accumulatedFirstMoment[a] == null && (this.accumulatedFirstMoment[a] = { originalName: `${r}/m`, variable: q(() => je(o).variable(i)) }), this.accumulatedSecondMoment[a] == null && (this.accumulatedSecondMoment[a] = { originalName: `${r}/v`, variable: q(() => je(o).variable(i)) });
let u = Array.isArray(e) ? e[a].tensor : e[r];
if (u == null)
return;
let l = this.accumulatedFirstMoment[a].variable, c = this.accumulatedSecondMoment[a].variable, p = oe(V(l, this.beta1), V(u, 1 - this.beta1)), d = oe(V(c, this.beta2), V(ct(u), 1 - this.beta2)), h = xe(p, n), f = xe(d, s);
l.assign(p), c.assign(d);
let m = oe(V(xe(h, oe(dn(f), this.epsilon)), -this.learningRate), o);
o.assign(m);
}), this.accBeta1.assign(V(this.accBeta1, this.beta1)), this.accBeta2.assign(V(this.accBeta2, this.beta2));
}), this.incrementIterations();
}
dispose() {
this.accBeta1.dispose(), this.accBeta2.dispose(), this.accumulatedFirstMoment != null && De(this.accumulatedFirstMoment.map((e) => e.variable)), this.accumulatedSecondMoment != null && De(this.accumulatedSecondMoment.map((e) => e.variable));
}
async getWeights() {
let e = [...this.accumulatedFirstMoment, ...this.accumulatedSecondMoment];
return [await this.saveIterations()].concat(e.map((t) => ({ name: t.originalName, tensor: t.variable })));
}
async setWeights(e) {
e = await this.extractIterations(e), q(() => {
this.accBeta1.assign(ha(this.beta1, this.iterations_ + 1)), this.accBeta2.assign(ha(this.beta2, this.iterations_ + 1));
});
let t = e.length / 2, n = false;
this.accumulatedFirstMoment = e.slice(0, t).map((s) => ({ originalName: s.name, variable: s.tensor.variable(n) })), this.accumulatedSecondMoment = e.slice(t, t * 2).map((s) => ({ originalName: s.name, variable: s.tensor.variable(n) }));
}
getConfig() {
return { learningRate: this.learningRate, beta1: this.beta1, beta2: this.beta2, epsilon: this.epsilon };
}
static fromConfig(e, t) {
return new e(t.learningRate, t.beta1, t.beta2, t.epsilon);
}
};
$b.className = "Adam";
_r($b);
var _b = class extends Er {
constructor(e, t, n, s = null, r = 0) {
super(), this.learningRate = e, this.beta1 = t, this.beta2 = n, this.epsilon = s, this.decay = r, this.accumulatedFirstMoment = [], this.accumulatedWeightedInfNorm = [], q(() => {
this.iteration = we(0).variable(), this.accBeta1 = we(t).variable();
}), s == null && (this.epsilon = z.backend.epsilon());
}
applyGradients(e) {
let t = Array.isArray(e) ? e.map((n) => n.name) : Object.keys(e);
q(() => {
let n = ge(1, this.accBeta1), s = xe(-this.learningRate, oe(V(this.iteration, this.decay), 1));
t.forEach((r, a) => {
let o = z.registeredVariables[r], i = false;
this.accumulatedFirstMoment[a] == null && (this.accumulatedFirstMoment[a] = { originalName: `${r}/m`, variable: je(o).variable(i) }), this.accumulatedWeightedInfNorm[a] == null && (this.accumulatedWeightedInfNorm[a] = { originalName: `${r}/v`, variable: je(o).variable(i) });
let u = Array.isArray(e) ? e[a].tensor : e[r];
if (u == null)
return;
let l = this.accumulatedFirstMoment[a].variable, c = this.accumulatedWeightedInfNorm[a].variable, p = oe(V(l, this.beta1), V(u, 1 - this.beta1)), d = V(c, this.beta2), h = Lt(u), f = Ar(d, h);
l.assign(p), c.assign(f);
let m = oe(V(xe(s, n), xe(p, oe(f, this.epsilon))), o);
o.assign(m);
}), this.iteration.assign(oe(this.iteration, 1)), this.accBeta1.assign(V(this.accBeta1, this.beta1));
}), this.incrementIterations();
}
dispose() {
this.accBeta1.dispose(), this.iteration.dispose(), this.accumulatedFirstMoment != null && De(this.accumulatedFirstMoment.map((e) => e.variable)), this.accumulatedWeightedInfNorm != null && De(this.accumulatedWeightedInfNorm.map((e) => e.variable));
}
async getWeights() {
throw new Error("getWeights() is not implemented for Adamax yet.");
}
async setWeights(e) {
throw new Error("setWeights() is not implemented for Adamax yet.");
}
getConfig() {
return { learningRate: this.learningRate, beta1: this.beta1, beta2: this.beta2, epsilon: this.epsilon, decay: this.decay };
}
static fromConfig(e, t) {
return new e(t.learningRate, t.beta1, t.beta2, t.epsilon, t.decay);
}
};
_b.className = "Adamax";
_r(_b);
var Rp = class extends Er {
constructor(e) {
super(), this.learningRate = e, this.setLearningRate(e);
}
applyGradients(e) {
(Array.isArray(e) ? e.map((n) => n.name) : Object.keys(e)).forEach((n, s) => {
let r = Array.isArray(e) ? e[s].tensor : e[n];
if (r == null)
return;
let a = z.registeredVariables[n];
q(() => {
let o = oe(V(this.c, r), a);
a.assign(o);
});
}), this.incrementIterations();
}
setLearningRate(e) {
this.learningRate = e, this.c != null && this.c.dispose(), this.c = qt(we(-e));
}
dispose() {
this.c.dispose();
}
async getWeights() {
return [await this.saveIterations()];
}
async setWeights(e) {
if (e = await this.extractIterations(e), e.length !== 0)
throw new Error("SGD optimizer does not have settable weights.");
}
getConfig() {
return { learningRate: this.learningRate };
}
static fromConfig(e, t) {
return new e(t.learningRate);
}
};
Rp.className = "SGD";
_r(Rp);
var Ab = class extends Rp {
constructor(e, t, n = false) {
super(e), this.learningRate = e, this.momentum = t, this.useNesterov = n, this.accumulations = [], this.m = we(this.momentum);
}
applyGradients(e) {
(Array.isArray(e) ? e.map((n) => n.name) : Object.keys(e)).forEach((n, s) => {
let r = z.registeredVariables[n];
this.accumulations[s] == null && (this.accumulations[s] = { originalName: `${n}/momentum`, variable: q(() => je(r).variable(false)) });
let a = this.accumulations[s].variable, o = Array.isArray(e) ? e[s].tensor : e[n];
o != null && q(() => {
let i, u = oe(V(this.m, a), o);
this.useNesterov ? i = oe(V(this.c, oe(o, V(u, this.m))), r) : i = oe(V(this.c, u), r), a.assign(u), r.assign(i);
});
}), this.incrementIterations();
}
dispose() {
this.m.dispose(), this.accumulations != null && De(this.accumulations.map((e) => e.variable));
}
setMomentum(e) {
this.momentum = e;
}
async getWeights() {
return [await this.saveIterations()].concat(this.accumulations.map((e) => ({ name: e.originalName, tensor: e.variable })));
}
async setWeights(e) {
e = await this.extractIterations(e);
let t = false;
this.accumulations = e.map((n) => ({ originalName: n.name, variable: n.tensor.variable(t) }));
}
getConfig() {
return { learningRate: this.learningRate, momentum: this.momentum, useNesterov: this.useNesterov };
}
static fromConfig(e, t) {
return new e(t.learningRate, t.momentum, t.useNesterov);
}
};
Ab.className = "Momentum";
_r(Ab);
var Eb = class extends Er {
constructor(e, t = 0.9, n = 0, s = null, r = false) {
if (super(), this.learningRate = e, this.decay = t, this.momentum = n, this.epsilon = s, this.accumulatedMeanSquares = [], this.accumulatedMoments = [], this.accumulatedMeanGrads = [], this.centered = r, s == null && (this.epsilon = z.backend.epsilon()), e == null)
throw new Error("learningRate for RMSPropOptimizer must be defined.");
}
applyGradients(e) {
(Array.isArray(e) ? e.map((n) => n.name) : Object.keys(e)).forEach((n, s) => {
let r = z.registeredVariables[n], a = false;
this.accumulatedMeanSquares[s] == null && (this.accumulatedMeanSquares[s] = { originalName: `${n}/rms`, variable: q(() => je(r).variable(a)) }), this.accumulatedMoments[s] == null && (this.accumulatedMoments[s] = { originalName: `${n}/momentum`, variable: q(() => je(r).variable(a)) }), this.accumulatedMeanGrads[s] == null && this.centered && (this.accumulatedMeanGrads[s] = { originalName: `${n}/mg`, variable: q(() => je(r).variable(a)) });
let o = Array.isArray(e) ? e[s].tensor : e[n];
if (o == null)
return;
let i = this.accumulatedMeanSquares[s].variable, u = this.accumulatedMoments[s].variable;
q(() => {
let l = oe(V(i, this.decay), V(ct(o), 1 - this.decay));
if (this.centered) {
let c = this.accumulatedMeanGrads[s].variable, p = oe(V(c, this.decay), V(o, 1 - this.decay)), d = xe(V(o, this.learningRate), dn(ge(l, oe(ct(p), this.epsilon)))), h = oe(V(u, this.momentum), d);
i.assign(l), c.assign(p), u.assign(h);
let f = ge(r, h);
r.assign(f);
} else {
let c = oe(V(i, this.decay), V(ct(o), 1 - this.decay)), p = oe(V(u, this.momentum), xe(V(o, this.learningRate), dn(oe(c, this.epsilon))));
i.assign(c), u.assign(p);
let d = ge(r, p);
r.assign(d);
}
});
}), this.incrementIterations();
}
dispose() {
this.accumulatedMeanSquares != null && De(this.accumulatedMeanSquares.map((e) => e.variable)), this.accumulatedMeanGrads != null && this.centered && De(this.accumulatedMeanGrads.map((e) => e.variable)), this.accumulatedMoments != null && De(this.accumulatedMoments.map((e) => e.variable));
}
async getWeights() {
let e = [...this.accumulatedMeanSquares, ...this.accumulatedMoments];
return this.centered && e.push(...this.accumulatedMeanGrads), [await this.saveIterations()].concat(e.map((t) => ({ name: t.originalName, tensor: t.variable })));
}
async setWeights(e) {
e = await this.extractIterations(e);
let t = this.centered ? e.length / 3 : e.length / 2, n = false;
this.accumulatedMeanSquares = e.slice(0, t).map((s) => ({ originalName: s.name, variable: s.tensor.variable(n) })), this.accumulatedMoments = e.slice(t, t * 2).map((s) => ({ originalName: s.name, variable: s.tensor.variable(n) })), this.centered && (this.accumulatedMeanGrads = e.slice(t * 2, t * 3).map((s) => ({ originalName: s.name, variable: s.tensor.variable(n) })));
}
getConfig() {
return { learningRate: this.learningRate, decay: this.decay, momentum: this.momentum, epsilon: this.epsilon, centered: this.centered };
}
static fromConfig(e, t) {
return new e(t.learningRate, t.decay, t.momentum, t.epsilon, t.centered);
}
};
Eb.className = "RMSProp";
_r(Eb);
var Gr = class {
static sgd(e) {
return new Rp(e);
}
static momentum(e, t, n = false) {
return new Ab(e, t, n);
}
static rmsprop(e, t = 0.9, n = 0, s = null, r = false) {
return new Eb(e, t, n, s, r);
}
static adam(e = 1e-3, t = 0.9, n = 0.999, s = null) {
return new $b(e, t, n, s);
}
static adadelta(e = 1e-3, t = 0.95, n = null) {
return new Nb(e, t, n);
}
static adamax(e = 2e-3, t = 0.9, n = 0.999, s = null, r = 0) {
return new _b(e, t, n, s, r);
}
static adagrad(e, t = 0.1) {
return new Tb(e, t);
}
};
var Mo = { sgd: Gr.sgd, momentum: Gr.momentum, adadelta: Gr.adadelta, adagrad: Gr.adagrad, rmsprop: Gr.rmsprop, adamax: Gr.adamax, adam: Gr.adam };
var dP = (() => typeof requestAnimationFrame != "undefined" ? requestAnimationFrame : typeof setImmediate != "undefined" ? setImmediate : (e) => e())();
function ZS() {
return new Promise((e) => dP(() => e()));
}
var C = {};
Ee(C, { ERF_A1: () => kP, ERF_A2: () => SP, ERF_A3: () => IP, ERF_A4: () => CP, ERF_A5: () => NP, ERF_P: () => wP, PARALLELIZE_THRESHOLD: () => Rb, SELU_SCALE: () => eI, SELU_SCALEALPHA: () => JS, applyActivation: () => Ap, assertAndGetBroadcastShape: () => at, assertAxesAreInnerMostDims: () => jR, assertParamsConsistent: () => pP, assignToTypedArray: () => RP, axesAreInnerMostDims: () => ob, calculateShapes: () => Xk, checkEinsumDimSizes: () => LP, checkPadOnDimRoundingMode: () => fn, combineLocations: () => wS, complexWithEvenIndex: () => _P, complexWithOddIndex: () => AP, computeConv2DInfo: () => Ml, computeConv3DInfo: () => dS, computeDefaultPad: () => tb, computeDilation2DInfo: () => RE, computeOptimalWindowSize: () => fP, computeOutAndReduceShapes: () => kS, computeOutShape: () => hP, computePool2DInfo: () => cS, computePool3DInfo: () => DE, convertConv2DDataFormat: () => pS, decodeEinsumEquation: () => PP, eitherStridesOrDilationsAreOne: () => Ps, expandShapeToKeepDim: () => pa, exponent: () => FP, exponents: () => DP, fromStringArrayToUint8: () => az, fromUint8ToStringArray: () => rz, getAxesPermutation: () => SS, getBroadcastDims: () => Uk, getComplexWithIndex: () => EP, getEinsumComputePath: () => MP, getEinsumPermutation: () => zP, getFusedBiasGradient: () => _p, getFusedDyActivation: () => $p, getImageCenter: () => mP, getInnerMostAxes: () => KR, getPermuted: () => bP, getReductionAxes: () => _t, getReshaped: () => gP, getReshapedPermuted: () => yP, getSliceBeginCoords: () => vP, getSliceSize: () => xP, getSparseFillEmptyRowsIndicesDenseShapeMismatch: () => UP, getSparseFillEmptyRowsNegativeIndexErrorMessage: () => GP, getSparseFillEmptyRowsOutOfRangeIndexErrorMessage: () => HP, getSparseReshapeEmptyTensorZeroOutputDimErrorMessage: () => KP, getSparseReshapeInputOutputMismatchErrorMessage: () => YP, getSparseReshapeInputOutputMultipleErrorMessage: () => XP, getSparseReshapeMultipleNegativeOneOutputDimErrorMessage: () => qP, getSparseReshapeNegativeOutputDimErrorMessage: () => jP, getSparseSegmentReductionIndicesOutOfRangeErrorMessage: () => ez, getSparseSegmentReductionNegativeSegmentIdsErrorMessage: () => QP, getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage: () => ZP, getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage: () => JP, getUndoAxesPermutation: () => ib, isIdentityPermutation: () => BP, log: () => Y$, mergeRealAndImagArrays: () => TP, prepareAndValidate: () => jk, prepareSplitSize: () => WP, segment_util: () => tI, shouldFuse: () => Ep, slice_util: () => kt, splitRealAndImagArrays: () => $P, tupleValuesAreOne: () => gr, upcastType: () => cn, validateInput: () => Zg, validateUpdateShape: () => Qg, warn: () => ar });
function pP(e, t) {
let n = e[0].length;
e.forEach((r, a) => {
O(r.length === n, () => `Error in concat${n}D: rank of tensors[${a}] must be the same as the rank of the rest (${n})`);
}), O(t >= 0 && t < n, () => `Error in concat${n}D: axis must be between 0 and ${n - 1}.`);
let s = e[0];
e.forEach((r, a) => {
for (let o = 0; o < n; o++)
O(o === t || r[o] === s[o], () => `Error in concat${n}D: Shape of tensors[${a}] (${r}) does not match the shape of the rest (${s}) along the non-concatenated axis ${a}.`);
});
}
function hP(e, t) {
let n = e[0].slice();
for (let s = 1; s < e.length; s++)
n[t] += e[s][t];
return n;
}
var Rb = 30;
function fP(e) {
return e <= Rb ? e : vd(e, Math.floor(Math.sqrt(e)));
}
function mP(e, t, n) {
let s = n * (typeof e == "number" ? e : e[0]), r = t * (typeof e == "number" ? e : e[1]);
return [s, r];
}
function gP(e, t, n, s = true) {
let r = [];
if (s)
r = r.concat(t.slice(0)), r.push(e[0] / n), r = r.concat(e.slice(1));
else {
r = r.concat(e[0]);
let a = t.length;
for (let o = 0; o < a; ++o)
r = r.concat([e[o + 1] / t[o], t[o]]);
r = r.concat(e.slice(a + 1));
}
return r;
}
function bP(e, t, n = true) {
let s = [];
if (n) {
s.push(t);
for (let r = t + 1; r < e; ++r)
r <= 2 * t ? (s.push(r), s.push(r - (t + 1))) : s.push(r);
} else {
let r = [], a = [];
for (let o = 1; o < e; ++o)
o >= t * 2 + 1 || o % 2 === 1 ? a.push(o) : r.push(o);
s.push(...r), s.push(0), s.push(...a);
}
return s;
}
function yP(e, t, n, s = true) {
let r = [];
s ? r.push(e[0] / n) : r.push(e[0] * n);
for (let a = 1; a < e.length; ++a)
a <= t.length ? s ? r.push(t[a - 1] * e[a]) : r.push(e[a] / t[a - 1]) : r.push(e[a]);
return r;
}
function vP(e, t) {
let n = [0];
for (let s = 0; s < t; ++s)
n.push(e[s][0]);
return n;
}
function xP(e, t, n) {
let s = e.slice(0, 1);
for (let r = 0; r < n; ++r)
s.push(e[r + 1] - t[r][0] - t[r][1]);
return s;
}
var JS = 1.7580993408473768;
var eI = 1.0507009873554805;
var wP = 0.3275911;
var kP = 0.254829592;
var SP = -0.284496736;
var IP = 1.421413741;
var CP = -1.453152027;
var NP = 1.061405429;
function TP(e, t) {
if (e.length !== t.length)
throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);
let n = new Float32Array(e.length * 2);
for (let s = 0; s < n.length; s += 2)
n[s] = e[s / 2], n[s + 1] = t[s / 2];
return n;
}
function $P(e) {
let t = new Float32Array(e.length / 2), n = new Float32Array(e.length / 2);
for (let s = 0; s < e.length; s += 2)
t[s / 2] = e[s], n[s / 2] = e[s + 1];
return { real: t, imag: n };
}
function _P(e) {
let t = Math.ceil(e.length / 4), n = new Float32Array(t), s = new Float32Array(t);
for (let r = 0; r < e.length; r += 4)
n[Math.floor(r / 4)] = e[r], s[Math.floor(r / 4)] = e[r + 1];
return { real: n, imag: s };
}
function AP(e) {
let t = Math.floor(e.length / 4), n = new Float32Array(t), s = new Float32Array(t);
for (let r = 2; r < e.length; r += 4)
n[Math.floor(r / 4)] = e[r], s[Math.floor(r / 4)] = e[r + 1];
return { real: n, imag: s };
}
function EP(e, t) {
let n = e[t * 2], s = e[t * 2 + 1];
return { real: n, imag: s };
}
function RP(e, t, n, s) {
e[s * 2] = t, e[s * 2 + 1] = n;
}
function DP(e, t) {
let n = new Float32Array(e / 2), s = new Float32Array(e / 2);
for (let r = 0; r < Math.ceil(e / 2); r++) {
let a = (t ? 2 : -2) * Math.PI * (r / e);
n[r] = Math.cos(a), s[r] = Math.sin(a);
}
return { real: n, imag: s };
}
function FP(e, t, n) {
let s = (n ? 2 : -2) * Math.PI * (e / t), r = Math.cos(s), a = Math.sin(s);
return { real: r, imag: a };
}
var Qf = "->";
var OP = /->/g;
var Tx = ",";
var $x = "...";
function PP(e, t) {
e = e.replace(/\s/g, "");
let n = (e.length - e.replace(OP, "").length) / Qf.length;
if (n < 1)
throw new Error("Equations without an arrow are not supported.");
if (n > 1)
throw new Error(`Equation must contain exactly one arrow ("${Qf}").`);
let [s, r] = e.split(Qf);
O(s.indexOf($x) === -1, () => `The ellipsis notation ("${$x}") is not supported yet.`);
let a = s.split(Tx), o = a.length;
if (t !== o)
throw new Error(`Expected ${o} input tensors, received ${t}`);
if (o > 2)
throw new Error("Support for more than 2 input tensors is not implemented yet.");
let i = [];
for (let d = 0; d < r.length; ++d) {
let h = r[d];
if (!a.some((f) => f.indexOf(h) !== -1))
throw new Error(`Output subscripts contain the label ${h} not present in the input subscripts.`);
i.indexOf(h) === -1 && i.push(h);
}
for (let d = 0; d < s.length; ++d) {
let h = s[d];
i.indexOf(h) === -1 && h !== Tx && i.push(h);
}
let u = new Array(a.length);
for (let d = 0; d < o; ++d) {
if (new Set(a[d].split("")).size !== a[d].length)
throw new Error(`Found duplicate axes in input component ${a[d]}. Support for duplicate axes in input is not implemented yet.`);
u[d] = [];
for (let h = 0; h < a[d].length; ++h)
u[d].push(i.indexOf(a[d][h]));
}
let l = i.length, c = r.length, p = [];
for (let d = c; d < l; ++d)
p.push(d);
return { allDims: i, summedDims: p, idDims: u };
}
function zP(e, t) {
let n = new Array(e);
n.fill(-1);
for (let r = 0; r < t.length; ++r)
n[t[r]] = r;
let s = [];
for (let r = 0; r < e; ++r)
n[r] === -1 && s.push(r);
return n = n.filter((r) => r !== -1), { permutationIndices: n, expandDims: s };
}
function LP(e, t, n) {
let s = new Array(e);
for (let r = 0; r < n.length; ++r) {
let a = n[r].shape;
for (let o = 0; o < t[r].length; ++o)
s[t[r][o]] === void 0 ? s[t[r][o]] = a[o] : O(s[t[r][o]] === a[o], () => `Expected dimension ${s[t[r][o]]} at axis ${o} of input shaped ${JSON.stringify(a)}, but got dimension ${a[o]}`);
}
}
function MP(e, t) {
let n = e, s = [], r = 0;
e.length === 0 && n.push(-1), r = e.length + 1;
for (let o = 0; o < r; ++o)
s.push([]);
let a = [];
for (let o = 0; o < n.length; ++o) {
let i = n[o], u = VP(t, i);
for (let l of u)
a.indexOf(l) === -1 && (s[o].push(l), a.push(l));
}
return { path: n, steps: s };
}
function BP(e) {
return e.every((t, n) => t === n);
}
function VP(e, t) {
let n = [];
for (let s = 0; s < e.length; ++s)
(e[s].length === 0 || e[s].indexOf(t) !== -1 || t === -1) && n.push(s);
return n;
}
function WP(e, t, n = 0) {
let s = [];
if (typeof t == "number")
O(e.shape[n] % t === 0, () => "Number of splits must evenly divide the axis."), s = new Array(t).fill(e.shape[n] / t);
else {
let r = t.reduce((o, i) => (i === -1 && (o += 1), o), 0);
O(r <= 1, () => "There should be only one negative value in split array.");
let a = t.indexOf(-1);
if (a !== -1) {
let o = t.reduce((i, u) => u > 0 ? i + u : i);
t[a] = e.shape[n] - o;
}
O(e.shape[n] === t.reduce((o, i) => o + i), () => "The sum of sizes must match the size of the axis dimension."), s = t;
}
return s;
}
function UP(e) {
return `Received SparseTensor with denseShape[0] = 0 but
indices.shape[0] = ${e}`;
}
function GP(e, t) {
return `indices(${e}, 0) is invalid: ${t} < 0`;
}
function HP(e, t, n) {
return `indices(${e}, 0) is invalid: ${t} >= ${n}`;
}
function qP(e, t) {
return `only one output dimension may be -1, not both ${e} and ${t}`;
}
function jP(e, t) {
return `size ${e} must be non-negative, not ${t}`;
}
function KP() {
return "reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero";
}
function XP(e, t) {
let n = dt(e), s = dt(t);
return `Input to reshape is a SparseTensor with ${n}
dense values, but the requested shape requires a multiple of ${s}. inputShape=${e} outputShape= ${t}`;
}
function YP(e, t) {
let n = dt(e), s = dt(t);
return `Input to reshape is a tensor with ${n} dense values, but the requested shape has ${s}. inputShape=${e} outputShape=${t}`;
}
function QP() {
return "segment ids must be >= 0";
}
function ZP() {
return "segment ids are not increasing";
}
function JP(e, t) {
return `Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`;
}
function ez(e, t, n) {
return `Bad: indices[${e}] == ${t} out of range [0, ${n})`;
}
var tI = {};
Ee(tI, { collectGatherOpShapeInfo: () => sz, computeOutShape: () => nz, segOpComputeOptimalWindowSize: () => tz });
function tz(e, t) {
let n = false, s;
for (e <= Rb ? (s = e, n = true) : s = vd(e, Math.floor(Math.sqrt(e))); !n; )
s > t || s === e ? n = true : s = vd(e, s + 1);
return s;
}
function nz(e, t, n) {
let s = [], r = e.length;
for (let a = 0; a < r; a++)
a !== t ? s.push(e[a]) : s.push(n);
return s;
}
function sz(e, t, n, s) {
let r = t.shape.length, a = e.shape.length;
if (s !== 0 && (s < -r || s > r))
throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${s}`);
if (s < 0 && (s += r), s > a)
throw new Error(`batchDims (${s}) must be less than rank(x) (
${a}).`);
if (n < s)
throw new Error(`batchDims (${s}) must be less than or equal to axis (${n}).`);
for (let p = 0; p < s; ++p)
if (e.shape[p] !== t.shape[p])
throw new Error(`x.shape[${p}]: ${e.shape[p]} should be equal to indices.shape[${p}]: ${t.shape[p]}.`);
let o = e.shape[n], i = [], u = 1, l = 1, c = 1;
for (let p = 0; p < s; ++p)
i.push(e.shape[p]), u *= e.shape[p];
for (let p = s; p < n; p++)
i.push(e.shape[p]), l *= e.shape[p];
for (let p = s; p < r; p++)
i.push(t.shape[p]);
for (let p = n + 1; p < a; p++)
i.push(e.shape[p]), c *= e.shape[p];
return { batchSize: u, sliceSize: c, outerSize: l, dimSize: o, outputShape: i };
}
function rz(e) {
try {
return e.map((t) => wd(t));
} catch (t) {
throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`);
}
}
function az(e) {
return e.map((t) => zl(t));
}
var ws = {};
Ee(ws, { nonMaxSuppressionV3Impl: () => XS, nonMaxSuppressionV4Impl: () => YS, nonMaxSuppressionV5Impl: () => QS, whereImpl: () => VS });
var Bs = class extends Error {
constructor(e) {
super(e), Object.setPrototypeOf(this, Bs.prototype);
}
};
var fs = class extends Error {
constructor(e) {
super(e), Object.setPrototypeOf(this, fs.prototype);
}
};
var G = class extends Error {
constructor(e) {
super(e), Object.setPrototypeOf(this, G.prototype);
}
};
var Fe = class extends Error {
constructor(e) {
super(e), Object.setPrototypeOf(this, Fe.prototype);
}
};
var nI = class extends Error {
constructor(e) {
super(e), Object.setPrototypeOf(this, nI.prototype);
}
};
var sI = class {
constructor(e) {
this.maxEntries = e || 100, this.cache = /* @__PURE__ */ new Map();
}
get(e) {
let t;
return this.cache.has(e) && (t = this.cache.get(e), this.cache.delete(e), this.cache.set(e, t)), t;
}
put(e, t) {
if (this.cache.has(e))
this.cache.delete(e);
else if (this.cache.size >= this.maxEntries) {
let n = this.cache.keys().next().value;
this.cache.delete(n);
}
this.cache.set(e, t);
}
getMaxEntries() {
return this.maxEntries;
}
setMaxEntries(e) {
if (e < 0)
throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);
if (this.maxEntries > e)
for (let t = 0; t < this.maxEntries - e; t++) {
let n = this.cache.keys().next().value;
this.cache.delete(n);
}
this.maxEntries = e;
}
};
function ma(e, t) {
if (Array.isArray(e)) {
let n = [];
for (let s = 0; s < t; s++)
n = n.concat(e);
return n;
} else {
let n = new Array(t);
return n.fill(e), n;
}
}
function Cs(e, t) {
if (!e)
throw new nI(t);
}
function _x(e, t) {
let n = 0;
for (let s of e)
s === t && n++;
return n;
}
function bn(e) {
return e.length === 1 ? e[0] : e;
}
function ht(e) {
return Array.isArray(e) ? e : [e];
}
function Vs(e) {
let n = e.replace(/(.)([A-Z][a-z0-9]+)/g, "$1_$2").replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
return n[0] !== "_" ? n : "private" + n;
}
function Yr(e) {
return e.length <= 1 || e.indexOf("_") === -1 ? e : e.replace(/[_]+(\w|$)/g, (t, n) => n.toUpperCase());
}
var qn = {};
function Db(e) {
if (e == null)
return null;
let t = {};
return t.className = e.getClassName(), t.config = e.getConfig(), t;
}
function Tm(e) {
if (!(e == null || typeof e != "object"))
if (Array.isArray(e))
e.forEach((t) => Tm(t));
else {
let t = Object.keys(e);
for (let n of t) {
let s = e[n];
s != null && typeof s == "object" && (!Array.isArray(s) && s.type === "ndarray" && typeof s.value == "number" ? e[n] = s.value : Tm(s));
}
}
}
function Ul(e, t = {}, n = {}, s = "object", r = false) {
if (typeof e == "string") {
let a = e, o;
if (a in n)
o = n[a];
else if (a in qn)
o = qn[a];
else if (o = t[a], o == null)
throw new G(`Unknown ${s}: ${e}. This may be due to one of the following reasons:
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);
return o;
} else {
let a = e;
if (a.className == null || a.config == null)
throw new G(`${s}: Improper config format: ${JSON.stringify(a)}.
'className' and 'config' must set.`);
let o = a.className, i, u;
if (o in n ? [i, u] = n[o] : o in qn ? [i, u] = qn.className : o in t && ([i, u] = t[o]), i == null)
throw new G(`Unknown ${s}: ${o}. This may be due to one of the following reasons:
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);
if (u != null) {
let l = {};
for (let h of Object.keys(qn))
l[h] = qn[h];
for (let h of Object.keys(n))
l[h] = n[h];
let c = a.config;
c.customObjects = l;
let p = { ...qn };
for (let h of Object.keys(n))
qn[h] = n[h];
Tm(a.config);
let d = u(i, a.config, n, r);
return qn = { ...p }, d;
} else {
let l = { ...qn };
for (let p of Object.keys(n))
qn[p] = n[p];
let c = new i(a.config);
return qn = { ...l }, c;
}
}
}
function oz(e, t) {
return e < t ? -1 : e > t ? 1 : 0;
}
function Kc(e, t) {
return -1 * oz(e, t);
}
function cr(e) {
if (e == null)
return e;
let t = [];
for (let n of e)
t.indexOf(n) === -1 && t.push(n);
return t;
}
function iz(e) {
if (e == null)
throw new G(`Invalid value in obj: ${JSON.stringify(e)}`);
for (let t in e)
if (e.hasOwnProperty(t))
return false;
return true;
}
function yo(e, t, n) {
if (n != null && e.indexOf(n) < 0)
throw new G(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`);
}
function Fb(e, t, n = 0, s = 1 / 0) {
return Cs(n >= 0), Cs(s >= n), Array.isArray(e) && e.length >= n && e.length <= s && e.every((r) => typeof r === t);
}
function Bt(e, t) {
Array.isArray(e) ? (w.assert(e.length > 0, () => `${t} is unexpectedly an empty array.`), e.forEach((n, s) => Bt(n, `element ${s + 1} of ${t}`))) : w.assert(Number.isInteger(e) && e > 0, () => `Expected ${t} to be a positive integer, but got ${rI(e)}.`);
}
function rI(e) {
return e === null ? "null" : Array.isArray(e) ? "[" + e.map((t) => rI(t)).join(",") + "]" : typeof e == "string" ? `"${e}"` : `${e}`;
}
function uz(e, t, n) {
let s = n != null ? n() : w.now(), r;
return (...o) => {
let i = n != null ? n() : w.now();
return i - s < t || (s = i, r = e(...o)), r;
};
}
function aI(e) {
return e === "relu" ? "relu" : e === "linear" ? "linear" : e === "elu" ? "elu" : null;
}
var lz = 0;
function oI() {
return lz++;
}
var Xc = {};
function Dp(e = "") {
return e in Xc || (Xc[e] = 0), Xc[e] += 1, e + Xc[e].toString();
}
var cz = ["channelsFirst", "channelsLast"];
var dz = ["nearest", "bilinear"];
var pz = ["valid", "same", "causal"];
var hz = ["max", "avg"];
var fz = ["sum", "mul", "concat", "ave"];
var Bo = /* @__PURE__ */ new Map();
function Ct(e) {
yo(cz, "DataFormat", e);
}
function mz(e) {
yo(dz, "InterpolationFormat", e);
}
function Hn(e) {
yo(pz, "PaddingMode", e);
}
function iI(e) {
yo(hz, "PoolMode", e);
}
var Wu = [];
var Ax = "/";
function na(e, t) {
Wu.push(e);
try {
let n = t();
return Wu.pop(), n;
} catch (n) {
throw Wu.pop(), n;
}
}
function gz() {
return Wu.length === 0 ? "" : Wu.join(Ax) + Ax;
}
function uI(e) {
if (!cI(e))
throw new Error("Not a valid tensor name: '" + e + "'");
return gz() + e;
}
function lI(e) {
if (!cI(e))
throw new Error("Not a valid tensor name: '" + e + "'");
Bo.has(e) || Bo.set(e, 0);
let t = Bo.get(e);
if (Bo.set(e, Bo.get(e) + 1), t > 0) {
let n = `${e}_${t}`;
return Bo.set(n, 1), n;
} else
return e;
}
var bz = new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);
function cI(e) {
return !!e.match(bz);
}
function yz(e) {
return e === parseInt(e.toString(), 10);
}
function dr(e, t, n) {
t == null && (t = 0), n == null && (n = e.length);
let s = 1;
for (let r = t; r < n; ++r)
s *= e[r];
return s;
}
function ni(e) {
if (e.length === 0)
return Number.NaN;
let t = Number.POSITIVE_INFINITY;
for (let n = 0; n < e.length; n++) {
let s = e[n];
s < t && (t = s);
}
return t;
}
function yr(e) {
if (e.length === 0)
return Number.NaN;
let t = Number.NEGATIVE_INFINITY;
for (let n = 0; n < e.length; n++) {
let s = e[n];
s > t && (t = s);
}
return t;
}
function ys(e, t) {
if (t < e)
throw new G(`end (${t}) < begin (${e}) is forbidden.`);
let n = [];
for (let s = e; s < t; ++s)
n.push(s);
return n;
}
var Zf;
function Rt() {
return Zf == null && (Zf = $A().epsilon()), Zf;
}
function vs() {
return "channelsLast";
}
function Fp(e, t) {
return le(e, t);
}
function Gl(e, t = -1) {
let n = e.shape.slice();
return t < 0 && (t = n.length + t + 1), n.splice(t, 0, 1), U(e, n);
}
function vz(e, t) {
return q(() => {
if (e.shape.length !== 2)
throw new G(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);
let n = Gl(e, 1);
return $m(n, [1, t, 1]);
});
}
function xz(e) {
let t = [dr(e.shape)];
return U(e, t);
}
function wz(e) {
if (e.rank <= 1)
throw new G(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);
let t = [e.shape[0], dr(e.shape, 1)];
return U(e, t);
}
function sa(e, t, n) {
return q(() => {
switch (e.rank) {
case 1:
return yb(e, t, n);
case 2:
return LS(e, [t, 0], [n, e.shape[1]]);
case 3:
return vb(e, [t, 0, 0], [n, e.shape[1], e.shape[2]]);
case 4:
return Td(e, [t, 0, 0, 0], [n, e.shape[1], e.shape[2], e.shape[3]]);
case 5:
return qe(e, [t, 0, 0, 0, 0], [n, e.shape[1], e.shape[2], e.shape[3], e.shape[4]]);
case 6:
return qe(e, [t, 0, 0, 0, 0, 0], [n, e.shape[1], e.shape[2], e.shape[3], e.shape[4], e.shape[5]]);
default:
throw new G(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`);
}
});
}
function Jf(e, t, n) {
return q(() => {
switch (e.rank) {
case 1:
return yb(e, t, n);
case 2:
return LS(e, [0, t], [e.shape[0], n]);
case 3:
return vb(e, [0, 0, t], [e.shape[0], e.shape[1], n]);
case 4:
return Td(e, [0, 0, 0, t], [e.shape[0], e.shape[1], e.shape[2], n]);
default:
throw new G(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`);
}
});
}
function Yc(e, t, n, s) {
return q(() => {
switch (e.rank) {
case 1:
return yb(e, t, n);
case 2:
switch (s) {
case 1:
return sa(e, t, n);
case 2:
return Jf(e, t, n);
default:
throw new G(`The axis is not within the rank of the tensor ${s}`);
}
case 3:
switch (s) {
case 1:
return sa(e, t, n);
case 2:
return vb(e, [0, t, 0], [e.shape[0], n, e.shape[2]]);
case 3:
return Jf(e, t, n);
default:
throw new G(`The axis is not within the rank of the tensor ${s}`);
}
case 4:
switch (s) {
case 1:
return sa(e, t, n);
case 2:
return Td(e, [0, t, 0, 0], [e.shape[0], n, e.shape[2], e.shape[3]]);
case 3:
return Td(e, [0, 0, t, 0], [e.shape[0], e.shape[1], n, e.shape[3]]);
case 4:
return Jf(e, t, n);
default:
throw new G(`The axis is not within the rank of the tensor ${s}`);
}
default:
throw new G(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`);
}
});
}
function Ob(e, t = -1) {
let n;
return t < 0 && (n = e[0].rank, n !== 0 ? t = n : t = 0), t === e[0].rank && (t = -1), Ft(e, t);
}
function Ex(e, t) {
switch (e.rank) {
case 1:
return lR([e, t]);
case 2:
return dR([e, t], 0);
case 3:
return hR([e, t], 0);
case 4:
return mR([e, t], 0);
default:
throw new G(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`);
}
}
function $m(e, t) {
if (Array.isArray(t) || (t = [t]), e.rank !== t.length)
throw new G(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);
return hs(e, t);
}
function Op(e, t = 0, n = 1, s, r) {
return v3(e, t, n, s, r);
}
function Es(e, t, n, s) {
if (e.rank < 2 || t.rank < 2)
throw new Fe(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);
if (t.rank >= 3) {
let r = e.shape.slice(-1)[0], a = t.shape.slice(-2)[0];
if (r !== a)
throw new Fe(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${t.shape}`);
}
if (e.rank === 2 && t.rank === 2)
return fa.matMul({ a: e, b: t, transposeA: false, transposeB: false, bias: s ? _m(e.rank, s, vs()) : null, activation: n });
{
let r = e.shape.slice(), a = r.pop();
e = U(e, [-1, a]);
let o = t.shape.slice(), i = o.pop(), u = o.pop(), l = [...o, i], c = Array.from({ length: t.rank }, (f, m) => m === 0 ? t.rank - 2 : m <= t.rank - 2 ? m - 1 : m);
t = U(Ge(t, c), [u, -1]);
let p = [...r, ...l], d = false, h = false;
return U(fa.matMul({ a: e, b: t, transposeA: d, transposeB: h, bias: s ? _m(e.rank, s, vs()) : null, activation: n }), p);
}
}
function dI(e, t, n) {
return q(() => (Array.isArray(t) ? t = Zt(t, "int32") : t = le(t, "int32"), Ju(e, t, n)));
}
function Hl(e) {
return V(e, e);
}
function _m(e, t, n) {
let s = t.shape;
if (t.rank !== 1 && t.rank !== e)
throw new G(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);
if (e === 5) {
if (n === "channelsFirst")
return s.length === 1 ? U(t, [1, s[0], 1, 1, 1]) : U(t, [1, s[3], s[0], s[1], s[2]]);
if (n === "channelsLast")
return s.length === 1 ? U(t, [1, 1, 1, 1, s[0]]) : U(t, [1].concat(s));
} else if (e === 4) {
if (n === "channelsFirst")
return s.length === 1 ? U(t, [1, s[0], 1, 1]) : U(t, [1, s[2], s[0], s[1]]);
if (n === "channelsLast")
return s.length === 1 ? U(t, [1, 1, 1, s[0]]) : U(t, [1].concat(s));
} else if (e === 3) {
if (n === "channelsFirst")
return s.length === 1 ? U(t, [1, s[0], 1]) : U(t, [1, s[1], s[0]]);
if (n === "channelsLast")
return s.length === 1 ? U(t, [1, 1, s[0]]) : U(t, [1].concat(s));
} else if (e < 3)
return t;
throw new G(`Unsupported input rank by biasAdd: ${t.rank}`);
}
function ks(e, t, n) {
return q(() => (n == null && (n = vs()), Ct(n), oe(e, _m(e.rank, t, n))));
}
function kz(e, t = 1) {
if (t !== 1)
throw new Fe(`Support for alpha values other than 1 (${t}) is not implemented yet.`);
return Sp(e);
}
function Sz(e) {
return q(() => xe(e, oe(Lt(e), 1)));
}
function pI(e, t, n, s) {
return q(() => CF(e, t, n, s));
}
function Iz(e) {
return q(() => {
let t = oe(0.5, V(0.2, e));
return Wn(t, 0, 1);
});
}
function ql(e, t, n = false) {
return n ? e() : t();
}
var Cz = ["fanIn", "fanOut", "fanAvg"];
var Nz = ["normal", "uniform", "truncatedNormal"];
function Tz(e) {
yo(Cz, "FanMode", e);
}
function $z(e) {
yo(Nz, "Distribution", e);
}
var ns = class extends re.Serializable {
fromConfigUsesCustomObjects() {
return false;
}
getConfig() {
return {};
}
};
var Pb = class extends ns {
apply(e, t) {
return $t(e, t);
}
};
Pb.className = "Zeros";
re.registerClass(Pb);
var Pp = class extends ns {
apply(e, t) {
return Ln(e, t);
}
};
Pp.className = "Ones";
re.registerClass(Pp);
var zb = class extends ns {
constructor(e) {
if (super(), typeof e != "object")
throw new G(`Expected argument of type ConstantConfig but got ${e}`);
if (e.value === void 0)
throw new G(`config must have value set but got ${e}`);
this.value = e.value;
}
apply(e, t) {
return q(() => V(we(this.value), Ln(e, t)));
}
getConfig() {
return { value: this.value };
}
};
zb.className = "Constant";
re.registerClass(zb);
var Lb = class extends ns {
constructor(e) {
super(), this.DEFAULT_MINVAL = -0.05, this.DEFAULT_MAXVAL = 0.05, this.minval = e.minval || this.DEFAULT_MINVAL, this.maxval = e.maxval || this.DEFAULT_MAXVAL, this.seed = e.seed;
}
apply(e, t) {
return Wl(e, this.minval, this.maxval, t);
}
getConfig() {
return { minval: this.minval, maxval: this.maxval, seed: this.seed };
}
};
Lb.className = "RandomUniform";
re.registerClass(Lb);
var Mb = class extends ns {
constructor(e) {
super(), this.DEFAULT_MEAN = 0, this.DEFAULT_STDDEV = 0.05, this.mean = e.mean || this.DEFAULT_MEAN, this.stddev = e.stddev || this.DEFAULT_STDDEV, this.seed = e.seed;
}
apply(e, t) {
if (t = t || "float32", t !== "float32" && t !== "int32")
throw new Fe(`randomNormal does not support dType ${t}.`);
return Op(e, this.mean, this.stddev, t, this.seed);
}
getConfig() {
return { mean: this.mean, stddev: this.stddev, seed: this.seed };
}
};
Mb.className = "RandomNormal";
re.registerClass(Mb);
var Bb = class extends ns {
constructor(e) {
super(), this.DEFAULT_MEAN = 0, this.DEFAULT_STDDEV = 0.05, this.mean = e.mean || this.DEFAULT_MEAN, this.stddev = e.stddev || this.DEFAULT_STDDEV, this.seed = e.seed;
}
apply(e, t) {
if (t = t || "float32", t !== "float32" && t !== "int32")
throw new Fe(`truncatedNormal does not support dType ${t}.`);
return Sb(e, this.mean, this.stddev, t, this.seed);
}
getConfig() {
return { mean: this.mean, stddev: this.stddev, seed: this.seed };
}
};
Bb.className = "TruncatedNormal";
re.registerClass(Bb);
var Vb = class extends ns {
constructor(e) {
super(), this.gain = e.gain != null ? e.gain : 1;
}
apply(e, t) {
return q(() => {
if (e.length !== 2 || e[0] !== e[1])
throw new G("Identity matrix initializer can only be used for 2D square matrices.");
return V(this.gain, CS(e[0]));
});
}
getConfig() {
return { gain: this.gain };
}
};
Vb.className = "Identity";
re.registerClass(Vb);
function _z(e, t = "channelsLast") {
let n, s;
if (Ct(t), e.length === 2)
n = e[0], s = e[1];
else if ([3, 4, 5].indexOf(e.length) !== -1) {
if (t === "channelsFirst") {
let r = dr(e, 2);
n = e[1] * r, s = e[0] * r;
} else if (t === "channelsLast") {
let r = dr(e, 0, e.length - 2);
n = e[e.length - 2] * r, s = e[e.length - 1] * r;
}
} else {
let r = dr(e);
n = Math.sqrt(r), s = Math.sqrt(r);
}
return [n, s];
}
var xn = class extends ns {
constructor(e) {
if (super(), e.scale < 0)
throw new G(`scale must be a positive float. Got: ${e.scale}`);
this.scale = e.scale == null ? 1 : e.scale, this.mode = e.mode == null ? "fanIn" : e.mode, Tz(this.mode), this.distribution = e.distribution == null ? "normal" : e.distribution, $z(this.distribution), this.seed = e.seed;
}
apply(e, t) {
let n = _z(e), s = n[0], r = n[1], a = this.scale;
if (this.mode === "fanIn" ? a /= Math.max(1, s) : this.mode === "fanOut" ? a /= Math.max(1, r) : a /= Math.max(1, (s + r) / 2), this.distribution === "normal") {
let o = Math.sqrt(a);
if (t = t || "float32", t !== "float32" && t !== "int32")
throw new Fe(`${this.getClassName()} does not support dType ${t}.`);
return Sb(e, 0, o, t, this.seed);
} else {
let o = Math.sqrt(3 * a);
return Wl(e, -o, o, t);
}
}
getConfig() {
return { scale: this.scale, mode: this.mode, distribution: this.distribution, seed: this.seed };
}
};
xn.className = "VarianceScaling";
re.registerClass(xn);
var zp = class extends xn {
constructor(e) {
super({ scale: 1, mode: "fanAvg", distribution: "uniform", seed: e == null ? null : e.seed });
}
getClassName() {
return xn.className;
}
};
zp.className = "GlorotUniform";
re.registerClass(zp);
var Lp = class extends xn {
constructor(e) {
super({ scale: 1, mode: "fanAvg", distribution: "normal", seed: e == null ? null : e.seed });
}
getClassName() {
return xn.className;
}
};
Lp.className = "GlorotNormal";
re.registerClass(Lp);
var Mp = class extends xn {
constructor(e) {
super({ scale: 2, mode: "fanIn", distribution: "normal", seed: e == null ? null : e.seed });
}
getClassName() {
return xn.className;
}
};
Mp.className = "HeNormal";
re.registerClass(Mp);
var Bp = class extends xn {
constructor(e) {
super({ scale: 2, mode: "fanIn", distribution: "uniform", seed: e == null ? null : e.seed });
}
getClassName() {
return xn.className;
}
};
Bp.className = "HeUniform";
re.registerClass(Bp);
var Vp = class extends xn {
constructor(e) {
super({ scale: 1, mode: "fanIn", distribution: "normal", seed: e == null ? null : e.seed });
}
getClassName() {
return xn.className;
}
};
Vp.className = "LeCunNormal";
re.registerClass(Vp);
var Wp = class extends xn {
constructor(e) {
super({ scale: 1, mode: "fanIn", distribution: "uniform", seed: e == null ? null : e.seed });
}
getClassName() {
return xn.className;
}
};
Wp.className = "LeCunNormal";
re.registerClass(Wp);
var Wb = class extends ns {
constructor(e) {
if (super(), this.DEFAULT_GAIN = 1, this.gain = e.gain == null ? this.DEFAULT_GAIN : e.gain, this.seed = e.seed, this.seed != null)
throw new Fe("Random seed is not implemented for Orthogonal Initializer yet.");
}
apply(e, t) {
return q(() => {
if (e.length < 2)
throw new Fe("Shape must be at least 2D.");
e[0] * e[1] > 2e3 && console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${e[0] * e[1]}) elements: Slowness may result.`);
let n = e[0] > e[1] ? [e[1], e[0]] : e, s = Op(n, 0, 1, "float32"), r = cP.gramSchmidt(s);
return e[0] > e[1] && (r = Ge(r)), V(this.gain, r);
});
}
getConfig() {
return { gain: this.gain, seed: this.seed };
}
};
Wb.className = "Orthogonal";
re.registerClass(Wb);
var Rx = { constant: "Constant", glorotNormal: "GlorotNormal", glorotUniform: "GlorotUniform", heNormal: "HeNormal", heUniform: "HeUniform", identity: "Identity", leCunNormal: "LeCunNormal", leCunUniform: "LeCunUniform", ones: "Ones", orthogonal: "Orthogonal", randomNormal: "RandomNormal", randomUniform: "RandomUniform", truncatedNormal: "TruncatedNormal", varianceScaling: "VarianceScaling", zeros: "Zeros" };
function Dx(e, t = {}) {
return Ul(e, re.SerializationMap.getMap().classNameMap, t, "initializer");
}
function yt(e) {
return Db(e);
}
function ft(e) {
if (typeof e == "string") {
let t = e in Rx ? Rx[e] : e;
if (t === "GlorotNormal")
return new Lp();
if (t === "GlorotUniform")
return new zp();
if (t === "HeNormal")
return new Mp();
if (t === "HeUniform")
return new Bp();
if (t === "LeCunNormal")
return new Vp();
if (t === "LeCunUniform")
return new Wp();
{
let n = {};
return n.className = t, n.config = {}, Dx(n);
}
} else
return e instanceof ns ? e : Dx(e);
}
function Am(e) {
return Array.isArray(e) && Array.isArray(e[0]);
}
function _d(e) {
return e.length === 0 ? [] : Array.isArray(e[0]) ? e : [e];
}
function Oe(e) {
let t;
if (Array.isArray(e)) {
if (e.length !== 1)
throw new G(`Expected Tensor length to be 1; got ${e.length}`);
t = e[0];
} else
t = e;
return t;
}
function nt(e) {
if (Array.isArray(e) && Array.isArray(e[0])) {
if (e.length === 1)
return e = e, e[0];
throw new G(`Expected exactly 1 Shape; got ${e.length}`);
} else
return e;
}
function Ad(e) {
let t = 0;
for (let n of e)
n.shape.length === 0 ? t += 1 : t += n.shape.reduce((s, r) => s * r);
return t;
}
var Fx = "Variable";
var Az = class {
constructor(e, t = "float32", n = Fx, s = true, r = null) {
this.dtype = t == null ? "float32" : t, this.shape = e.shape, this.id = oI(), n = n == null ? Fx : n, this.originalName = uI(n), this.name = lI(this.originalName), this.trainable_ = s, this.constraint = r, this.val = hF(e, this.trainable_, this.name, this.dtype);
}
read() {
return this.assertNotDisposed(), this.val;
}
write(e) {
return this.assertNotDisposed(), Ez(this.val, e), this.val.id !== e.id && (this.val.assign(e), this.constraint != null && this.val.assign(this.constraint.apply(this.val))), this;
}
dispose() {
this.assertNotDisposed(), this.val.dispose();
}
assertNotDisposed() {
if (this.val.isDisposed)
throw new Error(`LayersVariable ${this.name} is already disposed.`);
}
get trainable() {
return this.trainable_;
}
set trainable(e) {
this.trainable_ = e, this.val.trainable = e;
}
};
function Ez(e, t) {
if (e.shape.toString() !== t.shape.toString())
throw new Error("Shape mismatch: " + JSON.stringify(e.shape) + " vs. " + JSON.stringify(t.shape));
}
function Em(e) {
return e.map((t) => t.read());
}
function Ub(e) {
e.forEach((t) => {
t[0].write(t[1]);
});
}
var Dt = class {
constructor(e) {
this.dtype = e.dtype, this.shape = e.shape, e.shape != null ? this.ndim = e.shape.length : this.ndim = e.ndim, this.maxNDim = e.maxNDim, this.minNDim = e.minNDim, this.axes = e.axes || {};
}
};
var $s = class {
constructor(e, t, n, s, r, a, o) {
this.dtype = e, this.shape = t, this.sourceLayer = n, this.inputs = s, this.callArgs = r, this.outputTensorIndex = o, this.id = oI(), a != null && (this.originalName = uI(a), this.name = lI(this.originalName)), this.rank = t.length;
}
};
var Rz = 0;
var Up = class {
constructor(e, t) {
this.callArgs = t, this.id = Rz++, this.outboundLayer = e.outboundLayer, this.inboundLayers = e.inboundLayers, this.nodeIndices = e.nodeIndices, this.tensorIndices = e.tensorIndices, this.inputTensors = e.inputTensors, this.outputTensors = e.outputTensors, this.inputMasks = e.inputMasks, this.outputMasks = e.outputMasks, this.inputShapes = e.inputShapes, this.outputShapes = e.outputShapes;
for (let n of e.inboundLayers)
n != null && n.outboundNodes.push(this);
e.outboundLayer.inboundNodes.push(this);
}
getConfig() {
let e = [];
for (let t of this.inboundLayers)
t != null ? e.push(t.name) : e.push(null);
return { outboundLayer: this.outboundLayer ? this.outboundLayer.name : null, inboundLayers: e, nodeIndices: this.nodeIndices, tensorIndices: this.tensorIndices };
}
};
var Dz = 0;
var He = class extends re.Serializable {
constructor(e = {}) {
super(), this._callHook = null, this._addedWeightNames = [], this._stateful = false, this.id = Dz++, this.activityRegularizer = null, this.inputSpec = null, this.supportsMasking = false, this._trainableWeights = [], this._nonTrainableWeights = [], this._losses = [], this._updates = [], this._built = false, this.inboundNodes = [], this.outboundNodes = [];
let t = e.name;
if (!t) {
let n = this.getClassName();
t = Vs(n) + "_" + Dp(n);
}
if (this.name = t, this.trainable_ = e.trainable == null ? true : e.trainable, e.inputShape != null || e.batchInputShape != null) {
let n;
if (e.batchInputShape != null)
n = e.batchInputShape;
else if (e.inputShape != null) {
let r = null;
e.batchSize != null && (r = e.batchSize), n = [r].concat(e.inputShape);
}
this.batchInputShape = n;
let s = e.dtype;
s == null && (s = e.inputDType), s == null && (s = "float32"), this.dtype = s;
}
e.weights != null ? this.initialWeights = e.weights : this.initialWeights = null, this._refCount = null, this.fastWeightInitDuringBuild = false;
}
static nodeKey(e, t) {
return e.name + "_ib-" + t.toString();
}
getNodeAtIndex(e, t) {
if (this.inboundNodes.length === 0)
throw new fs(`The layer has never been called and thus has no defined ${t}.`);
if (this.inboundNodes.length <= e)
throw new G(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);
return this.inboundNodes[e];
}
getInputAt(e) {
return bn(this.getNodeAtIndex(e, "input").inputTensors);
}
getOutputAt(e) {
return bn(this.getNodeAtIndex(e, "output").outputTensors);
}
get input() {
if (this.inboundNodes.length > 1)
throw new Bs(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);
if (this.inboundNodes.length === 0)
throw new Bs(`Layer ${this.name} is not connected, no input to return.`);
return bn(this.getNodeAtIndex(0, "input").inputTensors);
}
get output() {
if (this.inboundNodes.length === 0)
throw new Bs(`Layer ${this.name} has no inbound nodes.`);
if (this.inboundNodes.length > 1)
throw new Bs(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);
return bn(this.getNodeAtIndex(0, "output").outputTensors);
}
get losses() {
return this._losses;
}
calculateLosses() {
return this.losses.map((e) => e());
}
get updates() {
return this._updates;
}
get built() {
return this._built;
}
set built(e) {
this._built = e;
}
get trainable() {
return this.trainable_;
}
set trainable(e) {
this._trainableWeights.forEach((t) => t.trainable = e), this.trainable_ = e;
}
get trainableWeights() {
return this.trainable_ ? this._trainableWeights.filter((e) => e.trainable) : [];
}
set trainableWeights(e) {
this._trainableWeights = e;
}
get nonTrainableWeights() {
return this.trainable ? this._trainableWeights.filter((e) => !e.trainable).concat(this._nonTrainableWeights) : this._trainableWeights.concat(this._nonTrainableWeights);
}
set nonTrainableWeights(e) {
this._nonTrainableWeights = e;
}
get weights() {
return this.trainableWeights.concat(this.nonTrainableWeights);
}
get stateful() {
return this._stateful;
}
resetStates() {
if (!this.stateful)
throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.");
}
assertInputCompatibility(e) {
if (e = ht(e), this.inputSpec == null || this.inputSpec.length === 0)
return;
let t = ht(this.inputSpec);
if (e.length !== t.length)
throw new G(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);
for (let n = 0; n < e.length; n++) {
let s = e[n], r = t[n];
if (r == null)
continue;
let a = s.rank;
if (r.ndim != null && a !== r.ndim)
throw new G(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${r.ndim}, found ndim=${a}`);
if (r.maxNDim != null && a > r.maxNDim)
throw new G(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${r.maxNDim}, found ndim=${a}`);
if (r.minNDim != null && a < r.minNDim)
throw new G(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${r.minNDim}, found ndim=${a}.`);
if (r.dtype != null && s.dtype !== r.dtype)
throw new G(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${r.dtype}, found dtype=${s.dtype}.`);
if (r.axes) {
let o = s.shape;
for (let i in r.axes) {
let u = Number(i), l = r.axes[i], c = u >= 0 ? o[u] : o[o.length + u];
if (l != null && [l, null].indexOf(c) === -1)
throw new G(`Input ${n} is incompatible with layer ${this.name}: expected axis ${u} of input shape to have value ${l} but got shape ${o}.`);
}
}
if (r.shape != null)
for (let o = 0; o < r.shape.length; ++o) {
let i = r.shape[o], u = s.shape[o];
if (i != null && u != null && i !== u)
throw new G(`Input ${n} is incompatible with layer ${this.name}: expected shape=${r.shape}, found shape=${s.shape}.`);
}
}
}
call(e, t) {
return e;
}
invokeCallHook(e, t) {
this._callHook != null && this._callHook(e, t);
}
setCallHook(e) {
this._callHook = e;
}
clearCallHook() {
this._callHook = null;
}
apply(e, t) {
t = t || {}, this.assertNotDisposed();
let n = ht(e), s = true;
for (let a of n)
if (!(a instanceof $s)) {
s = false;
break;
}
let r = true;
for (let a of n)
if (a instanceof $s) {
r = false;
break;
}
if (s === r)
throw new G("Arguments to apply() must be all SymbolicTensors or all Tensors");
return na(this.name, () => {
if (!this.built) {
this.assertInputCompatibility(e);
let a = [];
for (let o of ht(e))
a.push(o.shape);
this.build(bn(a)), this.built = true, this.initialWeights && this.setWeights(this.initialWeights), this._refCount === null && r && (this._refCount = 1);
}
if (this.assertInputCompatibility(e), r) {
let a = this.call(e, t), o = ht(a), i = [];
for (let u of o)
n.indexOf(u) !== -1 && (u = u.clone()), i.push(u);
if (a = bn(i), this.activityRegularizer != null)
throw new Fe("Layer invocation in the presence of activity regularizer(s) is not supported yet.");
return a;
} else {
let a = Fz(e), o = this.computeOutputShape(a), i, u = Oz(e);
if (this.warnOnIncompatibleInputShape(Array.isArray(e) ? a[0] : a), o != null && o.length > 0 && Array.isArray(o[0]) ? i = o.map((l, c) => new $s(u, l, this, ht(e), t, this.name, c)) : i = new $s(u, o, this, ht(e), t, this.name), this.addInboundNode(e, i, null, null, a, o, t), this._refCount++, this.activityRegularizer != null)
throw new Fe("Layer invocation in the presence of activity regularizer(s) is not supported yet.");
return i;
}
});
}
warnOnIncompatibleInputShape(e) {
if (this.batchInputShape != null)
if (e.length !== this.batchInputShape.length)
console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);
else {
let t = false;
this.batchInputShape.forEach((n, s) => {
n != null && e[s] != null && e[s] !== n && (t = true);
}), t && console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`);
}
}
get outputShape() {
if (this.inboundNodes == null || this.inboundNodes.length === 0)
throw new Bs(`The layer ${this.name} has never been called and thus has no defined output shape.`);
let e = [];
for (let t of this.inboundNodes) {
let n = JSON.stringify(t.outputShapes);
e.indexOf(n) === -1 && e.push(n);
}
if (e.length === 1) {
let t = this.inboundNodes[0].outputShapes;
return Array.isArray(t) && Array.isArray(t[0]) && t.length === 1 ? t[0] : t;
} else
throw new Bs(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`);
}
countParams() {
if (!this.built)
throw new fs(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);
return Ad(this.weights);
}
build(e) {
this.built = true;
}
getWeights(e = false) {
return Em(e ? this.trainableWeights : this.weights);
}
setWeights(e) {
q(() => {
let t = this.weights;
if (t.length !== e.length)
throw new G(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);
if (t.length === 0)
return;
let n = [], s = Em(t);
for (let r = 0; r < s.length; ++r) {
let a = s[r], o = t[r], i = e[r];
if (!w.arraysEqual(a.shape, i.shape))
throw new G(`Layer weight shape ${a.shape} not compatible with provided weight shape ${i.shape}`);
n.push([o, i]);
}
Ub(n);
});
}
addWeight(e, t, n, s, r, a, o, i) {
if (this._addedWeightNames.indexOf(e) !== -1)
throw new G(`Duplicate weight name ${e} for layer ${this.name}`);
this._addedWeightNames.push(e), n == null && (n = "float32"), this.fastWeightInitDuringBuild && (s = i != null ? i() : ft("zeros"));
let u = s.apply(t, n), l = new Az(u, n, e, a, o);
return u.dispose(), r != null && this.addLoss(() => r.apply(l.read())), a == null && (a = true), a ? this._trainableWeights.push(l) : this._nonTrainableWeights.push(l), l;
}
setFastWeightInitDuringBuild(e) {
this.fastWeightInitDuringBuild = e;
}
addLoss(e) {
e == null || Array.isArray(e) && e.length === 0 || (e = ht(e), this._losses !== void 0 && this._losses !== null && this.losses.push(...e));
}
computeOutputShape(e) {
return e;
}
computeMask(e, t) {
if (!this.supportsMasking) {
if (t != null)
if (Array.isArray(t))
t.forEach((n) => {
if (n != null)
throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);
});
else
throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);
return null;
}
return t;
}
addInboundNode(e, t, n, s, r, a, o = null) {
let i = ht(e);
t = ht(t), n = ht(n), s = ht(s), r = _d(r), a = _d(a);
let u = [], l = [], c = [];
for (let p of i)
u.push(p.sourceLayer), l.push(p.nodeIndex), c.push(p.tensorIndex);
new Up({ outboundLayer: this, inboundLayers: u, nodeIndices: l, tensorIndices: c, inputTensors: i, outputTensors: t, inputMasks: n, outputMasks: s, inputShapes: r, outputShapes: a }, o);
for (let p = 0; p < t.length; p++)
t[p].sourceLayer = this, t[p].nodeIndex = this.inboundNodes.length - 1, t[p].tensorIndex = p;
}
getConfig() {
let e = { name: this.name, trainable: this.trainable };
return this.batchInputShape != null && (e.batchInputShape = this.batchInputShape), this.dtype != null && (e.dtype = this.dtype), e;
}
disposeWeights() {
return this.weights.forEach((e) => e.dispose()), this.weights.length;
}
assertNotDisposed() {
if (this._refCount === 0)
throw new Error(`Layer '${this.name}' is already disposed.`);
}
dispose() {
if (!this.built)
throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);
if (this._refCount === null)
throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);
this.assertNotDisposed();
let e = 0;
return --this._refCount === 0 && (e = this.disposeWeights()), { refCountAfterDispose: this._refCount, numDisposedVariables: e };
}
};
function Fz(e) {
e = ht(e);
let t = [];
for (let n of e)
t.push(n.shape);
return bn(t);
}
function Oz(e) {
return "float32";
}
function hI(e, t, n) {
if ((t == null || n != null && n > 0) && (t = e.sourceLayer, n = e.nodeIndex), t.inboundNodes.length === 0)
return [e];
{
let s = t.inboundNodes[n];
if (s.inboundLayers.length === 0)
return s.inputTensors;
{
let r = [];
for (let a = 0; a < s.inboundLayers.length; a++) {
let o = s.inputTensors[a], i = s.inboundLayers[a], u = s.nodeIndices[a], l = hI(o, i, u);
for (let c of l)
r.indexOf(c) === -1 && r.push(c);
}
return r;
}
}
}
var tu = class extends He {
constructor(e) {
if (super({ dtype: e.dtype, name: e.name != null ? e.name : Dp("input").toString() }), e.batchSize == null && (e.batchSize = null), e.sparse == null && (e.sparse = false), this.trainable = false, this.built = true, this.sparse = e.sparse, e.inputShape != null && e.batchInputShape != null)
throw new G("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");
let t = e.batchInputShape;
if (t == null) {
if (e.inputShape == null)
throw new G("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");
t = [e.batchSize].concat(e.inputShape);
} else if (e.batchSize != null)
throw new G("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");
let n = e.dtype || "float32";
this.batchInputShape = t, this.dtype = n, this.inputSpec = [{ shape: t }];
let s = new $s(this.dtype, this.batchInputShape, this, [], {}, this.name);
s.nodeIndex = 0, s.tensorIndex = 0, new Up({ outboundLayer: this, inboundLayers: [], nodeIndices: [], tensorIndices: [], inputTensors: [s], outputTensors: [s], inputMasks: [null], outputMasks: [null], inputShapes: [t], outputShapes: [t] });
}
apply(e, t) {
throw new G(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`);
}
dispose() {
return { refCountAfterDispose: this._refCount, numDisposedVariables: 0 };
}
getConfig() {
return { batchInputShape: this.batchInputShape, dtype: this.dtype, sparse: this.sparse, name: this.name };
}
};
tu.className = "InputLayer";
re.registerClass(tu);
function fI(e) {
if (e.batchShape == null && e.shape == null)
throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");
if (e.batchShape != null && e.shape != null)
throw new G("Please provide either a `shape` or `batchShape` argument to Input, but not both.");
let t = e.batchShape;
e.shape != null && t == null && (t = [null].concat(e.shape));
let n = e.dtype;
return n == null && (n = "float32"), new tu({ batchInputShape: t, name: e.name, dtype: n, sparse: e.sparse }).inboundNodes[0].outputTensors[0];
}
function Pz(e, t) {
if (e.dtype == null || e.dtype === t.dtype)
return t;
try {
return le(t, e.dtype);
} catch (n) {
throw new G(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`);
}
}
var Jr = class {
constructor(e) {
if (this.id2Value = {}, this.id2Mask = {}, this.name2Id = {}, e instanceof Jr)
for (let t in e.id2Value)
this.id2Value[t] = e.id2Value[t], t in e.id2Mask && (this.id2Mask[t] = e.id2Mask[t]);
else {
if (e == null)
return;
for (let t of e)
this.add(t.key, t.value);
}
}
add(e, t, n) {
if (this.id2Value[e.id] == null)
this.id2Value[e.id] = Pz(e, t), this.name2Id[e.name] = e.id, n != null && (this.id2Mask[e.id] = n);
else
throw new G(`Duplicate key: name=${e.name}, id=${e.id}`);
return this;
}
addFeed(e) {
this.add(e.key, e.value);
}
hasKey(e) {
return this.id2Value[e.id] != null;
}
names() {
return Object.keys(this.name2Id);
}
getValue(e) {
if (e instanceof $s) {
if (this.id2Value[e.id] == null)
throw new G(`Nonexistent key: ${e.name}`);
return this.id2Value[e.id];
} else {
let t = this.name2Id[e];
if (t == null)
throw new G(`Feed dict has no SymbolicTensor name: ${e}`);
return this.id2Value[t];
}
}
getMask(e) {
if (e instanceof $s) {
if (this.id2Value[e.id] == null)
throw new G(`Nonexistent key: ${e.name}`);
return this.id2Mask[e.id];
} else {
let t = this.name2Id[e];
if (t == null)
throw new G(`Feed dict has no SymbolicTensor name: ${e}`);
return this.id2Mask[t];
}
}
disposeMasks() {
this.id2Mask != null && De(this.id2Mask);
}
};
var Ed = new sI();
var Rd = new sI();
function zz(e) {
Ed != null && Ed.setMaxEntries(e), Rd != null && Rd.setMaxEntries(e);
}
function Fu(e, t, n, s) {
let r = n == null ? false : n.training, a = Array.isArray(e), o = a ? e : [e], i = o.map((f) => f.name), u = [], l = t.names();
for (let f of i)
l.indexOf(f) !== -1 ? u.push(t.getValue(f)) : u.push(null);
s != null && (s.maxNumTensors = -1 / 0, s.minNumTensors = 1 / 0);
let c = i.join(",") + "|" + t.names().sort().join(","), p = Ed.get(c), d;
if (p == null) {
let f = Lz(o, t);
p = f.sorted, d = f.recipientCounts, Ed.put(c, p), Rd.put(c, d);
}
d = {}, r || Object.assign(d, Rd.get(c));
let h = new Jr(t);
for (let f = 0; f < p.length; ++f) {
if (s != null) {
let E = xm().numTensors;
E > s.maxNumTensors && (s.maxNumTensors = E), E < s.minNumTensors && (s.minNumTensors = E);
}
let m = p[f], g = m.sourceLayer;
if (g instanceof tu)
continue;
let b = [], y = [], v = [], x = false;
for (let E of m.inputs) {
let P = h.getValue(E), A = h.getMask(E);
b.push(P), y.push(A), A != null && (x = true), r || (d[E.name]--, d[E.name] === 0 && !t.hasKey(E) && i.indexOf(E.name) === -1 && !P.isDisposed && E.sourceLayer.stateful !== true && v.push(P));
}
x && (n = n || {}, n.mask = y[0]);
let k = ht(g.apply(b, n)), I = null;
g.supportsMasking && (I = g.computeMask(b, y));
let $ = Bz(m), R = Array.isArray($) ? $ : [$];
for (let E = 0; E < R.length; ++E) {
h.hasKey(R[E]) || h.add(R[E], k[E], Array.isArray(I) ? I[0] : I);
let P = i.indexOf(R[E].name);
P !== -1 && (u[P] = k[E]);
}
r || De(v);
}
return h.disposeMasks(), a ? u : u[0];
}
function Lz(e, t) {
w.assert(e != null && e.length > 0, () => "Expected at least one fetch, got none");
let n = [], s = {};
if (e.length === 1) {
let r = Ox(e[0], t);
n = r.sorted, s = r.recipientMap;
} else {
let r = /* @__PURE__ */ new Set();
for (let a of e) {
let { sorted: o, recipientMap: i } = Ox(a, t);
for (let u of o)
r.has(u.name) || (n.push(u), r.add(u.name));
for (let u in i)
s[u] == null && (s[u] = /* @__PURE__ */ new Set()), i[u].forEach((l) => s[u].add(l));
}
}
return { sorted: n, recipientCounts: Mz(s) };
}
function Mz(e) {
let t = {};
for (let n in e)
t[n] = e[n].size;
return t;
}
function Ox(e, t) {
let n = /* @__PURE__ */ new Set(), s = [], r = {};
for (let i of t.names())
n.add(i);
let a = [], o = [];
for (a.push(e); a.length > 0; ) {
let i = a[a.length - 1];
if (n.has(i.name)) {
a.pop();
continue;
}
let u = o[o.length - 1] === a.length - 1;
if (i.inputs.length === 0 || u)
a.pop(), s.push(i), n.add(i.name), u && o.pop();
else {
o.push(a.length - 1);
for (let l of i.inputs)
r[l.name] == null && (r[l.name] = /* @__PURE__ */ new Set()), r[l.name].add(i.name), !n.has(l.name) && a.push(l);
}
}
return { sorted: s, recipientMap: r };
}
function Bz(e) {
let t;
if (e.sourceLayer.inboundNodes.length === 1)
t = e.sourceLayer.output;
else {
let n = null;
for (let s = 0; s < e.sourceLayer.inboundNodes.length; ++s)
for (let r of e.sourceLayer.inboundNodes[s].outputTensors)
if (r.id === e.id) {
n = s;
break;
}
t = e.sourceLayer.getOutputAt(n);
}
return t;
}
var Vz = K();
Vz.registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES", () => 100, zz);
var mI = { kernelName: di, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => V(e, Tp(le(n, "float32"), -1)) };
} };
var Wz = { kernelName: ul, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => {
let s = ct(le(n, "float32")), r = dn(ge(we(1), s));
return vt(xe(e, r));
} };
} };
var Uz = { kernelName: ll, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => {
let s = dn(ge(ct(le(n, "float32")), 1));
return xe(e, s);
} };
} };
var Gz = { kernelName: Cr, inputsToSave: ["a", "b"], gradFunc: (e, t) => {
let [n, s] = t, r = at(n.shape, s.shape);
return { a: () => {
let i = e, u = _t(n.shape, r);
return u.length > 0 && (i = ve(i, u)), U(i, n.shape);
}, b: () => {
let i = e, u = _t(s.shape, r);
return u.length > 0 && (i = ve(i, u)), U(i, s.shape);
} };
} };
var Hz = { kernelName: Sa, saveAllInputs: true, gradFunc: (e, t) => {
let n = {};
return t.forEach((s, r) => {
n[r] = () => e.clone();
}), n;
} };
var qz = { kernelName: Ia, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => je(n) };
} };
var jz = { kernelName: pl, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => je(n) };
} };
var Kz = { kernelName: hl, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => xe(e, dn(ge(we(1), ct(le(n, "float32"))))) };
} };
var Xz = { kernelName: fl, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => {
let s = dn(oe(we(1), ct(le(n, "float32"))));
return xe(e, s);
} };
} };
var Yz = { kernelName: bl, inputsToSave: ["a", "b"], gradFunc: (e, t) => {
let [n, s] = t, r = at(n.shape, s.shape);
return { a: () => {
let i = oe(ct(n), ct(s)), u = V(e, xe(s, i)), l = _t(n.shape, r);
return l.length > 0 && (u = ve(u, l)), U(u, n.shape);
}, b: () => {
let i = oe(ct(n), ct(s)), u = vt(V(e, xe(n, i))), l = _t(s.shape, r);
return l.length > 0 && (u = ve(u, l)), U(u, s.shape);
} };
} };
var Qz = { kernelName: ml, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => xe(e, oe(ct(le(n, "float32")), 1)) };
} };
var Zz = { kernelName: gl, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => xe(e, ge(we(1), ct(le(n, "float32")))) };
} };
function Jz(e, t, n, s, r, a) {
let o = _(e, "dy", "avgPool3dGrad"), i = _(t, "input", "avgPool3dGrad"), u = o, l = i, c = false;
i.rank === 4 && (c = true, u = U(o, [1, o.shape[0], o.shape[1], o.shape[2], o.shape[3]]), l = U(i, [1, i.shape[0], i.shape[1], i.shape[2], i.shape[3]])), O(u.rank === 5, () => `Error in avgPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`), O(l.rank === 5, () => `Error in avgPool3dGrad: input must be rank 5 but got rank ${l.rank}.`), fn("avgPool3dGrad", r, a);
let p = { dy: u, input: l }, d = { filterSize: n, strides: s, pad: r, dimRoundingMode: a }, h = z.runKernel(yg, p, d);
return c ? U(h, [h.shape[1], h.shape[2], h.shape[3], h.shape[4]]) : h;
}
var eL = M({ avgPool3dGrad_: Jz });
var tL = { kernelName: tp, inputsToSave: ["x"], gradFunc: (e, t, n) => {
let [s] = t, { filterSize: r, strides: a, pad: o, dimRoundingMode: i } = n;
return { x: () => eL(e, s, r, a, o, i) };
} };
function nL(e, t, n, s, r) {
let a = _(e, "dy", "avgPoolGrad"), o = _(t, "input", "avgPoolGrad");
O(o.rank === a.rank, () => `Rank of input (${o.rank}) does not match rank of dy (${a.rank})`);
let i = o, u = a, l = false;
o.rank === 3 && (l = true, i = U(o, [1, o.shape[0], o.shape[1], o.shape[2]]), u = U(a, [1, a.shape[0], a.shape[1], a.shape[2]])), O(u.rank === 4, () => `Error in avgPoolGrad: dy must be rank 4 but got rank ${u.rank}.`), O(i.rank === 4, () => `Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);
let c = { dy: u, input: i }, p = { filterSize: n, strides: s, pad: r }, d = z.runKernel(bg, c, p);
return l ? U(d, [d.shape[1], d.shape[2], d.shape[3]]) : d;
}
var sL = M({ avgPoolGrad_: nL });
var rL = { kernelName: Ca, inputsToSave: ["x"], gradFunc: (e, t, n) => {
let [s] = t, { filterSize: r, strides: a, pad: o } = n;
return { x: () => sL(e, s, r, a, o) };
} };
var aL = { kernelName: Na, inputsToSave: ["a", "b"], gradFunc: (e, t, n) => {
let [s, r] = t, { transposeA: a, transposeB: o } = n;
return !a && !o ? { a: () => We(e, r, false, true), b: () => We(s, e, true, false) } : !a && o ? { a: () => We(e, r, false, false), b: () => We(e, s, true, false) } : a && !o ? { a: () => We(r, e, false, true), b: () => We(s, e, false, false) } : { a: () => We(r, e, true, true), b: () => We(e, s, true, true) };
} };
var oL = { kernelName: pi, gradFunc: (e, t, n) => {
let { blockShape: s, crops: r } = n;
return { x: () => fb(e, s, r) };
} };
var iL = { kernelName: j$, gradFunc: (e, t, n) => {
let s = n, r = s.inputShape, a = s.shape, o = Array.from(a);
for (let u = r.length - 1; u >= 0; u--)
if (r[u] === a[u])
o[u] = 1;
else if (r[u] !== 1)
throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${a}].`);
let i = [];
for (let u = 0; u < o.length; u++)
o[u] > 1 && i.push(u);
return { x: () => ve(e, i, true) };
} };
var uL = { kernelName: Ta, gradFunc: (e) => ({ x: () => e.clone() }) };
var lL = { kernelName: $a, gradFunc: (e) => ({ x: () => je(e) }) };
var cL = { kernelName: Nr, inputsToSave: ["x"], gradFunc: (e, t, n) => {
let [s] = t, { clipValueMin: r, clipValueMax: a } = n;
return { x: () => vn(Ds(Zi(s, r), Ji(s, a)), e, je(e)) };
} };
var dL = { kernelName: sp, inputsToSave: ["x"], gradFunc: mI.gradFunc };
var pL = { kernelName: hi, saveAllInputs: true, gradFunc: (e, t, n) => {
let s = t.map((u) => u.shape), { axis: r } = n, a = ts(r, t[0].shape)[0], o = s.map((u) => u[a]);
return Bn(e, o, a).map((u) => () => u);
} };
var hL = { kernelName: _a, inputsToSave: ["x", "filter"], gradFunc: (e, t, n) => {
let [s, r] = t, { dilations: a, strides: o, pad: i, dataFormat: u } = n;
return O(gr(a), () => `Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`), { x: () => rb(s.shape, e, r, o, i, u), filter: () => Ib(s, e, r.shape, o, i, u) };
} };
var fL = { kernelName: Aa, inputsToSave: ["dy", "filter"], gradFunc: (e, t, n) => {
let [s, r] = t, { strides: a, pad: o, dataFormat: i, dimRoundingMode: u } = n;
return { dy: () => da(e, r, a, o, i, 1, u), filter: () => Ib(e, s, r.shape, a, o, i, u) };
} };
function mL(e, t, n, s, r) {
let a = e;
e.rank === 4 && (a = U(e, [1, e.shape[0], e.shape[1], e.shape[2], e.shape[3]]));
let o = t;
o.rank === 4 && (o = U(t, [1, t.shape[0], t.shape[1], t.shape[2], t.shape[3]])), O(a.rank === 5, () => `Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`), O(o.rank === 5, () => `Error in conv3dDerFilter: dy must be rank 5, but got shape ${o.shape}.`), O(n.length === 5, () => `Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`), O(a.shape[4] === n[3], () => `Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${n[3]}.`), O(o.shape[4] === n[4], () => `Error in conv3dDerFilter: depth of dy (${o.shape[4]}) must match output depth for filter (${n[4]}).`);
let i = { x: a, dy: o }, u = { strides: s, pad: r, filterShape: n };
return z.runKernel(kg, i, u);
}
var gL = M({ conv3DBackpropFilter_: mL });
var bL = { kernelName: rp, inputsToSave: ["x", "filter"], gradFunc: (e, t, n) => {
let { dilations: s, strides: r, pad: a } = n;
O(gr(s), () => `Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);
let [o, i] = t;
return { x: () => yS(o.shape, e, i, r, a), filter: () => gL(o, e, i.shape, r, a) };
} };
var yL = { kernelName: Ea, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => V(vt(PS(le(n, "float32"))), e) };
} };
var vL = { kernelName: Ra, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => V(zS(le(n, "float32")), e) };
} };
var xL = { kernelName: Da, inputsToSave: ["x"], gradFunc: (e, t, n) => {
let [s] = t, { axis: r, exclusive: a, reverse: o } = n;
return { x: () => {
let i = SS([r], s.rank), u = xS(e, r, a, !o);
return i != null && (u = Ge(u, i)), u;
} };
} };
var wL = { kernelName: Fa, inputsToSave: ["x", "filter"], gradFunc: (e, t, n) => {
let { dilations: s, strides: r, pad: a, dimRoundingMode: o } = n, i = s == null ? [1, 1] : s;
O(gr(i), () => `Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);
let [u, l] = t;
return O(u.rank === 4, () => `Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${u.rank}.`), O(l.rank === 4, () => `Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${l.rank}.`), O(u.shape[3] === l.shape[2], () => `Error in gradient of depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`), O(Ps(r, i), () => `Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'.`), fn("depthwiseConv2d", a, o), { x: () => qS(u.shape, e, l, r, a, i, o), filter: () => HS(u, e, l.shape, r, a, i, o) };
} };
var kL = { kernelName: ap, inputsToSave: ["x", "filter"], gradFunc: (e, t, n) => {
let [s, r] = t, a = { x: s, filter: r, dy: e }, o = { x: s, filter: r, dy: e };
return { x: () => z.runKernel(im, a, n), filter: () => z.runKernel(um, o, n) };
} };
var SL = { kernelName: Pa, outputsToSave: [true], gradFunc: (e, t) => {
let [n] = t, s = { dy: e, y: n };
return { x: () => z.runKernel($g, s) };
} };
var IL = { kernelName: yl, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t, s = V(Yn(vt(ct(n))), 2 / Math.sqrt(Math.PI));
return { x: () => V(e, s) };
} };
var CL = { kernelName: za, outputsToSave: [true], gradFunc: (e, t) => {
let [n] = t;
return { x: () => V(e, n) };
} };
var NL = { kernelName: yi, inputsToSave: ["input"], gradFunc: (e, t) => {
let [n] = t;
return { input: () => U(e, n.shape) };
} };
var TL = { kernelName: vi, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => V(e, Yn(n)) };
} };
var $L = { kernelName: La, gradFunc: (e) => ({ x: () => je(e) }) };
var _L = { kernelName: Ma, inputsToSave: ["a", "b"], gradFunc: (e, t) => {
let [n, s] = t, r = at(n.shape, s.shape);
return { a: () => {
let i = xe(e, le(s, "float32")), u = _t(n.shape, r);
return u.length > 0 ? U(ve(i, u), n.shape) : i;
}, b: () => {
let i = V(e, le(n, "float32")), u = _t(s.shape, r);
u.length > 0 && (i = U(ve(i, u), s.shape));
let l = ct(s);
return vt(xe(i, le(l, "float32")));
} };
} };
var AL = { kernelName: Ba, inputsToSave: ["x", "mean", "variance", "scale"], gradFunc: (e, t, n) => {
let { varianceEpsilon: s } = n, [r, a, o, i] = t, u = i == null ? we(1) : i, l = _t(a.shape, r.shape), c = [];
if (a.rank === 1) {
for (let x = 0; x < r.shape.length - 1; ++x)
c.push(r.shape[x]);
c.push(1);
}
let p = ge(r, a), d = V(e, u), h = FS(oe(o, we(s))), f = V(V(V(h, h), h), we(-0.5));
return { x: () => a.rank === 1 ? U(V(V(e, hs(U(h, [1, 1, 1, a.shape[0]]), c)), u), r.shape) : U(V(V(e, h), u), r.shape), mean: () => {
let x = V(V(h, we(-1)), d);
return a.rank === 1 && (x = ve(x, l)), U(x, a.shape);
}, variance: () => {
let x = V(V(f, p), d);
return a.rank === 1 && (x = ve(x, l)), U(x, a.shape);
}, scale: () => {
let x = V(p, h), k = V(e, x);
return a.rank === 1 && (k = ve(k, l)), U(k, a.shape);
}, offset: () => {
let x = e;
return a.rank === 1 && (x = ve(x, l)), U(x, a.shape);
} };
} };
var EL = { kernelName: wi, inputsToSave: ["x", "indices"], gradFunc: (e, t, n) => {
let [s, r] = t, { axis: a } = n, o = ts(a, s.shape)[0];
return { x: () => {
let u = s.shape, l = r.size, c = u.slice(0, o), p = c.length, d = u.slice(a, u.length).slice(1), h = d.length, f = Px(0, p), m = Px(p + 1, p + 1 + h), g = zx([c, [l], d]), b = U(e, g), y = U(r, [l]), v = zx([[p], f, m]), x = Ge(b, v), k = cF(x, y, s.shape[o]), I = ib(v);
return k = Ge(k, I), k;
}, indices: () => r };
} };
function Px(e, t) {
let n = [];
for (let s = e; s < t; ++s)
n.push(s);
return n;
}
function zx(e) {
let t = [];
for (let n = 0; n < e.length; ++n)
for (let s = 0; s < e[n].length; ++s)
t.push(e[n][s]);
return t;
}
var RL = { kernelName: Va, inputsToSave: ["a", "b"], gradFunc: (e, t) => {
let [n, s] = t;
return { a: () => je(n), b: () => je(s) };
} };
var DL = { kernelName: Wa, gradFunc: (e) => ({ x: () => le(e, "float32") }) };
var FL = { kernelName: xl, gradFunc: (e) => ({ x: () => je(e) }) };
var OL = { kernelName: wl, gradFunc: (e) => ({ x: () => je(e) }) };
var PL = { kernelName: kl, gradFunc: (e) => ({ x: () => je(e) }) };
var zL = { kernelName: Ua, inputsToSave: ["x"], gradFunc: (e, t, n) => {
let [s] = t, { alpha: r } = n, a = Gn(s, 0);
return { x: () => vn(a, e, V(e, r)) };
} };
var LL = { kernelName: Sl, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => xe(e, oe(n, 1)) };
} };
var ML = { kernelName: Ga, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => xe(e, le(n, "float32")) };
} };
var BL = { kernelName: X$, inputsToSave: [], outputsToSave: [true], gradFunc: (e, t, n) => {
let [s] = t, { axis: r } = n;
return { logits: () => {
let o = Yn(s);
return ge(e, V(ve(e, r, true), o));
} };
} };
function VL(e, t, n, s = 5, r = 1, a = 1, o = 0.5) {
let i = { x: e, y: t, dy: n }, u = { depthRadius: s, bias: r, alpha: a, beta: o };
return z.runKernel(Rg, i, u);
}
var WL = M({ localResponseNormalizationBackprop_: VL });
var UL = { kernelName: up, inputsToSave: ["x"], outputsToSave: [true], gradFunc: (e, t, n) => {
let [s, r] = t, { depthRadius: a, bias: o, alpha: i, beta: u } = n;
return { x: () => WL(s, r, e, a, o, i, u) };
} };
function gI(e, t, n, s) {
return t.rank < n.rank && (t = U(t, pa(t.shape, s))), e.rank < n.rank && (e = U(e, pa(e.shape, s))), { x: () => V(e, le(Xn(n, t), e.dtype)) };
}
var Lx = { kernelName: Ha, inputsToSave: ["x"], outputsToSave: [true], gradFunc: (e, t, n) => {
let s = n, { reductionIndices: r } = s, a = t[0], o = t[1], i = ts(r, a.shape), u = gI(e, o, a, i);
return { x: () => u.x() };
} };
var GL = { kernelName: qa, inputsToSave: ["a", "b"], gradFunc: (e, t) => {
let [n, s] = t;
return { a: () => V(e, le(Zi(n, s), "float32")), b: () => V(e, le(NS(n, s), "float32")) };
} };
function HL(e, t, n, s, r, a, o) {
let i = _(e, "dy", "maxPool3dGrad"), u = _(t, "input", "maxPool3dGrad"), l = _(n, "output", "maxPool3dGrad"), c = i, p = u, d = l, h = false;
u.rank === 4 && (h = true, c = U(i, [1, i.shape[0], i.shape[1], i.shape[2], i.shape[3]]), p = U(u, [1, u.shape[0], u.shape[1], u.shape[2], u.shape[3]]), d = U(l, [1, l.shape[0], l.shape[1], l.shape[2], l.shape[3]])), O(c.rank === 5, () => `Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`), O(p.rank === 5, () => `Error in maxPool3dGrad: input must be rank 5 but got rank ${p.rank}.`), O(d.rank === 5, () => `Error in maxPool3dGrad: output must be rank 5 but got rank ${d.rank}.`), fn("maxPool3dGrad", a, o);
let f = { dy: c, input: p, output: d }, m = { filterSize: s, strides: r, pad: a, dimRoundingMode: o }, g = z.runKernel(Fg, f, m);
return h ? U(g, [g.shape[1], g.shape[2], g.shape[3], g.shape[4]]) : g;
}
var qL = M({ maxPool3dGrad_: HL });
var jL = { kernelName: lp, inputsToSave: ["x"], outputsToSave: [true], gradFunc: (e, t, n) => {
let [s, r] = t, { filterSize: a, strides: o, pad: i, dimRoundingMode: u } = n;
return { x: () => qL(e, s, r, a, o, i, u) };
} };
function KL(e, t, n, s, r, a, o) {
let i = _(e, "dy", "maxPoolGrad"), u = _(t, "input", "maxPoolGrad"), l = _(n, "output", "maxPoolGrad");
O(u.rank === i.rank, () => `Rank of input (${u.rank}) does not match rank of dy (${i.rank})`), O(i.rank === 4, () => `Error in maxPoolGrad: dy must be rank 4 but got rank ${i.rank}.`), O(u.rank === 4, () => `Error in maxPoolGrad: input must be rank 4 but got rank ${u.rank}.`), fn("maxPoolGrad", a, o);
let c = { dy: i, input: u, output: l }, p = { filterSize: s, strides: r, pad: a, dimRoundingMode: o };
return z.runKernel(Dg, c, p);
}
var XL = M({ maxPoolGrad_: KL });
var YL = { kernelName: ja, inputsToSave: ["x"], outputsToSave: [true], gradFunc: (e, t, n) => {
let [s, r] = t, { filterSize: a, strides: o, pad: i } = n;
return { x: () => XL(e, s, r, a, o, i) };
} };
var QL = { kernelName: Ka, inputsToSave: ["x"], gradFunc: (e, t, n) => {
let [s] = t, { axis: r } = n, a = ts(r, s.shape), i = kS(s.shape, a)[1], u = dt(i);
return { x: () => {
let c = s.shape.slice();
a.forEach((h) => {
c[h] = 1;
});
let p = U(e, c);
return xe(V(p, Ln(s.shape, "float32")), u);
} };
} };
var ZL = { kernelName: Xa, inputsToSave: ["x"], outputsToSave: [true], gradFunc: (e, t, n) => {
let s = n, { axis: r } = s, [a, o] = t, i = ts(r, a.shape), u = gI(e, o, a, i);
return { x: () => u.x() };
} };
var JL = { kernelName: Ya, inputsToSave: ["a", "b"], gradFunc: (e, t) => {
let [n, s] = t;
return { a: () => V(e, le(Ji(n, s), "float32")), b: () => V(e, le(Gn(n, s), "float32")) };
} };
var eM = { kernelName: Qa, inputsToSave: ["x"], gradFunc: (e, t, n) => {
let s = t[0], { paddings: r } = n, a = r.map((o) => o[0]);
return { x: () => qe(e, a, s.shape) };
} };
var tM = { kernelName: Cl, inputsToSave: ["a", "b"], gradFunc: (e, t) => {
let [n, s] = t, r = at(n.shape, s.shape);
return { a: () => {
let i = _t(n.shape, r);
return i.length > 0 ? U(ve(e, i), n.shape) : e;
}, b: () => {
let i = V(e, vt(Ip(xe(n, s)))), u = _t(s.shape, r);
return u.length > 0 ? U(ve(i, u), s.shape) : i;
} };
} };
var nM = { kernelName: Za, inputsToSave: ["a", "b"], gradFunc: (e, t) => {
let [n, s] = t, r = at(n.shape, s.shape);
return { a: () => {
let i = V(e, le(s, "float32")), u = _t(n.shape, r);
return u.length > 0 ? U(ve(i, u), n.shape) : i;
}, b: () => {
let i = V(e, le(n, "float32")), u = _t(s.shape, r);
return u.length > 0 ? U(ve(i, u), s.shape) : i;
} };
} };
var sM = { kernelName: $i, gradFunc: (e) => ({ x: () => vt(e) }) };
var rM = { kernelName: Di, inputsToSave: ["indices"], gradFunc: (e, t) => {
let n = t[0];
return { indices: () => $t(n.shape, "float32") };
} };
var aM = { kernelName: Ri, gradFunc: (e) => ({ x: () => je(e) }) };
var oM = { kernelName: Fi, saveAllInputs: true, gradFunc: (e, t, n) => {
let { axis: s } = n;
return Fs(e, s).map((a) => () => a);
} };
var Mx = { kernelName: Ja, inputsToSave: ["x"], gradFunc: (e, t, n) => {
let s = t[0], { paddings: r } = n, a = r.map((o) => o[0]);
return { x: () => qe(e, a, s.shape) };
} };
var iM = { kernelName: eo, inputsToSave: ["a", "b"], outputsToSave: [true], gradFunc: (e, t) => {
let [n, s, r] = t, a = n, o = s, i = at(a.shape, o.shape);
return { a: () => {
let c = le(o, "float32"), p = V(e, V(c, ha(a, ge(c, we(1))))), d = _t(a.shape, i);
return d.length > 0 && (p = ve(p, d)), U(p, a.shape);
}, b: () => {
let c = Gn(a, 0), p = vn(c, Qn(a), je(a)), d = V(e, V(r, p)), h = _t(o.shape, i);
return h.length > 0 && (d = ve(d, h)), U(d, o.shape);
} };
} };
var uM = { kernelName: to, inputsToSave: ["x", "alpha"], gradFunc: (e, t) => {
let [n, s] = t, r = Gn(n, 0);
return { x: () => vn(r, e, V(e, s)), alpha: () => {
let a = vn(r, je(e), V(e, n)), o = _t(s.shape, e.shape);
return o.length > 0 && (a = ve(a, o)), U(a, s.shape);
} };
} };
function lM(e, t, n) {
let s = e.shape.slice();
s[n] = 1;
let r = U(t, s), a = Cm(e, n, true, false), o = Cm(e, n, true, true), i = V(a, o);
return V(r, i);
}
function cM(e, t, n) {
let s = e.shape.length, r = s - n.length, a = C.getAxesPermutation(n, s), o = e;
a != null && (o = Ge(e, a));
let i = o.shape.slice(), l = i.splice(s - n.length, n.length).reduce((d, h) => d * h, 1);
i.push(l);
let c = o.reshape(i), p = lM(c, t, r);
if (p = p.reshape(o.shape), a != null) {
let d = C.getUndoAxesPermutation(a);
p = Ge(p, d);
}
return p;
}
var dM = { kernelName: no, inputsToSave: ["x"], gradFunc: (e, t, n) => {
let [s] = t, { axis: r } = n, a = [];
return r == null ? a = s.shape.map((o, i) => i) : typeof r == "number" ? a = [r] : a = r, { x: () => cM(s, e, a) };
} };
var pM = { kernelName: Oa, inputsToSave: ["a", "b"], gradFunc: (e, t) => {
let [n, s] = t, r = at(n.shape, s.shape);
return { a: () => {
let i = xe(e, le(s, "float32")), u = _t(n.shape, r);
return u.length > 0 ? U(ve(i, u), n.shape) : i;
}, b: () => {
let i = V(e, le(n, "float32")), u = _t(s.shape, r);
u.length > 0 && (i = U(ve(i, u), s.shape));
let l = ct(s);
return vt(xe(i, le(l, "float32")));
} };
} };
var hM = { kernelName: $l, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => xe(e, vt(ct(n))) };
} };
var fM = { kernelName: ao, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t, s = V(Ji(n, 6), Tp(n));
return { x: () => V(e, le(s, "float32")) };
} };
var mM = { kernelName: so, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => V(e, le(Tp(n), "float32")) };
} };
var gM = { kernelName: Oi, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => U(e, n.shape) };
} };
var bM = { kernelName: ro, inputsToSave: ["images"], gradFunc: (e, t, n) => {
let [s] = t, r = { dy: e, images: s };
return { images: () => z.runKernel(Lg, r, n) };
} };
var yM = { kernelName: _l, inputsToSave: ["images"], gradFunc: (e, t, n) => {
let [s] = t, r = { dy: e, images: s };
return { images: () => z.runKernel(zg, r, n) };
} };
var vM = { kernelName: Pi, gradFunc: (e, t, n) => {
let { dims: s } = n, r = ts(s, e.shape);
return { x: () => Jn(e, r) };
} };
var xM = { kernelName: zi, gradFunc: (e) => ({ x: () => je(e) }) };
var wM = { kernelName: oo, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => vt(xe(e, V(ha(n, 1.5), 2))) };
} };
var kM = { kernelName: Mi, inputsToSave: ["condition"], gradFunc: (e, t) => {
let [n] = t;
return { condition: () => le(je(n), "float32"), t: () => V(e, le(n, e.dtype)), e: () => V(e, le(db(n), e.dtype)) };
} };
var SM = { kernelName: Al, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => {
let s = Gn(n, we(0)), r = we(JS), a = we(eI), o = V(e, a), i = V(V(e, r), Yn(le(n, "float32")));
return vn(s, o, i);
} };
} };
var IM = { kernelName: uo, outputsToSave: [true], gradFunc: (e, t) => {
let [n] = t;
return { x: () => V(e, V(n, ge(we(1), n))) };
} };
var CM = { kernelName: El, gradFunc: (e) => ({ x: () => je(e) }) };
var NM = { kernelName: io, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => V(ab(le(n, "float32")), e) };
} };
var TM = { kernelName: Vi, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => V(vS(le(n, "float32")), e) };
} };
var $M = { kernelName: Bi, inputsToSave: ["x"], gradFunc: (e, t, n) => {
let [s] = t, { begin: r, size: a } = n, o = s.shape, [i, u] = rS(s, r, a), l = [];
for (let c = 0; c < e.rank; c++)
l.push([i[c], o[c] - i[c] - u[c]]);
return { x: () => bo(e, l) };
} };
var _M = { kernelName: po, outputsToSave: [true], gradFunc: (e, t, n) => {
let [s] = t, { dim: r } = n, a = true, o = V(e, s);
return { logits: () => ge(o, V(ve(o, [r], a), s)) };
} };
var AM = { kernelName: Rl, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => V(e, qs(n)) };
} };
var Bx = { kernelName: Wi, gradFunc: (e, t, n) => {
let { blockShape: s, paddings: r } = n;
return { x: () => sb(e, s, r) };
} };
var Vx = { kernelName: Ui, gradFunc: (e, t, n) => {
let { axis: s } = n;
return { x: () => Ft(e, s) };
} };
var EM = { kernelName: lo, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => xe(e, V(dn(le(n, "float32")), 2)) };
} };
var RM = { kernelName: Fl, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => V(e, V(le(n, "float32"), 2)) };
} };
var DM = { kernelName: ho, inputsToSave: ["a", "b"], gradFunc: (e, t) => {
let [n, s] = t, r = we(2);
return { a: () => V(e, V(r, ge(n, s))), b: () => V(e, V(r, ge(s, n))) };
} };
var FM = { kernelName: go, gradFunc: (e) => ({ x: () => je(e) }) };
var OM = { kernelName: fo, inputsToSave: ["a", "b"], gradFunc: (e, t) => {
let [n, s] = t, r = at(n.shape, s.shape);
return { a: () => {
let i = e, u = _t(n.shape, r);
return u.length > 0 && (i = ve(i, u)), U(i, n.shape);
}, b: () => {
let i = e, u = _t(s.shape, r);
return u.length > 0 && (i = ve(i, u)), U(vt(i), s.shape);
} };
} };
var PM = { kernelName: co, inputsToSave: ["x"], gradFunc: (e, t, n) => {
let [s] = t, r = s.shape.slice(), { axis: a } = n;
ts(a, s.shape).forEach((l) => {
r[l] = 1;
});
let i = U(e, r), u = V(i, Ln(s.shape, "float32"));
return { x: () => u };
} };
var zM = { kernelName: Hi, inputsToSave: ["x"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => xe(e, ct(ab(n))) };
} };
var LM = { kernelName: mo, outputsToSave: [true], gradFunc: (e, t) => {
let [n] = t;
return { x: () => V(ge(we(1), ct(n)), e) };
} };
var MM = { kernelName: Tr, inputsToSave: ["x"], gradFunc: (e, t, n) => {
let [s] = t, { reps: r } = n;
return { x: () => {
let o = je(s);
if (s.rank === 1)
for (let i = 0; i < r[0]; ++i)
o = oe(o, qe(e, [i * s.shape[0]], [s.shape[0]]));
else if (s.rank === 2)
for (let i = 0; i < r[0]; ++i)
for (let u = 0; u < r[1]; ++u)
o = oe(o, qe(e, [i * s.shape[0], u * s.shape[1]], [s.shape[0], s.shape[1]]));
else if (s.rank === 3)
for (let i = 0; i < r[0]; ++i)
for (let u = 0; u < r[1]; ++u)
for (let l = 0; l < r[2]; ++l)
o = oe(o, qe(e, [i * s.shape[0], u * s.shape[1], l * s.shape[2]], [s.shape[0], s.shape[1], s.shape[2]]));
else if (s.rank === 4)
for (let i = 0; i < r[0]; ++i)
for (let u = 0; u < r[1]; ++u)
for (let l = 0; l < r[2]; ++l)
for (let c = 0; c < r[3]; ++c)
o = oe(o, qe(e, [i * s.shape[0], u * s.shape[1], l * s.shape[2], c * s.shape[3]], [s.shape[0], s.shape[1], s.shape[2], s.shape[3]]));
else
throw new Error(`Gradient for tile operation is not implemented for rank-${s.rank} tensors yet.`);
return o;
} };
} };
var BM = { kernelName: Hs, gradFunc: (e, t, n) => {
let s = n, { perm: r } = s, a = ib(r);
return { x: () => Ge(e, a) };
} };
var VM = { kernelName: Ki, gradFunc: (e, t, n) => {
let s = n, { axis: r } = s;
return { value: () => es(e, r) };
} };
var WM = { kernelName: gp, inputsToSave: ["segmentIds"], gradFunc: (e, t) => {
let [n] = t;
return { x: () => UM(e, n) };
} };
function UM(e, t) {
let n = Ar(t, je(t)), s = Ju(e, n), r = Zi(t, we(0, "int32")), a = s.rank - r.rank;
for (let i = 0; i < a; ++i)
r = Pn(r, i + 1);
r = Ds(r, Ln(s.shape, "bool"));
let o = je(s);
return vn(r, s, o);
}
var GM = { kernelName: Xi, gradFunc: (e) => ({ x: () => je(e) }) };
var HM = [mI, Wz, Uz, Gz, Hz, qz, jz, Kz, Xz, Yz, Qz, Zz, tL, rL, aL, oL, iL, uL, lL, cL, dL, pL, fL, hL, bL, yL, vL, xL, wL, kL, pM, SL, IL, CL, NL, TL, _L, $L, AL, EL, RL, DL, FL, OL, PL, zL, LL, ML, BL, UL, Lx, Lx, GL, jL, YL, QL, ZL, JL, eM, tM, nM, sM, rM, aM, oM, Mx, Mx, iM, uM, dM, hM, fM, mM, gM, bM, yM, vM, xM, wM, kM, SM, IM, CM, NM, TM, $M, _M, AM, Bx, Bx, Vx, Vx, EM, DM, RM, FM, OM, PM, zM, LM, MM, BM, VM, WM, GM];
for (let e of HM)
Q$(e);
var qM = {};
Ee(qM, { maxNorm: () => jM, minMaxNorm: () => YM, nonNeg: () => XM, unitNorm: () => KM });
function Gb(e, t) {
return q(() => dn(ve(V(e, e), t, true)));
}
var jl = class extends re.Serializable {
getConfig() {
return {};
}
};
var Hb = class extends jl {
constructor(e) {
super(), this.defaultMaxValue = 2, this.defaultAxis = 0, this.maxValue = e.maxValue != null ? e.maxValue : this.defaultMaxValue, this.axis = e.axis != null ? e.axis : this.defaultAxis;
}
apply(e) {
return q(() => {
let t = Gb(e, this.axis), n = Wn(t, 0, this.maxValue);
return V(e, xe(n, oe(Rt(), t)));
});
}
getConfig() {
return { maxValue: this.maxValue, axis: this.axis };
}
};
Hb.className = "MaxNorm";
re.registerClass(Hb);
var qb = class extends jl {
constructor(e) {
super(), this.defaultAxis = 0, this.axis = e.axis != null ? e.axis : this.defaultAxis;
}
apply(e) {
return q(() => xe(e, oe(Rt(), Gb(e, this.axis))));
}
getConfig() {
return { axis: this.axis };
}
};
qb.className = "UnitNorm";
re.registerClass(qb);
var jb = class extends jl {
apply(e) {
return Xs(e);
}
};
jb.className = "NonNeg";
re.registerClass(jb);
var Kb = class extends jl {
constructor(e) {
super(), this.defaultMinValue = 0, this.defaultMaxValue = 1, this.defaultRate = 1, this.defaultAxis = 0, this.minValue = e.minValue != null ? e.minValue : this.defaultMinValue, this.maxValue = e.maxValue != null ? e.maxValue : this.defaultMaxValue, this.rate = e.rate != null ? e.rate : this.defaultRate, this.axis = e.axis != null ? e.axis : this.defaultAxis;
}
apply(e) {
return q(() => {
let t = Gb(e, this.axis), n = oe(V(this.rate, Wn(t, this.minValue, this.maxValue)), V(1 - this.rate, t));
return V(e, xe(n, oe(Rt(), t)));
});
}
getConfig() {
return { minValue: this.minValue, maxValue: this.maxValue, rate: this.rate, axis: this.axis };
}
};
Kb.className = "MinMaxNorm";
re.registerClass(Kb);
var Wx = { maxNorm: "MaxNorm", minMaxNorm: "MinMaxNorm", nonNeg: "NonNeg", unitNorm: "UnitNorm" };
function Ot(e) {
return Db(e);
}
function Ux(e, t = {}) {
return Ul(e, re.SerializationMap.getMap().classNameMap, t, "constraint");
}
function Pt(e) {
if (e == null)
return null;
if (typeof e == "string") {
let n = { className: e in Wx ? Wx[e] : e, config: {} };
return Ux(n);
} else
return e instanceof jl ? e : Ux(e);
}
function jM(e) {
return new Hb(e);
}
function KM(e) {
return new qb(e);
}
function XM() {
return new jb();
}
function YM(e) {
return new Kb(e);
}
var QM = {};
Ee(QM, { constant: () => eB, glorotNormal: () => iB, glorotUniform: () => oB, heNormal: () => uB, heUniform: () => lB, identity: () => rB, leCunNormal: () => cB, leCunUniform: () => dB, ones: () => JM, orthogonal: () => pB, randomNormal: () => nB, randomUniform: () => tB, truncatedNormal: () => sB, varianceScaling: () => aB, zeros: () => ZM });
function ZM() {
return new Pb();
}
function JM() {
return new Pp();
}
function eB(e) {
return new zb(e);
}
function tB(e) {
return new Lb(e);
}
function nB(e) {
return new Mb(e);
}
function sB(e) {
return new Bb(e);
}
function rB(e) {
return new Vb(e);
}
function aB(e) {
return new xn(e);
}
function oB(e) {
return new zp(e);
}
function iB(e) {
return new Lp(e);
}
function uB(e) {
return new Mp(e);
}
function lB(e) {
return new Bp(e);
}
function cB(e) {
return new Vp(e);
}
function dB(e) {
return new Wp(e);
}
function pB(e) {
return new Wb(e);
}
var hB = {};
Ee(hB, { Layer: () => He, RNN: () => Rr, RNNCell: () => Yl, activation: () => LV, add: () => jV, alphaDropout: () => AW, average: () => KV, averagePooling1d: () => sv, averagePooling2d: () => rv, averagePooling3d: () => av, avgPool1d: () => sW, avgPool2d: () => aW, avgPool3d: () => iW, avgPooling1d: () => rW, avgPooling2d: () => oW, avgPooling3d: () => uW, batchNormalization: () => eW, bidirectional: () => kW, concatenate: () => XV, conv1d: () => _V, conv2d: () => AV, conv2dTranspose: () => EV, conv3d: () => RV, conv3dTranspose: () => DV, convLstm2d: () => yW, convLstm2dCell: () => vW, cropping2D: () => OV, dense: () => MV, depthwiseConv2d: () => zV, dot: () => JV, dropout: () => BV, elu: () => SV, embedding: () => qV, flatten: () => WV, gaussianDropout: () => _W, gaussianNoise: () => $W, globalAveragePooling1d: () => lW, globalAveragePooling2d: () => cW, globalMaxPool1d: () => IW, globalMaxPool2d: () => CW, globalMaxPooling1d: () => u0, globalMaxPooling2d: () => l0, gru: () => pW, gruCell: () => hW, input: () => lV, inputLayer: () => kV, layerNormalization: () => tW, leakyReLU: () => CV, lstm: () => fW, lstmCell: () => mW, masking: () => EW, maxPool1d: () => NW, maxPool2d: () => TW, maxPooling1d: () => c0, maxPooling2d: () => d0, maxPooling3d: () => dW, maximum: () => YV, minimum: () => QV, multiply: () => ZV, permute: () => HV, prelu: () => NV, reLU: () => IV, repeatVector: () => UV, reshape: () => GV, rnn: () => xW, separableConv2d: () => FV, simpleRNN: () => gW, simpleRNNCell: () => bW, softmax: () => TV, spatialDropout1d: () => VV, stackedRNNCells: () => wW, thresholdedReLU: () => $V, timeDistributed: () => SW, upSampling2d: () => PV, zeroPadding2d: () => nW });
async function rr(e) {
if (e == null)
return;
let t = [], n = [], s = [];
for (let r in e) {
let a = e[r];
if (typeof a != "number") {
let o = a;
t.push(o.data()), n.push(r), s.push(o);
}
}
if (t.length > 0) {
let r = await Promise.all(t);
for (let a = 0; a < r.length; ++a)
e[n[a]] = r[a][0];
De(s);
}
}
function bI(e) {
if (e != null)
for (let t in e) {
let n = e[t];
typeof n != "number" && n.dispose();
}
}
var fB = 125;
var si = class {
constructor() {
this.validationData = null;
}
setParams(e) {
this.params = e;
}
async onEpochBegin(e, t) {
}
async onEpochEnd(e, t) {
}
async onBatchBegin(e, t) {
}
async onBatchEnd(e, t) {
}
async onTrainBegin(e) {
}
async onTrainEnd(e) {
}
setModel(e) {
}
};
var mB = class {
constructor(e, t = 10) {
e == null && (e = []), this.callbacks = e, this.queueLength = t;
}
append(e) {
this.callbacks.push(e);
}
setParams(e) {
for (let t of this.callbacks)
t.setParams(e);
}
setModel(e) {
for (let t of this.callbacks)
t.setModel(e);
}
async onEpochBegin(e, t) {
t == null && (t = {});
for (let n of this.callbacks)
await n.onEpochBegin(e, t);
}
async onEpochEnd(e, t) {
t == null && (t = {});
for (let n of this.callbacks)
await n.onEpochEnd(e, t);
}
async onBatchBegin(e, t) {
t == null && (t = {});
for (let n of this.callbacks)
await n.onBatchBegin(e, t);
}
async onBatchEnd(e, t) {
t == null && (t = {});
for (let n of this.callbacks)
await n.onBatchEnd(e, t);
}
async onTrainBegin(e) {
e == null && (e = {});
for (let t of this.callbacks)
await t.onTrainBegin(e);
}
async onTrainEnd(e) {
e == null && (e = {});
for (let t of this.callbacks)
await t.onTrainEnd(e);
}
};
var gB = class extends si {
constructor() {
super();
}
async onEpochBegin(e) {
this.seen = 0, this.totals = {};
}
async onBatchEnd(e, t) {
t == null && (t = {});
let n = t.size == null ? 0 : t.size;
this.seen += n;
for (let s in t) {
let r = t[s];
if (typeof r == "number")
this.totals.hasOwnProperty(s) || (this.totals[s] = 0), this.totals[s] = this.totals[s] + r * n;
else {
let a;
s in this.totals ? a = this.totals[s] : this.totals[s] = 0;
let o = q(() => oe(this.totals[s], V(r, n)));
this.totals[s] = o, a != null && a.dispose();
}
}
}
async onEpochEnd(e, t) {
if (t != null)
for (let n of this.params.metrics)
this.totals[n] != null && (typeof this.totals[n] == "number" ? t[n] = this.totals[n] / this.seen : q(() => {
let s = V(xe(1, this.seen), this.totals[n]);
t[n] = s, this.totals[n].dispose(), qt(t[n]);
}));
}
};
var bB = class extends si {
async onTrainBegin(e) {
this.epoch = [], this.history = {};
}
async onEpochEnd(e, t) {
t == null && (t = {}), this.epoch.push(e);
for (let n in t)
this.history[n] == null && (this.history[n] = []), this.history[n].push(t[n]);
}
async syncData() {
let e = [], t = [], n = [];
for (let r in this.history) {
let a = this.history[r];
for (let o = 0; o < a.length; ++o)
if (typeof a[o] != "number") {
let i = a[o];
e.push(i.data()), t.push(r), n.push(o);
}
}
let s = await Promise.all(e);
for (let r = 0; r < s.length; ++r)
this.history[t[r]][n[r]].dispose(), this.history[t[r]][n[r]] = s[r][0];
}
};
var yB = class extends si {
constructor(e, t) {
if (super(), this.currentEpoch = 0, this.nowFunc = e.nowFunc, this.nextFrameFunc = e.nextFrameFunc || ZS, this.yieldEvery = t || "auto", this.yieldEvery === "auto" && (this.yieldEvery = fB), this.yieldEvery === "never" && e.onYield != null)
throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");
w.isNumber(this.yieldEvery) && (this.maybeWait = uz(this.maybeWait.bind(this), this.yieldEvery, this.nowFunc)), this.trainBegin = e.onTrainBegin, this.trainEnd = e.onTrainEnd, this.epochBegin = e.onEpochBegin, this.epochEnd = e.onEpochEnd, this.batchBegin = e.onBatchBegin, this.batchEnd = e.onBatchEnd, this.yield = e.onYield;
}
async maybeWait(e, t, n) {
let s = [];
this.yield != null && (await rr(n), s.push(this.yield(e, t, n))), s.push(this.nextFrameFunc()), await Promise.all(s);
}
async onEpochBegin(e, t) {
this.currentEpoch = e, this.epochBegin != null && (await rr(t), await this.epochBegin(e, t));
}
async onEpochEnd(e, t) {
let n = [];
this.epochEnd != null && (await rr(t), n.push(this.epochEnd(e, t))), this.yieldEvery === "epoch" && n.push(this.nextFrameFunc()), await Promise.all(n);
}
async onBatchBegin(e, t) {
this.batchBegin != null && (await rr(t), await this.batchBegin(e, t));
}
async onBatchEnd(e, t) {
let n = [];
this.batchEnd != null && (await rr(t), n.push(this.batchEnd(e, t))), this.yieldEvery === "batch" ? n.push(this.nextFrameFunc()) : w.isNumber(this.yieldEvery) && n.push(this.maybeWait(this.currentEpoch, e, t)), await Promise.all(n);
}
async onTrainBegin(e) {
this.trainBegin != null && (await rr(e), await this.trainBegin(e));
}
async onTrainEnd(e) {
this.trainEnd != null && (await rr(e), await this.trainEnd(e));
}
};
function yI(e, t) {
return e == null && (e = {}), e instanceof si ? [e] : Array.isArray(e) && e[0] instanceof si ? e : ht(e).map((s) => new yB(s, t));
}
var Ss = class {
constructor() {
}
static registerCallbackConstructor(e, t) {
w.assert(e >= 0 && Number.isInteger(e), () => `Verbosity level is expected to be an integer >= 0, but got ${e}`), Ss.checkForDuplicate(t), Ss.constructors[e] == null && (Ss.constructors[e] = []), Ss.constructors[e].push(t);
}
static checkForDuplicate(e) {
for (let t in Ss.constructors)
Ss.constructors[+t].forEach((s) => {
if (s === e)
throw new G("Duplicate callback constructor.");
});
}
static clear() {
Ss.constructors = {};
}
static createCallbacks(e) {
let t = [];
for (let n in Ss.constructors) {
let s = +n;
e >= s && t.push(...Ss.constructors[s]);
}
return t.map((n) => new n());
}
};
var Xb = Ss;
Xb.constructors = {};
function vI(e, t, n, s, r, a, o, i, u) {
let l = new bB(), c = [new gB(), ...Xb.createCallbacks(t)];
e != null && c.push(...e), c.push(l);
let p = new mB(c);
return p.setParams({ epochs: n, initialEpoch: s, samples: r, steps: a, batchSize: o, verbose: t, doValidation: i, metrics: u }), { callbackList: p, history: l };
}
function gs(e, t = {}, n = false) {
return Ul(e, re.SerializationMap.getMap().classNameMap, t, "layer", n);
}
function Dd(e, t) {
return q(() => {
e.dtype !== "float32" && (e = le(e, "float32"));
let n = ve(Hl(e), t, true), s = Bl(n.shape, Rt()), r = dn(Ar(n, s));
return xe(e, r);
});
}
function vo(e, t) {
return q(() => It(Hl(ge(t, e)), -1));
}
function Gp(e, t) {
return q(() => It(Lt(ge(t, e)), -1));
}
function nu(e, t) {
return q(() => {
let n = ge(e, t), s = Wn(Lt(e), Rt(), Number.MAX_VALUE), r = Lt(xe(n, s));
return V(100, It(r, -1));
});
}
function vB(e, t) {
return q(() => {
let n = Wn(t, Rt(), Number.MAX_VALUE), s = Qn(oe(1, n)), r = Wn(e, Rt(), Number.MAX_VALUE), a = Qn(oe(1, r));
return It(Hl(ge(s, a)), -1);
});
}
function xB(e, t) {
return q(() => {
let n = Ar(0, ge(1, V(e, t)));
return It(Hl(n), -1);
});
}
function wB(e, t) {
return q(() => {
let n = Ar(0, ge(1, V(e, t)));
return It(n, -1);
});
}
function kB(e, t) {
return q(() => {
let n = ve(V(e, t), -1), s = As(V(ge(1, e), t), -1);
return Ar(0, oe(1, ge(s, n)));
});
}
function SB(e, t) {
return q(() => {
let n = Math.log(2), s = ge(t, e), r = ge(oe(s, Vl(V(-2, s))), n);
return It(r, -1);
});
}
function nl(e, t, n = false) {
return q(() => {
if (n)
t = xb(t);
else {
let s = ve(t, t.shape.length - 1, true);
t = xe(t, s);
}
return t = Wn(t, Rt(), 1 - Rt()), vt(ve(V(le(e, "float32"), Qn(t)), t.shape.length - 1));
});
}
function Fd(e, t, n = false) {
return q(() => {
let s = le(Ip(xz(e)), "int32");
t = Wn(t, Rt(), 1 - Rt());
let r = t.shape, a = U(Cd(s, r[r.length - 1]), r);
return nl(a, t, n);
});
}
function IB(e, t) {
if (!w.arraysEqual(e.shape, t.shape))
throw new G(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);
return q(() => {
let n = Xs(t), s = vt(Lt(t));
return oe(ge(n, V(t, e)), cb(Yn(s)));
});
}
function Hp(e, t) {
return q(() => {
let n;
return n = Wn(t, Rt(), 1 - Rt()), n = Qn(xe(n, ge(1, n))), It(IB(e, n), -1);
});
}
function CB(e, t) {
return q(() => {
let n = Wn(e, Rt(), 1), s = Wn(t, Rt(), 1);
return ve(V(e, Qn(xe(n, s))), -1);
});
}
function NB(e, t) {
return q(() => {
let n = Qn(oe(Rt(), t));
return It(ge(t, V(e, n)), -1);
});
}
function Yb(e, t) {
return q(() => {
let n = Dd(e, -1), s = Dd(t, -1), r = V(n, s);
return vt(ve(r, -1));
});
}
var Od = { meanSquaredError: vo, meanAbsoluteError: Gp, meanAbsolutePercentageError: nu, meanSquaredLogarithmicError: vB, squaredHinge: xB, hinge: wB, categoricalHinge: kB, logcosh: SB, categoricalCrossentropy: nl, sparseCategoricalCrossentropy: Fd, binaryCrossentropy: Hp, kullbackLeiblerDivergence: CB, poisson: NB, cosineProximity: Yb };
function em(e) {
if (typeof e == "string") {
if (e in Od)
return Od[e];
let t = `Unknown loss ${e}`;
throw e.toLowerCase().includes("softmaxcrossentropy") && (t = `Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`), new G(t);
} else
return e;
}
function Qb(e, t) {
return q(() => {
let n = V(0.5, Zn(t)), s = Fp(Gn(t, n), e.dtype);
return It(Xn(e, s), -1);
});
}
function Zb(e, t) {
return q(() => Fp(Xn(Yu(e, -1), Yu(t, -1)), "float32"));
}
function xI(e, t) {
return q(() => le(ve(Ds(Xn(e, 1), Xn(t, 1))), "float32"));
}
function TB(e, t) {
return q(() => le(ve(Ds(Xn(e, 1), Xn(t, 0))), "float32"));
}
function $B(e, t) {
return q(() => le(ve(Ds(Xn(e, 0), Xn(t, 1))), "float32"));
}
function wI(e, t) {
return q(() => {
let n = xI(e, t), s = $B(e, t), r = oe(n, s);
return le(vn(Gn(r, 0), xe(n, r), 0), "float32");
});
}
function _B(e, t) {
return q(() => {
let n = xI(e, t), s = TB(e, t), r = oe(n, s);
return le(vn(Gn(r, 0), xe(n, r), 0), "float32");
});
}
function kI(e, t) {
return Hp(e, t);
}
function SI(e, t) {
return e.rank === t.rank && (e = br(e, [e.rank - 1])), t = Yu(t, -1), t.dtype !== e.dtype && (t = le(t, e.dtype)), le(Xn(e, t), "float32");
}
var AB = vo;
var EB = vo;
var RB = Gp;
var DB = Gp;
var FB = nu;
var OB = nu;
var Jb = nl;
var PB = Yb;
var II = Fd;
var Pd = { binaryAccuracy: Qb, categoricalAccuracy: Zb, precision: wI, categoricalCrossentropy: Jb, sparseCategoricalCrossentropy: II, mse: AB, MSE: EB, mae: RB, MAE: DB, mape: FB, MAPE: OB, cosine: PB };
function zB(e) {
if (typeof e == "string" && e in Pd)
return Pd[e];
if (typeof e != "string" && e != null)
return e;
throw new G(`Unknown metric ${e}`);
}
function Qc(e) {
if (Cs(e !== null, `Unknown LossOrMetricFn ${e}`), typeof e == "string")
return e;
{
let t;
for (let n of Object.keys(Od))
if (Od[n] === e) {
t = n;
break;
}
if (t !== void 0)
return t;
for (let n of Object.keys(Pd))
if (Pd[n] === e) {
t = n;
break;
}
return t !== void 0 ? t : e.name;
}
}
function LB(e) {
let t = { Adagrad: () => Mo.adagrad(0.01), Adadelta: () => Mo.adadelta(1, 0.95, Rt()), Adam: () => Mo.adam(1e-3, 0.9, 0.999, Rt()), Adamax: () => Mo.adamax(2e-3, 0.9, 0.999, Rt(), 0), RMSProp: () => Mo.rmsprop(1e-3, 0.9, 0, Rt()), SGD: () => Mo.sgd(0.01) };
if (t.adagrad = t.Adagrad, t.adadelta = t.Adadelta, t.adam = t.Adam, t.adamax = t.Adamax, t.rmsprop = t.RMSProp, t.sgd = t.SGD, e in t)
return t[e]();
throw new G(`Unknown Optimizer ${e}`);
}
var Gx = 1 * 1024 * 1024;
function Hx(e, t, n = false) {
if (e == null || typeof e != "object" || Object.getPrototypeOf(e) !== Object.prototype || !Rm(e))
throw new Error("User-defined metadata is expected to be a JSON object, but is not.");
if (n) {
let s = JSON.stringify(e);
s.length > Gx && console.warn(`User-defined metadata of model "${t}" is too large in size (length=${s.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${Gx}.`);
}
}
function Rm(e) {
if (e === null)
return true;
if (typeof e == "object")
if (Object.getPrototypeOf(e) === Object.prototype) {
let t = Object.keys(e);
for (let n of t)
if (typeof n != "string" || !Rm(e[n]))
return false;
return true;
} else if (Array.isArray(e)) {
for (let t of e)
if (!Rm(t))
return false;
return true;
} else
return false;
else {
let t = typeof e;
return t === "string" || t === "number" || t === "boolean";
}
}
function MB(e, t, n, s = console.log) {
let r = VB(e), a = ["Layer (type)", "Input Shape", "Output shape", "Param #"];
r ? (t = t || 90, n = n || [0.32, 0.61, 0.89, 1]) : (t = t || 115, n = n || [0.24, 0.48, 0.7, 0.8, 1]), n[n.length - 1] <= 1 && (n = n.map((c) => Math.floor(t * c)));
let o;
if (!r) {
a.push("Receives inputs"), o = [];
for (let c in e.nodesByDepth)
o.push(...e.nodesByDepth[c]);
}
s("_".repeat(t)), zd(a, n, s), s("=".repeat(t));
let i = e.layers;
for (let c = 0; c < i.length; ++c)
r ? WB(i[c], n, s) : UB(i[c], n, o, s), s((c === i.length - 1 ? "=" : "_").repeat(t));
e.checkTrainableWeightsConsistency();
let u = BB(e), l = Ad(e.nonTrainableWeights);
s(`Total params: ${u + l}`), s(`Trainable params: ${u}`), s(`Non-trainable params: ${l}`), s("_".repeat(t));
}
function BB(e) {
let t;
return e.collectedTrainableWeights != null ? t = Ad(e.collectedTrainableWeights) : t = Ad(e.trainableWeights), t;
}
function VB(e) {
let t = true, n = [], s = [];
for (let r in e.nodesByDepth)
n.push(e.nodesByDepth[r]);
for (let r of n) {
if (r.length > 1 || r.length === 1 && r[0].inboundLayers.length > 1) {
t = false;
break;
}
s.push(...r);
}
if (t)
for (let r of e.layers) {
let a = false;
for (let o of r.inboundNodes)
if (s.indexOf(o) !== -1)
if (a) {
t = false;
break;
} else
a = true;
if (!t)
break;
}
return t;
}
function zd(e, t, n = console.log) {
let s = "";
for (let r = 0; r < e.length; ++r)
r > 0 && (s = s.slice(0, s.length - 1) + " "), s += e[r], s = s.slice(0, t[r]), s += " ".repeat(t[r] - s.length);
n(s);
}
function WB(e, t, n) {
let s, r;
try {
r = e.inboundNodes.map((u) => JSON.stringify(u.inputShapes)).join(",");
} catch (u) {
r = "multiple";
}
try {
s = JSON.stringify(e.outputShape);
} catch (u) {
s = "multiple";
}
let a = e.name, o = e.getClassName(), i = [`${a} (${o})`, r, s, e.countParams().toString()];
zd(i, t, n);
}
function UB(e, t, n, s) {
let r, a;
try {
a = e.inboundNodes.map((p) => JSON.stringify(p.inputShapes)).join(",");
} catch (p) {
a = "multiple";
}
try {
r = JSON.stringify(e.outputShape);
} catch (p) {
r = "multiple";
}
let o = [];
for (let p of e.inboundNodes)
if (!(n != null && n.length > 0 && n.indexOf(p) === -1))
for (let d = 0; d < p.inboundLayers.length; ++d) {
let h = p.inboundLayers[d].name, f = p.nodeIndices[d], m = p.tensorIndices[d];
o.push(`${h}[${f}][${m}]`);
}
let i = e.name, u = e.getClassName(), l = o.length === 0 ? "" : o[0], c = [`${i} (${u})`, a, r, e.countParams().toString(), l];
zd(c, t, s);
for (let p = 1; p < o.length; ++p)
zd(["", "", "", "", o[p]], t, s);
}
function CI(e, t, n) {
return (e === "inboundNodes" || e === "outputLayers" || e === "inputLayers") && t === 0 && typeof n == "string";
}
function sl(e, t) {
if (e === null)
return null;
if (typeof e == "string")
return Yr(e);
if (typeof e == "number" || typeof e == "boolean")
return e;
if (e instanceof Array) {
let n = [], s = e.length;
for (let r = 0; r < s; ++r) {
let a = e[r];
CI(t, r, a) ? n.push(a) : n.push(sl(a, t));
}
return n;
} else {
let n = {};
for (let s of Object.keys(e)) {
let r = e[s];
if (s === "name" && typeof r == "string")
n[s] = r;
else {
let a = Yr(s);
n[a] = sl(r, a);
}
}
return n;
}
}
function Dm(e, t) {
if (e == null)
return null;
if (typeof e == "string")
return Vs(e);
if (typeof e == "number" || typeof e == "boolean")
return e;
if (e instanceof Array) {
let n = [], s = e.length;
for (let r = 0; r < s; ++r) {
let a = e[r];
CI(t, r, a) ? n.push(a) : n.push(Dm(a, t));
}
return n;
} else {
let n = {};
for (let s of Object.keys(e)) {
let r = e[s], a = Vs(s);
(s === "name" || s === "className") && typeof r == "string" ? n[a] = r : n[a] = Dm(r, s);
}
return n;
}
}
var NI = "0.0.0";
var Is = class extends He {
constructor(e) {
if (super({}), this.containerNodes = /* @__PURE__ */ new Set(), this.name = e.name, this.name == null) {
let b = this.getClassName().toLowerCase();
this.name = Dp(b);
}
if (this.supportsMasking = false, this.trainable_ = true, Array.isArray(e.inputs) ? this.inputs = e.inputs.slice() : this.inputs = [e.inputs], Array.isArray(e.outputs) ? this.outputs = e.outputs.slice() : this.outputs = [e.outputs], cr(this.inputs).length !== this.inputs.length)
throw new G(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map((b) => b.name)}`);
cr(this.outputs).length !== this.outputs.length && console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map((b) => b.name)}`), this.inputLayers = [], this.inputLayersNodeIndices = [], this.inputLayersTensorIndices = [], this.outputLayers = [], this.outputLayersNodeIndices = [], this.outputLayersTensorIndices = [], this.layers = [], this.internalContainerRefs = [];
for (let b of this.outputs) {
let y = b.sourceLayer, v = b.nodeIndex, x = b.tensorIndex;
this.outputLayers.push(y), this.outputLayersNodeIndices.push(v), this.outputLayersTensorIndices.push(x);
}
for (let b of this.inputs) {
let y = b.sourceLayer, v = b.nodeIndex, x = b.tensorIndex;
Cs(v === 0, "input layer has >1 nodes"), Cs(x === 0, "input layer has >1 tensors"), this.inputLayers.push(y), this.inputLayersNodeIndices.push(v), this.inputLayersTensorIndices.push(x);
}
this.inputNames = [], this.outputNames = [], this.feedInputShapes = [], this.feedInputNames = [], this.feedOutputNames = [];
for (let b = 0; b < this.inputLayers.length; b++) {
let y = this.inputLayers[b];
if (!(y instanceof tu))
throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${b} (0-based) originates from layer type ${y.getClassName()}.`);
this.inputNames.push(y.name), this.feedInputShapes.push(y.batchInputShape), this.feedInputNames.push(y.name);
}
for (let b of this.outputLayers)
this.outputNames.push(b.name);
this.internalInputShapes = this.inputs.map((b) => b.shape), this.internalOutputShapes = this.outputs.map((b) => b.shape);
let t = {}, n = {}, s = {}, r = {}, a = {}, o = [], i = (b, y, v, x, k, I) => {
(x == null || k == null || I == null) && (x = b.sourceLayer, k = b.nodeIndex, I = b.tensorIndex);
let $ = x.inboundNodes[k];
if (v.indexOf($) !== -1)
throw new fs(`The tensor ${b.name} at layer "${x.name}" is part of a cycle.`);
if (y.indexOf($) !== -1)
return;
this.containerNodes.add(Is.nodeKey(x, k)), x.id in a || (a[x.id] = Object.keys(a).length), v.indexOf($) === -1 && v.push($);
let R = $.inboundLayers.length;
for (let E = 0; E < R; E++) {
let P = $.inputTensors[E], A = $.inboundLayers[E], D = $.nodeIndices[E], T = $.tensorIndices[E];
i(P, y, v, A, D, T);
}
for (y.push($); v.indexOf($) >= 0; )
v.splice(v.indexOf($), 1);
o.push($);
}, u = [], l = [];
for (let b of this.outputs)
i(b, u, l);
let c = o.slice().reverse();
for (let b of c) {
n[b.id] = b, b.id in t || (t[b.id] = 0);
let y = t[b.id], v = s[b.outboundLayer.id] == null ? 0 : s[b.outboundLayer.id];
y = Math.max(y, v), s[b.outboundLayer.id] = y, r[b.outboundLayer.id] = b.outboundLayer, t[b.id] = y;
for (let x = 0; x < b.inboundLayers.length; x++) {
let k = b.inboundLayers[x], I = b.nodeIndices[x], $ = k.inboundNodes[I], R = t[$.id] == null ? 0 : t[$.id];
t[$.id] = Math.max(y + 1, R), n[$.id] = $;
}
}
let p = {};
for (let b in t) {
let y = t[b];
y in p || (p[y] = []), p[y].push(n[b]);
}
let d = {};
for (let b in s) {
let y = s[b];
y in d || (d[y] = []), d[y].push(r[b]);
}
let h = Object.keys(d).map((b) => parseInt(b, 10)).sort(Kc);
this.layers = [];
for (let b of h) {
let y = d[b];
y.sort((v, x) => {
let k = a[v.id], I = a[x.id];
return k < I ? -1 : k > I ? 1 : 0;
});
for (let v of y)
v instanceof Is && this.internalContainerRefs.push(v), this.layers.push(v);
}
this.layersByDepth = d, h = Object.keys(p).map((b) => parseInt(b, 10)).sort(Kc);
let f = this.inputs.slice(), m = [];
for (let b of h)
for (let y of p[b]) {
let v = y.outboundLayer;
if (v != null) {
for (let x of y.inputTensors)
if (f.indexOf(x) === -1)
throw new fs(`Graph disconnected: cannot obtain value for tensor ${x} at layer "${v.name}". The following previous layers were accessed without issue: ${m}`);
for (let x of y.outputTensors)
f.push(x);
m.push(v.name);
}
}
this.nodesByDepth = p;
let g = this.layers.map((b) => b.name);
for (let b of g) {
let y = g.filter((v) => v === b).length;
if (y !== 1)
throw new fs(`The name "${b}" is used ${y} times in the model. All layer names should be unique. Layer names: ` + JSON.stringify(g));
}
this.outboundNodes = [], this.inboundNodes = [], new Up({ outboundLayer: this, inboundLayers: [], nodeIndices: [], tensorIndices: [], inputTensors: this.inputs, outputTensors: this.outputs, inputMasks: this.inputs.map((b) => null), outputMasks: this.outputs.map((b) => null), inputShapes: this.inputs.map((b) => b.shape), outputShapes: this.outputs.map((b) => b.shape) }), this.built = true, this._refCount = 1;
}
assertNotDisposed() {
if (this._refCount === 0)
throw new Error(`Container '${this.name}' is already disposed.`);
}
dispose() {
this.assertNotDisposed();
let e = { refCountAfterDispose: null, numDisposedVariables: 0 };
if (--this._refCount === 0) {
for (let t of this.layers)
e.numDisposedVariables += t.dispose().numDisposedVariables;
for (let t of this.internalContainerRefs)
e.numDisposedVariables += t.dispose().numDisposedVariables;
}
return e.refCountAfterDispose = this._refCount, e;
}
get trainable() {
return this.trainable_;
}
set trainable(e) {
this.layers.forEach((t) => {
t._trainableWeights.forEach((n) => n.trainable = e);
}), this.trainable_ = e;
}
get trainableWeights() {
if (this._trainableWeights.length > 0)
throw new G("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");
if (!this.trainable)
return [];
let e = [];
for (let t of this.layers)
e = e.concat(t.trainableWeights);
return e;
}
get nonTrainableWeights() {
let e = [];
for (let t of this.layers)
e.push(...t.nonTrainableWeights);
if (!this.trainable) {
let t = [];
for (let n of this.layers)
t.push(...n.trainableWeights);
return t.concat(e);
}
return e;
}
get weights() {
return this.trainableWeights.concat(this.nonTrainableWeights);
}
loadWeights(e, t = true) {
let n = {}, s = 0;
for (let a of this.layers)
for (let o of a.weights) {
if (n[o.originalName] != null)
throw new G(`Duplicate weight name: ${o.originalName}`);
n[o.originalName] = o, s++;
}
let r = [];
for (let a in e) {
let o = a;
if (n[a] == null) {
let i = a.split("/");
o = i.slice(0, -2).concat([i[i.length - 1]]).join("/");
}
if (n[o] != null)
r.push([n[o], e[a]]);
else if (t)
throw new G(`Provided weight data has no target variable: ${a}`);
delete n[o];
}
if (t) {
let a = [];
for (let o in n)
a.push(o);
if (a.length > 0)
throw new G(`${a.length} of ${s} weights are not set: ${a}`);
}
Ub(r);
}
updatedConfig() {
let e = this.getConfig(), t = {};
return t.className = this.getClassName(), t.config = e, t.kerasVersion = `tfjs-layers ${NI}`, t.backend = "TensorFlow.js", t;
}
toJSON(e, t = true) {
let n = Dm(this.updatedConfig());
return t ? JSON.stringify(n) : n;
}
call(e, t) {
return q(() => {
e = ht(e);
let n = new Jr();
for (let s = 0; s < this.inputs.length; ++s)
n.add(this.inputs[s], e[s]);
return Fu(this.outputs, n, t);
});
}
computeMask(e, t) {
return q(() => {
e = ht(e);
let n;
return t == null ? n = ma(null, e.length) : n = ht(t), this.runInternalGraph(e, n)[1];
});
}
computeOutputShape(e) {
let t = _d(e);
if (t.length !== this.inputLayers.length)
throw new G(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);
let n = {};
for (let o = 0; o < t.length; o++) {
let i = this.inputLayers[o], u = t[o], l = i.name + "_0_0";
n[l] = u;
}
let s = Object.keys(this.nodesByDepth).map((o) => parseInt(o, 10)).sort(Kc);
if (s.length > 1)
for (let o of s) {
let i = this.nodesByDepth[o];
for (let u of i) {
let l = u.outboundLayer;
if (this.inputLayers.map((f) => f.id).indexOf(l.id) !== -1)
continue;
let c = [];
for (let f = 0; f < u.inboundLayers.length; f++) {
let m = u.inboundLayers[f], g = u.nodeIndices[f], b = u.tensorIndices[f], y = `${m.name}_${g}_${b}`, v = n[y];
c.push(v);
}
let p = l.computeOutputShape(bn(c)), d = _d(p), h = l.inboundNodes.indexOf(u);
for (let f = 0; f < d.length; f++) {
let m = `${l.name}_${h}_${f}`;
n[m] = d[f];
}
}
}
let r = [], a = [];
for (let o = 0; o < this.outputLayers.length; o++) {
let i = this.outputLayers[o], u = this.outputLayersNodeIndices[o], l = this.outputLayersTensorIndices[o], c = `${i.name}_${u}_${l}`;
a.push(c);
}
for (let o = 0; o < a.length; o++) {
let i = a[o];
Cs(i in n), r.push(n[i]);
}
return bn(r);
}
runInternalGraph(e, t) {
t == null && (t = ma(null, e.length));
let n = {};
for (let i = 0; i < this.inputs.length; ++i) {
let u = this.inputs[i], l = e[i], c = t[i];
n[u.id] = [l, c];
}
let s = Object.keys(this.nodesByDepth).map((i) => parseInt(i, 10)).sort(Kc);
for (let i of s) {
let u = this.nodesByDepth[i];
for (let l of u) {
let c = l.outboundLayer, p = l.inputTensors, d = l.outputTensors, h = new Array();
for (let f of p)
f.id in n && h.push(n[f.id]);
if (h.length === p.length) {
let f = {}, m, g, b, y;
if (l.callArgs != null && (f = l.callArgs), h.length === 1) {
let [v, x] = h[0];
f.mask == null && (f.mask = x), b = ht(c.call(v, f)), y = ht(c.computeMask(v, x)), m = [v], g = [x];
} else
m = h.map((v) => v[0]), g = h.map((v) => v[1]), f.mask == null && (f.mask = g), b = ht(c.call(m, f)), y = ht(c.computeMask(m, g));
if (c.activityRegularizer)
throw new Fe("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");
for (let v = 0; v < d.length; ++v) {
let x = d[v], k = b[v], I = y[v];
n[x.id] = [k, I];
}
}
}
}
let r = [], a = [], o = [];
for (let i of this.outputs) {
Cs(i.id in n, `Could not compute output ${i.name} : ${i.id}`);
let [u, l] = n[i.id];
o.push(u.shape), r.push(u), a.push(l);
}
return [r, a, o];
}
buildNodeConversionMap(e) {
let t = {}, n;
for (let s of this.layers) {
n = s instanceof Is ? 1 : 0;
for (let r = 0; r < s.inboundNodes.length; r++) {
let a = Is.nodeKey(s, r);
this.containerNodes.has(a) && (t[a] = n, n += 1);
}
}
return t;
}
getLayer(e, t) {
if (t != null) {
if (this.layers.length <= t)
throw new G(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);
return this.layers[t];
} else if (e == null)
throw new G("Provide either a layer name or layer index");
for (let n of this.layers)
if (n.name === e)
return n;
throw new G(`No such layer: ${e}`);
}
calculateLosses() {
return q(() => {
let e = [];
for (let t of this.layers)
for (let n = 0; n < t.inboundNodes.length; ++n) {
let s = Is.nodeKey(t, n);
this.containerNodes.has(s) && e.push(...t.calculateLosses());
}
return e;
});
}
getConfig() {
let e = { name: this.name }, t = this.buildNodeConversionMap(this.layers), n = [];
for (let a of this.layers) {
let o = a.getClassName(), i = a.getConfig(), u = [];
for (let c = 0; c < a.inboundNodes.length; c++) {
let p = a.inboundNodes[c], d = Is.nodeKey(a, c), h = {};
if (this.containerNodes.has(d)) {
if (p.callArgs)
try {
JSON.stringify(p.callArgs), h = p.callArgs;
} catch (f) {
console.warn(`Layer ${a.name} was passed non-serializable keyword arguments: ${p.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`), h = {};
}
if (p.inboundLayers.length > 0) {
let f = [];
for (let m = 0; m < p.inboundLayers.length; m++) {
let g = p.inboundLayers[m], b = p.nodeIndices[m], y = p.tensorIndices[m], v = Is.nodeKey(g, b), x = t[v];
x == null && (x = 0), f.push([g.name, x, y, h]);
}
u.push(f);
}
}
}
let l = {};
l.name = a.name, l.className = o, l.config = i, l.inboundNodes = u, n.push(l);
}
e.layers = n;
let s = [];
for (let a = 0; a < this.inputLayers.length; a++) {
let o = this.inputLayers[a], i = this.inputLayersNodeIndices[a], u = Is.nodeKey(o, i);
if (!this.containerNodes.has(u))
continue;
let l = t[u];
l == null && (l = 0);
let c = this.inputLayersTensorIndices[a];
s.push([o.name, l, c]);
}
e.inputLayers = s;
let r = [];
for (let a = 0; a < this.outputLayers.length; a++) {
let o = this.outputLayers[a], i = this.outputLayersNodeIndices[a], u = Is.nodeKey(o, i);
if (!this.containerNodes.has(u))
continue;
let l = t[u];
l == null && (l = 0);
let c = this.outputLayersTensorIndices[a];
r.push([o.name, l, c]);
}
return e.outputLayers = r, e;
}
static fromConfig(e, t, n = {}, s = false) {
let r = {}, a = {};
function o(m, g) {
m.name in a ? a[m.name].push(g) : a[m.name] = [g];
}
function i(m, g) {
let b = [], y;
for (let v of g) {
let x = v[0], k = v[1], I = v[2];
if (y = v[3] == null ? {} : v[3], !(x in r)) {
o(m, g);
return;
}
let $ = r[x];
if ($.inboundNodes.length <= k) {
o(m, g);
return;
}
let R = $.inboundNodes[k];
b.push(R.outputTensors[I]);
}
b.length > 0 && m.apply(bn(b), y);
}
function u(m) {
let g = m.name, b = gs(m, t.customObjects != null ? t.customObjects : {});
b.setFastWeightInitDuringBuild(s), r[g] = b, m.inboundNodes.forEach((v) => {
if (!(v instanceof Array))
throw new G(`Corrupted configuration, expected array for nodeData: ${v}`);
o(b, v);
});
}
let l = t.name, c = t.layers;
for (let m of c)
u(m);
for (; !iz(a); )
for (let m of c) {
let g = r[m.name];
if (g.name in a) {
let b = a[g.name];
delete a[g.name];
for (let y of b)
i(g, y);
}
}
let p = [], d = [], h = t.inputLayers;
for (let m of h) {
let g = m[0], b = m[1], y = m[2];
Cs(g in r);
let x = r[g].inboundNodes[b].outputTensors;
p.push(x[y]);
}
let f = t.outputLayers;
for (let m of f) {
let g = m[0], b = m[1], y = m[2];
Cs(g in r);
let x = r[g].inboundNodes[b].outputTensors;
d.push(x[y]);
}
return new e({ inputs: p, outputs: d, name: l });
}
get stateful() {
if (this._stateful)
throw new G("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");
for (let e of this.layers)
if (e.stateful)
return true;
return false;
}
resetStates() {
q(() => {
this.layers.forEach((e) => {
e.stateful && e.resetStates();
});
});
}
};
function GB(e, t, n) {
let s = t.length;
if (e == null || Array.isArray(e) && e.length === 0)
return t.map((r) => null);
if (s === 1)
return Array.isArray(e) && e.length === 1 ? e : typeof e == "object" && t[0] in e ? [e[t[0]]] : [e];
if (Array.isArray(e)) {
if (e.length !== s)
throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);
return e;
} else if (typeof e == "object" && Object.keys(e).length > 0 && typeof e[Object.keys(e)[0]] == "object") {
let r = [];
return t.forEach((a) => {
a in e ? r.push(e[a]) : r.push(null);
}), r;
} else
throw new Error(`The model has multiple (${s}) outputs, so ${n} must be either an array with ${s} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`);
}
function TI(e, t) {
return GB(e, t, "classWeight");
}
async function $I(e, t, n, s) {
if (t != null || s != null)
throw new Error("Support sampleWeight is not implemented yet");
if (n != null) {
let r = q(() => {
if (e.shape.length === 1)
return lr(e);
if (e.shape.length === 2) {
if (e.shape[1] > 1)
return Yu(e, 1);
if (e.shape[1] === 1)
return U(e, [e.shape[0]]);
throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`);
} else
throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`);
}), a = Array.from(await r.data());
De(r);
let o = [];
return a.forEach((i) => {
if (n[i] == null)
throw new Error(`classWeight must contain all classes in the training data. The class ${i} exists in the data but not in classWeight`);
o.push(n[i]);
}), Zt(o, "float32");
} else
return null;
}
function HB(e, t) {
return V(e, t);
}
var qB = 32;
function _I(e, t) {
let n, s, r = t;
n = r.xs, s = r.ys, w.assert(n != null && s != null, () => `A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`);
let a = qx("input", e.inputNames, n), o = qx("output", e.outputNames, s), i = a[0].shape[0];
w.assert(a.length === e.inputs.length, () => `LayersModel has ${e.inputs.length} inputs, but the dataset provides ${a.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`), w.assert(o.length === e.outputs.length, () => `LayersModel has ${e.outputs.length} outputs, but the dataset provides ${o.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);
for (let u = 0; u < a.length; u++)
w.assert(a[u].shape[0] === i, () => `Batch size mismatch: input ${e.inputNames[u]} has ${a[u].shape[0]}; expected ${i} based on input ${e.inputNames[0]}.`);
for (let u = 0; u < o.length; u++)
w.assert(o[u].shape[0] === i, () => `Batch size mismatch: output ${e.outputNames[u]} has ${o[u].shape[0]}; expected ${i} based on input ${e.inputNames[0]}.`);
return { xs: a, ys: o };
}
function qx(e, t, n) {
if (n instanceof et)
return [n];
if (Array.isArray(n))
return w.assert(n.length === t.length, () => `Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`), n;
{
let s = [];
for (let r of t) {
if (n[r] == null)
throw new G(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);
s.push(n[r]);
}
return s;
}
}
function jB(e) {
if (e.length === 3)
throw new Fe("Validation with sample weights is not implemented yet.");
return { xs: e[0], ys: e[1] };
}
async function KB(e, t, n) {
let s = n.batchesPerEpoch != null;
if (w.assert(e.optimizer != null, () => "You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."), w.assert(n != null, () => "For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."), w.assert(n.epochs != null && n.epochs > 0 && Number.isInteger(n.epochs), () => `For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`), w.assert(!s || n.batchesPerEpoch > 0 && Number.isInteger(n.batchesPerEpoch), () => `For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`), w.assert(n.validationSplit == null, () => "`validationSplit` is not supported by `fitDataset()`. Use validationData instead."), e.isTraining)
throw new Error("Cannot start training because another fit() call is ongoing.");
e.isTraining = true;
try {
let r = n.validationData != null, a, o;
if (r)
if (jx(n.validationData))
w.assert(n.validationBatches == null || n.validationBatches > 0 && Number.isInteger(n.validationBatches), () => `For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`);
else {
let g = jB(n.validationData);
a = g.xs, o = g.ys;
}
let i = e.makeTrainFunction(), u = e.getDedupedMetricsNames(), l;
r ? l = u.slice().concat(u.map((g) => "val_" + g)) : l = u.slice();
let c = yI(n.callbacks, n.yieldEvery), p = n.verbose == null ? 1 : n.verbose, { callbackList: d, history: h } = vI(c, p, n.epochs, null, null, XB(t, n), null, r, l);
d.setModel(e), e.history = h, await d.onTrainBegin(), e.stopTraining_ = false;
let f = n.initialEpoch == null ? 0 : n.initialEpoch, m = await t.iterator();
for (; f < n.epochs; ) {
let g = {};
await d.onEpochBegin(f);
let b = 0, y = 0;
for (s || (m = await t.iterator()); !s || b < n.batchesPerEpoch; ) {
let v = await m.next();
if (s && v.done) {
console.warn(`You provided \`batchesPerEpoch\` as ${n.batchesPerEpoch}, but your dataset iterator ran out of data after ${b} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${n.batchesPerEpoch * n.epochs} batches). You may need to use the repeat() function when building your dataset.`);
break;
}
if (v.value != null) {
let { xs: x, ys: k } = _I(e, v.value), I = {};
I.batch = y, I.size = x[0].shape[0], await d.onBatchBegin(y, I);
let $ = [];
if (n.classWeight != null) {
let P = TI(n.classWeight, e.outputNames);
for (let A = 0; A < P.length; ++A)
$.push(await $I(k[A], null, P[A]));
}
let R = x.concat(k).concat($), E = i(R);
De(R);
for (let P = 0; P < u.length; ++P) {
let A = u[P], D = E[P];
I[A] = D, qt(D);
}
await d.onBatchEnd(y, I), bI(I), y++, b++;
}
if (s ? b >= n.batchesPerEpoch : v.done) {
if (r) {
let x;
jx(n.validationData) ? x = ht(await e.evaluateDataset(n.validationData, { batches: n.validationBatches })) : x = ht(e.evaluate(a, o, { batchSize: n.validationBatchSize == null ? qB : n.validationBatchSize, verbose: 0 }));
for (let k = 0; k < e.metricsNames.length; ++k)
g[`val_${e.metricsNames[k]}`] = x[k];
}
break;
}
if (e.stopTraining_)
break;
}
if (await d.onEpochEnd(f, g), f++, e.stopTraining_)
break;
}
return await d.onTrainEnd(), await e.history.syncData(), e.history;
} finally {
e.isTraining = false;
}
}
function XB(e, t) {
let n = null;
return t.batchesPerEpoch != null ? n = t.batchesPerEpoch : Number.isFinite(e.size) && (n = e.size), n;
}
function jx(e) {
return typeof e.iterator == "function";
}
function YB(e) {
return typeof e.next == "function";
}
async function QB(e, t, n) {
n = n || {};
let s = n.batches != null, r = e.testFunction, a = [];
if (n.verbose > 0)
throw new Fe("Verbose mode is not implemented yet.");
w.assert(!s || n.batches > 0 && Number.isInteger(n.batches), () => `Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`);
let o = YB(t) ? t : await t.iterator(), i = 0, u = 0;
for (; !s || u < n.batches; ) {
let l = await o.next();
if (a = q(() => {
if (l.value) {
let { xs: c, ys: p } = _I(e, l.value), d = c.concat(p), h = q(() => r(d));
if (De(d), u === 0)
for (let m = 0; m < h.length; ++m)
a.push(we(0));
let f = d[0].shape[0];
for (let m = 0; m < h.length; ++m) {
let g = h[m], b = a[m];
a[m] = q(() => oe(a[m], V(f, g))), u > 0 && De(b);
}
De(h), i += f, ++u;
}
return a;
}), l.done) {
s && console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);
break;
}
}
for (let l = 0; l < a.length; ++l) {
let c = a[l];
a[l] = xe(a[l], i), De(c);
}
return bn(a);
}
function Fm(e) {
w.assert(e > 0 && Number.isInteger(e), () => `batchSize is required to be a positive integer, but got ${e}`);
}
function Ou(e, t, n) {
return e == null ? [null] : Array.isArray(e) ? e.map((s) => sa(s, t, n - t)) : sa(e, t, n - t);
}
function ey(e, t) {
return q(() => e == null ? null : Array.isArray(e) ? e.map((n) => ey(n, t)) : dI(e, t.dtype === "int32" ? t : le(t, "int32")));
}
function Om(e, t) {
let n = [], s = 0, r = null;
for (; s < e; )
r = s + t, r >= e && (r = e), n.push([s, r]), s = r;
return n;
}
async function ZB(e, t, n, s, r, a, o, i, u, l, c, p, d, h, f) {
r == null && (r = 32), a == null && (a = 1), c == null && (c = true), d == null && (d = 0);
let m = false;
if (u != null && l != null && (m = true), f != null && (m = true, h == null))
throw new G("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");
let g = e.checkNumSamples(n, r, h, "steps_per_epoch"), b;
g != null && (b = ys(0, g)), o == null && (o = 1);
let { callbackList: y, history: v } = vI(i, o, a, d, g, h, r, m, p);
y.setModel(e), e.history = v, await y.onTrainBegin(), e.stopTraining_ = false;
for (let x = d; x < a; ++x) {
await y.onEpochBegin(x);
let k = {};
if (h != null)
throw new Fe("stepsPerEpoch mode is not implemented yet.");
{
if (c === "batch")
throw new Fe("batch shuffling is not implemneted yet");
c && w.shuffle(b);
let I = Zt(b), $ = Om(g, r);
for (let R = 0; R < $.length; ++R) {
let E = {};
if (await y.onBatchBegin(R, E), q(() => {
let P = $[R][0], A = $[R][1], D = sa(I, P, A - P);
E.batch = R, E.size = A - P;
let T = ey(n, D), L = t(T);
for (let W = 0; W < s.length; ++W) {
let j = s[W], Y = L[W];
E[j] = Y, qt(Y);
}
if (R === $.length - 1 && m) {
let W = e.testLoop(u, l, r);
for (let j = 0; j < s.length; ++j) {
let Y = s[j], X = W[j];
qt(X), k["val_" + Y] = X;
}
}
}), await y.onBatchEnd(R, E), bI(E), e.stopTraining_)
break;
}
I.dispose();
}
if (await y.onEpochEnd(x, k), e.stopTraining_)
break;
}
return await y.onTrainEnd(), await e.history.syncData(), e.history;
}
async function JB(e, t, n, s = {}) {
if (e.isTraining)
throw new Error("Cannot start training because another fit() call is ongoing.");
e.isTraining = true;
let r, a, o, i, u, l, c, p, d;
try {
let h = s.batchSize == null ? 32 : s.batchSize;
Fm(h);
let f = false, m = await e.standardizeUserData(t, n, s.sampleWeight, s.classWeight, f, h);
r = m[0], a = m[1], d = m[2];
let g = false, b;
if (s.validationData != null && s.validationData.length > 0) {
if (g = true, s.validationData.length === 2)
u = s.validationData[0], l = s.validationData[1];
else
throw s.validationData.length === 3 ? new Fe("validationData including sample weights is not supported yet.") : new G(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);
let E = true, P = await e.standardizeUserData(u, l, null, null, E, h);
c = P[0], p = P[1], b = c.concat(p);
} else if (s.validationSplit != null && s.validationSplit > 0 && s.validationSplit < 1) {
g = true;
let E = Math.floor(r[0].shape[0] * (1 - s.validationSplit)), P = r[0].shape[0];
c = Ou(r, E, P), o = r, r = Ou(r, 0, E), p = Ou(a, E, P), i = a, a = Ou(a, 0, E), b = c.concat(p);
} else
s.validationSteps != null && (g = true);
let y = r.concat(a).concat(d);
e.checkTrainableWeightsConsistency();
let v = e.makeTrainFunction(), x = e.getDedupedMetricsNames(), k, I;
g ? (e.makeTestFunction(), k = e.testFunction, I = x.slice().concat(x.map((E) => "val_" + E))) : (k = null, b = [], I = x.slice());
let $ = yI(s.callbacks, s.yieldEvery);
return await ZB(e, v, y, x, h, s.epochs, s.verbose, $, k, b, s.shuffle, I, s.initialEpoch, null, null);
} finally {
e.isTraining = false, ps(r, t), ps(a, n), ps(o, t), ps(i, n), ps(c, u), ps(p, l), d != null && De(d);
}
}
function AI(e) {
let t = [];
e instanceof et && (e = [e]);
for (let n = 0; n < e.length; ++n) {
let s = e[n];
if (s.rank === 1)
t.push(Gl(s, 1));
else {
if (s.rank === 0)
throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");
t.push(s);
}
}
return t;
}
function ps(e, t) {
if (e == null)
return;
let n = [];
if (t instanceof et)
n.push(t.id);
else if (Array.isArray(t))
t.forEach((r) => n.push(r.id));
else if (t != null)
for (let r in t) {
let a = t[r];
n.push(a.id);
}
let s = [];
if (e instanceof et)
n.indexOf(e.id) === -1 && s.push(e);
else if (Array.isArray(e))
e.forEach((r) => {
n.indexOf(r.id) === -1 && s.push(r);
});
else if (e != null)
for (let r in e) {
let a = e[r];
n.indexOf(a.id) === -1 && s.push(a);
}
s.forEach((r) => {
r.isDisposed || r.dispose();
});
}
function eV(e) {
return e instanceof et;
}
function Pm(e) {
return Array.isArray(e);
}
function Kx(e) {
return !eV(e) && !Pm(e);
}
function Xx(e, t, n, s = true, r = "") {
if (t == null || t.length === 0) {
if (e != null) {
let o = false;
if (Pm(e) && e.length > 0)
o = true;
else if (Kx(e)) {
for (let i in e)
if (e.hasOwnProperty(i)) {
o = true;
break;
}
} else
o = true;
if (o)
throw new G(`Error when checking model ${r} expected no data, but got ${e}`);
}
return [];
}
if (e == null)
return t.map((o) => null);
let a;
if (Kx(e)) {
e = e, a = [];
for (let o of t) {
if (e[o] == null)
throw new G(`No data provided for "${o}". Need data for each key in: ${t}`);
a.push(e[o]);
}
} else if (Pm(e)) {
if (e = e, e.length !== t.length)
throw new G(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);
a = e;
} else {
if (e = e, t.length > 1)
throw new G(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);
a = [e];
}
if (a = AI(a), n != null)
for (let o = 0; o < t.length; ++o) {
if (n[o] == null)
continue;
let i = a[o];
if (i.shape.length !== n[o].length)
throw new G(`Error when checking ${r}: expected ${t[o]} to have ${n[o].length} dimension(s). but got array with shape ${i.shape}`);
for (let u = 0; u < n[o].length; ++u) {
if (u === 0 && !s)
continue;
let l = i.shape[u], c = n[o][u];
if (c != null && c >= 0 && l !== c)
throw new G(`${r} expected a batch of elements where each example has shape [${n[o].slice(1, n[o].length)}] (i.e.,tensor shape [*,${n[o].slice(1, n[o].length)}]) but the ${r} received an input with ${i.shape[0]} examples, each with shape [${i.shape.slice(1, i.shape.length)}] (tensor shape [${i.shape}])`);
}
}
return a;
}
function tV(e, t, n) {
let s = cr(e.map((a) => a.shape[0]));
s.sort();
let r = cr(t.map((a) => a.shape[0]));
if (r.sort(), s.length > 1)
throw new G(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map((a) => a.shape))}`);
if (r.length > 1)
throw new G(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map((a) => a.shape))}`);
if (s.length > 0 && r.length > 0 && !w.arraysEqual(s, r))
throw new G(`Input Tensors should have the same number of samples as target Tensors. Found ${s[0]} input sample(s) and ${r[0]} target sample(s).`);
}
function nV(e, t, n) {
let s = [vo, Hp, nl];
for (let r = 0; r < e.length; ++r) {
let a = e[r], o = t[r], i = n[r];
if (o != null) {
if (o === nl && a.shape[a.shape.length - 1] === 1)
throw new G(`You are passing a target array of shape ${a.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);
if (s.indexOf(o) !== -1) {
let u = a.shape.slice(1), l = i.slice(1);
for (let c = 0; c < u.length; ++c) {
let p = u[c], d = l[c];
if (d != null && p !== d)
throw new G(`A target Tensor with shape ${a.shape} was passed for an output of shape ${i}, while using a loss function that expects targets to have the same shape as the output.`);
}
}
}
}
}
function Yx(e, t, n, s = true, r = "") {
let a;
if (Array.isArray(e)) {
if (e.length !== t.length)
throw new G(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);
a = e;
} else {
if (t.length > 1)
throw new G(`The model expects ${t.length} ${r} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);
a = [e];
}
if (n != null)
for (let o = 0; o < t.length; ++o) {
if (n[o] == null)
continue;
let i = a[o];
if (i.shape.length !== n[o].length)
throw new G(`Error when checking ${r}: expected ${t[o]} to have ${n[o].length} dimension(s), but got array with shape ${JSON.stringify(i.shape)}`);
for (let u = 0; u < n[o].length; ++u) {
if (u === 0 && !s)
continue;
let l = i.shape[u], c = n[o][u];
if (c != null && c !== l)
throw new G(`Error when checking ${r}: expected ${t[o]} to have shape ${JSON.stringify(n[o])} but got array with shape ${JSON.stringify(i.shape)}.`);
}
}
}
function sV(e, t) {
if (e == null || Array.isArray(e) && e.length === 0)
return t.map((s) => []);
let n;
if (typeof e == "string" || typeof e == "function")
n = [e];
else if (Array.isArray(e) || typeof e == "object")
n = e;
else
throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);
if (Array.isArray(n))
return t.map((s) => n);
{
let s = [];
for (let r of t) {
let a = n.hasOwnProperty(r) ? n[r] : [];
Array.isArray(a) || (a = [a]), s.push(a);
}
return s;
}
}
var rV = "layers-model";
var pr = class extends Is {
constructor(e) {
super(e), this.isTraining = false;
}
summary(e, t, n = console.log) {
if (!this.built)
throw new G("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");
MB(this, e, t, n);
}
compile(e) {
if (e.loss == null && (e.loss = []), this.loss = e.loss, typeof e.optimizer == "string")
this.optimizer_ = LB(e.optimizer), this.isOptimizerOwned = true;
else {
if (!(e.optimizer instanceof Er))
throw new G("User-defined optimizer must be an instance of tf.Optimizer.");
this.optimizer_ = e.optimizer, this.isOptimizerOwned = false;
}
let t = [];
if (!Array.isArray(e.loss) && typeof e.loss != "string" && typeof e.loss != "function") {
e.loss = e.loss;
for (let a in e.loss)
if (this.outputNames.indexOf(a) === -1)
throw new G(`Unknown entry in loss dictionary: "${a}". Only expected the following keys: ${this.outputNames}`);
for (let a of this.outputNames)
e.loss[a] == null && console.warn(`Output "${a}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${a} during training`), t.push(em(e.loss[a]));
} else if (Array.isArray(e.loss)) {
if (e.loss.length !== this.outputs.length)
throw new G(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);
t = e.loss.map((o) => em(o));
} else {
let a = em(e.loss);
this.outputs.forEach((o) => {
t.push(a);
});
}
this.lossFunctions = t, this.feedOutputNames = [], this.feedOutputShapes = [], this.feedLossFns = [];
for (let a = 0; a < this.outputs.length; ++a) {
let o = this.internalOutputShapes[a], i = this.outputNames[a];
this.feedOutputNames.push(i), this.feedOutputShapes.push(o), this.feedLossFns.push(this.lossFunctions[a]);
}
let n = [];
this.metrics = e.metrics, this.metricsNames = ["loss"], this.metricsTensors = [], na("loss", () => {
for (let a = 0; a < this.outputs.length; ++a) {
if (n.indexOf(a) !== -1)
continue;
let o = this.lossFunctions[a];
this.outputs.length > 1 && (this.metricsTensors.push([o, a]), this.metricsNames.push(this.outputNames[a] + "_loss"));
}
});
let s = sV(e.metrics, this.outputNames), r = (a, o, i) => {
this.outputNames.length > 1 && (o = this.outputNames[a] + "_" + o), this.metricsNames.push(o), this.metricsTensors.push([i, a]);
};
na("metric", () => {
for (let a = 0; a < this.outputs.length; ++a) {
if (n.indexOf(a) !== -1)
continue;
let o = s[a];
((u) => {
let l = "", c, p, d;
for (let h of u) {
if (typeof h == "string" && ["accuracy", "acc", "crossentropy", "ce"].indexOf(h) !== -1) {
let m = this.internalOutputShapes[a];
m[m.length - 1] === 1 || this.lossFunctions[a] === Hp ? ["accuracy", "acc"].indexOf(h) !== -1 ? p = Qb : ["crossentropy", "ce"].indexOf(h) !== -1 && (p = kI) : this.lossFunctions[a] === Fd ? ["accuracy", "acc"].indexOf(h) !== -1 ? p = SI : ["crossentropy", "ce"].indexOf(h) !== -1 && (p = II) : ["accuracy", "acc"].indexOf(h) !== -1 ? p = Zb : ["crossentropy", "ce"].indexOf(h) !== -1 && (p = Jb);
let g;
["accuracy", "acc"].indexOf(h) !== -1 ? g = "acc" : ["crossentropy", "ce"].indexOf(h) !== -1 && (g = "ce"), d = p, c = l + g;
} else
d = zB(h), c = l + Qc(h);
let f;
na(c, () => {
f = d;
}), r(a, c, f);
}
})(o);
}
}), this.collectedTrainableWeights = this.trainableWeights;
}
checkTrainableWeightsConsistency() {
this.collectedTrainableWeights != null && this.trainableWeights.length !== this.collectedTrainableWeights.length && console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?");
}
evaluate(e, t, n = {}) {
let s = n.batchSize == null ? 32 : n.batchSize;
Fm(s);
let r = true, a = this.standardizeUserDataXY(e, t, r, s);
try {
let o = a[0].concat(a[1]);
this.makeTestFunction();
let i = this.testFunction, u = this.testLoop(i, o, s, n.verbose, n.steps);
return bn(u);
} finally {
ps(a[0], e), ps(a[1], t);
}
}
async evaluateDataset(e, t) {
return this.makeTestFunction(), QB(this, e, t);
}
checkNumSamples(e, t, n, s = "steps") {
let r;
if (n != null) {
if (r = null, t != null)
throw new G(`If ${s} is set, batchSize must be null or undefined.Got batchSize = ${t}`);
} else if (e != null)
Array.isArray(e) ? r = e[0].shape[0] : r = e.shape[0];
else
throw new G(`Either the input data should have a defined shape, or ${s} shoud be specified.`);
return r;
}
execute(e, t) {
if (Array.isArray(t) && t.length === 0)
throw new G("`outputs` is an empty Array, which is not allowed.");
let n = Array.isArray(t), s = n ? t : [t], r = this.retrieveSymbolicTensors(s), a = new Jr();
if (e instanceof et && (e = [e]), Array.isArray(e)) {
if (e.length !== this.inputs.length)
throw new G(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);
for (let i = 0; i < this.inputs.length; ++i)
a.add(this.inputs[i], e[i]);
} else
for (let i of this.inputs) {
let u = e[i.name];
if (u == null)
throw new G(`No value is provided for the model's input ${i.name}`);
a.add(i, u);
}
let o = Fu(r, a);
return n ? o : o[0];
}
retrieveSymbolicTensors(e) {
let t = ma(null, e.length), n = e.length;
for (let s of this.layers) {
let r = Array.isArray(s.output) ? s.output : [s.output], a = r.map((o) => o.name);
for (let o = 0; o < e.length; ++o) {
let i = a.indexOf(e[o]);
if (i !== -1 && (t[o] = r[i], n--), n === 0)
break;
}
if (n === 0)
break;
}
if (n > 0) {
let s = [];
throw t.forEach((r, a) => {
r == null && s.push(e[a]);
}), new G(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(s)}`);
}
return t;
}
predictLoop(e, t = 32, n = false) {
return q(() => {
let s = this.checkNumSamples(e);
if (n)
throw new Fe("Verbose predictLoop() is not implemented yet.");
let r = Om(s, t), a = this.outputs.map((o) => []);
for (let o = 0; o < r.length; ++o)
q(() => {
let u = r[o][0], l = r[o][1], c = Ou(e, u, l), p = [];
if (Array.isArray(c))
for (let h = 0; h < c.length; ++h)
p.push({ key: this.inputs[h], value: c[h] });
else
p.push({ key: this.inputs[0], value: c });
let d = new Jr(p);
return Fu(this.outputs, d);
}).forEach((u, l) => a[l].push(u));
return bn(a.map((o) => Ft(o, 0)));
});
}
predict(e, t = {}) {
let n = AI(e);
Yx(n, this.inputNames, this.feedInputShapes, false);
try {
let s = t.batchSize == null ? 32 : t.batchSize;
return Fm(s), this.predictLoop(n, s);
} finally {
ps(n, e);
}
}
predictOnBatch(e) {
Yx(e, this.inputNames, this.feedInputShapes, true);
let t = (Array.isArray(e) ? e[0] : e).shape[0];
return this.predictLoop(e, t);
}
standardizeUserDataXY(e, t, n = true, s) {
if (this.optimizer_ == null)
throw new fs("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");
let r = [];
for (let a = 0; a < this.feedOutputShapes.length; ++a) {
let o = this.feedOutputShapes[a];
this.feedLossFns[a] === Fd ? r.push(o.slice(0, o.length - 1).concat([1])) : r.push(o);
}
if (e = Xx(e, this.feedInputNames, this.feedInputShapes, false, "input"), t = Xx(t, this.feedOutputNames, r, false, "target"), tV(e, t, null), nV(t, this.feedLossFns, this.feedOutputShapes), this.stateful && s != null && s > 0 && e[0].shape[0] % s !== 0)
throw new G(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${s}. Found: ${e[0].shape[0]} sample(s).`);
return [e, t];
}
async standardizeUserData(e, t, n, s, r = true, a) {
let [o, i] = this.standardizeUserDataXY(e, t, r, a);
if (n != null)
throw new Error("sample weight is not supported yet.");
let u = null;
if (s != null) {
let l = TI(s, this.outputNames);
u = [];
for (let c = 0; c < l.length; ++c)
u.push(await $I(i[c], null, l[c]));
}
return [o, i, u];
}
testLoop(e, t, n, s = 0, r) {
return q(() => {
let a = this.checkNumSamples(t, n, r, "steps"), o = [];
if (s > 0)
throw new Fe("Verbose mode is not implemented yet.");
if (r != null)
throw new Fe("steps mode in testLoop() is not implemented yet");
{
let i = Om(a, n), u = Zt(ys(0, a));
for (let l = 0; l < i.length; ++l) {
let c = i[l][0], p = i[l][1], d = sa(u, c, p - c), h = ey(t, d), f = e(h);
if (l === 0)
for (let m = 0; m < f.length; ++m)
o.push(we(0));
for (let m = 0; m < f.length; ++m) {
let g = f[m];
o[m] = oe(o[m], V(p - c, g));
}
}
for (let l = 0; l < o.length; ++l)
o[l] = xe(o[l], a);
}
return o;
});
}
getDedupedMetricsNames() {
let e = this.metricsNames, t = [];
for (let n = 0; n < e.length; ++n) {
let s = e[n], r = s;
_x(e, s) > 1 && (r += `_${_x(e.slice(0, n), s)}`), t.push(r);
}
return t;
}
makeTrainFunction() {
return (e) => {
let t = [], n = e.slice(0, this.inputs.length), s = e.slice(this.inputs.length, this.inputs.length + this.outputs.length), r = e.slice(this.inputs.length + this.outputs.length, this.inputs.length + this.outputs.length * 2), a = [], o = () => {
let c = [];
for (let f = 0; f < this.inputs.length; ++f)
c.push({ key: this.inputs[f], value: n[f] });
let p = new Jr(c), d = Fu(this.outputs, p, { training: true }), h;
for (let f = 0; f < this.lossFunctions.length; ++f) {
let g = this.lossFunctions[f](s[f], d[f]);
r[f] != null && (g = HB(g, r[f]));
let b = It(g);
t.push(b), f === 0 ? h = g : h = oe(h, g);
}
for (let f = 0; f < this.metricsTensors.length; ++f) {
let m;
if (this.outputs.length > 1 && f < this.outputs.length)
m = t[f];
else {
let g = this.metricsTensors[f][0], b = this.metricsTensors[f][1];
m = It(g(s[b], d[b]));
}
qt(m), a.push(m);
}
return h = It(h), this.calculateLosses().forEach((f) => {
h = oe(h, f);
}), h;
}, i = this.collectedTrainableWeights.map((c) => c.read()), u = true;
return [this.optimizer_.minimize(o, u, i)].concat(a);
};
}
makeTestFunction() {
this.testFunction = (e) => q(() => {
let t = [], n, s = e.slice(0, this.inputs.length), r = e.slice(this.inputs.length, this.inputs.length + this.outputs.length), a = [];
for (let u = 0; u < this.inputs.length; ++u)
a.push({ key: this.inputs[u], value: s[u] });
let o = new Jr(a), i = Fu(this.outputs, o);
for (let u = 0; u < this.lossFunctions.length; ++u) {
let l = this.lossFunctions[u], c = It(l(r[u], i[u]));
u === 0 ? n = c : n = oe(n, c), t.push(n);
}
for (let u = 0; u < this.metricsTensors.length; ++u) {
let l = this.metricsTensors[u][0], c = this.metricsTensors[u][1], p = It(l(r[c], i[c]));
t.push(p);
}
return t;
});
}
async fit(e, t, n = {}) {
return JB(this, e, t, n);
}
async fitDataset(e, t) {
return KB(this, e, t);
}
async trainOnBatch(e, t) {
let n = await this.standardizeUserData(e, t), s = n[0], r = n[1], o = this.makeTrainFunction()(s.concat(r)), i = [];
for (let u of o) {
let l = await u.data();
i.push(l[0]);
}
return De(o), ps(n[0], e), ps(n[1], t), bn(i);
}
getNamedWeights(e) {
let t = [], n = e != null && e.trainableOnly, s = n ? this.trainableWeights : this.weights, r = this.getWeights(n);
for (let a = 0; a < s.length; ++a)
n && !s[a].trainable || t.push({ name: s[a].originalName, tensor: r[a] });
return t;
}
set stopTraining(e) {
this.stopTraining_ = e;
}
get stopTraining() {
return this.stopTraining_;
}
get optimizer() {
return this.optimizer_;
}
set optimizer(e) {
this.optimizer_ !== e && (this.optimizer_ = e, this.isOptimizerOwned = false);
}
dispose() {
let e = super.dispose();
if (e.refCountAfterDispose === 0 && this.optimizer != null && this.isOptimizerOwned) {
let t = xm().numTensors;
this.optimizer_.dispose(), e.numDisposedVariables += t - xm().numTensors;
}
return e;
}
getLossIdentifiers() {
let e;
if (typeof this.loss == "string")
e = Vs(this.loss);
else if (Array.isArray(this.loss)) {
for (let t of this.loss)
if (typeof t != "string")
throw new Error("Serialization of non-string loss is not supported.");
e = this.loss.map((t) => Vs(t));
} else {
let t = Object.keys(this.loss);
e = {};
let n = this.loss;
for (let s of t)
if (typeof n[s] == "string")
e[s] = Vs(n[s]);
else
throw new Error("Serialization of non-string loss is not supported.");
}
return e;
}
getMetricIdentifiers() {
if (typeof this.metrics == "string" || typeof this.metrics == "function")
return [Vs(Qc(this.metrics))];
if (Array.isArray(this.metrics))
return this.metrics.map((e) => Vs(Qc(e)));
{
let e = {};
for (let t in this.metrics)
e[t] = Vs(Qc(this.metrics[t]));
return e;
}
}
getTrainingConfig() {
return { loss: this.getLossIdentifiers(), metrics: this.getMetricIdentifiers(), optimizer_config: { class_name: this.optimizer.getClassName(), config: this.optimizer.getConfig() } };
}
loadTrainingConfig(e) {
if (e.weighted_metrics != null)
throw new Error("Loading weight_metrics is not supported yet.");
if (e.loss_weights != null)
throw new Error("Loading loss_weights is not supported yet.");
if (e.sample_weight_mode != null)
throw new Error("Loading sample_weight_mode is not supported yet.");
let t = sl(e.optimizer_config), n = gs(t), s;
if (typeof e.loss == "string")
s = Yr(e.loss);
else if (Array.isArray(e.loss))
s = e.loss.map((a) => Yr(a));
else if (e.loss != null) {
s = {};
for (let a in e.loss)
s[a] = Yr(e.loss[a]);
}
let r;
if (Array.isArray(e.metrics))
r = e.metrics.map((a) => Yr(a));
else if (e.metrics != null) {
r = {};
for (let a in e.metrics)
r[a] = Yr(e.metrics[a]);
}
this.compile({ loss: s, metrics: r, optimizer: n });
}
async save(e, t) {
if (typeof e == "string") {
let u = An.getSaveHandlers(e);
if (u.length === 0)
throw new G(`Cannot find any save handlers for URL '${e}'`);
if (u.length > 1)
throw new G(`Found more than one (${u.length}) save handlers for URL '${e}'`);
e = u[0];
}
if (e.save == null)
throw new G("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");
let n = await An.encodeWeights(this.getNamedWeights(t)), s = false, r = null, o = { modelTopology: this.toJSON(r, s), format: rV, generatedBy: `TensorFlow.js tfjs-layers v${NI}`, convertedBy: null };
if ((t == null ? false : t.includeOptimizer) && this.optimizer != null) {
o.trainingConfig = this.getTrainingConfig();
let u = "optimizer", { data: l, specs: c } = await An.encodeWeights(await this.optimizer.getWeights(), u);
n.specs.push(...c), n.data = An.concatenateArrayBuffers([n.data, l]);
}
return this.userDefinedMetadata != null && (Hx(this.userDefinedMetadata, this.name, true), o.userDefinedMetadata = this.userDefinedMetadata), o.weightData = n.data, o.weightSpecs = n.specs, e.save(o);
}
setUserDefinedMetadata(e) {
Hx(e, this.name), this.userDefinedMetadata = e;
}
getUserDefinedMetadata() {
return this.userDefinedMetadata;
}
};
pr.className = "Model";
re.registerClass(pr);
var EI = class extends pr {
};
EI.className = "Functional";
re.registerClass(EI);
async function aV(e, t) {
"modelTopology" in e || (e = { modelTopology: e }), e = e;
let n = e.modelTopology;
n.model_config != null && (n = n.model_config);
let s = sl(n), r = gs(s, t);
if (e.weightsManifest != null) {
let a = await An.loadWeights(e.weightsManifest, e.pathPrefix, r.weights.map((i) => i.originalName)), o = {};
for (let i of r.weights)
o[i.originalName] = a[i.originalName];
r.loadWeights(o), De(a);
}
return r;
}
async function oV(e, t) {
if (t == null && (t = {}), typeof e == "string") {
let n = An.getLoadHandlers(e, t);
if (n.length === 0)
n.push(An.browserHTTPRequest(e, t));
else if (n.length > 1)
throw new G(`Found more than one (${n.length}) load handlers for URL '${e}'`);
e = n[0];
}
return iV(e, void 0, t);
}
async function iV(e, t, n) {
if (n == null && (n = {}), e.load == null)
throw new G("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");
let s = await e.load(), r = s.modelTopology;
r.model_config != null && (r = r.model_config);
let a = n.strict == null ? true : n.strict, o = s.weightData != null && s.weightSpecs != null && a, i = gs(sl(r), t, o), u = s.trainingConfig;
if (u != null && i.loadTrainingConfig(u), s.userDefinedMetadata != null && i.setUserDefinedMetadata(s.userDefinedMetadata), s.weightData != null) {
if (s.weightSpecs == null)
throw new G("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");
let { modelWeights: l, optimizerWeights: c } = uV(s.weightData, s.weightSpecs);
i.loadWeights(l, a), i.optimizer != null && c.length > 0 && await i.optimizer.setWeights(c), De(l), De(c.map((p) => p.tensor));
}
return i;
}
function uV(e, t) {
let n = An.decodeWeights(e, t), s = {}, r = [];
return t.forEach((a) => {
a.group === "optimizer" ? r.push({ name: a.name, tensor: n[a.name] }) : s[a.name] = n[a.name];
}), { modelWeights: s, optimizerWeights: r };
}
var zm = class extends pr {
constructor(e) {
if (super({ inputs: [], outputs: [] }), e = e || {}, this.trainable = true, this.built = false, this.name = e.name != null ? e.name : Dp("sequential_"), e.layers != null)
for (let t of e.layers)
this.add(t);
}
checkShape(e) {
if (e.inboundNodes[0].outputTensors[0].shape.some((n) => n < 0))
throw new G(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`);
}
add(e) {
let t = e instanceof zm || e instanceof pr, n;
if (t) {
if (n = e, n.outputs.length !== 1)
throw new G("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");
if (n.inputs.length !== 1)
throw new G("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.");
}
if (this.outputs.length === 0) {
if (e.inboundNodes.length === 0) {
if (e.batchInputShape == null)
throw new G("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");
let s = fI({ batchShape: e.batchInputShape, dtype: e.dtype, name: e.name + "_input" });
e.apply(s);
}
if (t)
this.outputs = n.outputs, this.inputs = n.inputs;
else {
if (e.inboundNodes.length !== 1)
throw new G(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);
if (e.inboundNodes[0].outputTensors.length !== 1)
throw new G("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");
this.checkShape(e), this.outputs = [e.inboundNodes[0].outputTensors[0]], this.inputs = hI(this.outputs[0]);
}
this.inboundNodes = [], new Up({ outboundLayer: this, inboundLayers: [], nodeIndices: [], tensorIndices: [], inputTensors: this.inputs, outputTensors: this.outputs, inputMasks: ma(null, this.inputs.length), outputMasks: [null], inputShapes: this.inputs.map((s) => s.shape), outputShapes: this.outputs[0].shape });
} else {
let s = e.apply(this.outputs[0]);
if (Array.isArray(s))
throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");
this.checkShape(e), this.outputs = [s], this.inboundNodes[0].outputTensors = this.outputs, this.inboundNodes[0].outputShapes = [this.outputs[0].shape];
}
this.layers.push(e), this.built = false;
}
pop() {
if (this.layers.length === 0)
throw new TypeError("There are no layers in the model.");
if (this.layers.pop(), this.layers.length === 0)
this.outputs = [], this.inboundNodes = [], this.outboundNodes = [];
else {
let e = this.layers.length - 1;
this.layers[e].outboundNodes = [], this.outputs = [this.layers[e].output], this.inboundNodes[0].outputTensors = this.outputs, this.inboundNodes[0].outputShapes = [this.outputs[0].shape];
}
}
call(e, t) {
return this.model == null && this.build(), this.model.call(e, t);
}
build(e) {
if (nt(e), this.inputs.length === 0 || this.outputs.length === 0)
throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");
this.model = new pr({ inputs: this.inputs, outputs: this.outputs[0], name: this.name + "_model" }), this.model.trainable = this.trainable, this.supportsMasking = this.model.supportsMasking, this.inputLayers = this.model.inputLayers, this.inputLayersNodeIndices = this.model.inputLayersNodeIndices, this.inputLayersTensorIndices = this.model.inputLayersTensorIndices, this.outputLayers = this.model.outputLayers, this.outputLayersNodeIndices = this.model.outputLayersNodeIndices, this.outputLayersTensorIndices = this.model.outputLayersTensorIndices, this.nodesByDepth = this.model.nodesByDepth, this.containerNodes = this.model.containerNodes, this.outputNames = this.model.outputNames, this.inputNames = this.model.inputNames, this.built = true;
}
countParams() {
return this.built || this.build(), super.countParams();
}
summary(e, t, n = console.log) {
this.built || this.build(), super.summary(e, t, n);
}
setWeights(e) {
this.model == null && this.build(), this.model.setWeights(e);
}
evaluate(e, t, n = {}) {
if (!this.built)
throw new fs("The model needs to be compiled before being used.");
return this.model.evaluate(e, t, n);
}
async evaluateDataset(e, t) {
if (!this.built)
throw new fs("The model needs to be compiled before being used.");
return this.model.evaluateDataset(e, t);
}
predict(e, t = {}) {
return this.model == null && this.build(), this.model.predict(e, t);
}
predictOnBatch(e) {
return this.model == null && this.build(), this.model.predictOnBatch(e);
}
compile(e) {
this.build(), this.model.compile(e), this.optimizer_ = this.model.optimizer, this.isOptimizerOwned = this.model.isOptimizerOwned, this.loss = this.model.loss, this.metrics = this.model.metrics, this.metricsTensors = this.model.metricsTensors, this.metricsNames = this.model.metricsNames;
}
get optimizer() {
return this.model == null ? void 0 : this.model.optimizer;
}
set optimizer(e) {
this.model.optimizer = e;
}
async fit(e, t, n = {}) {
if (!this.built)
throw new fs("The model needs to be compiled before being used.");
return this.model.fit(e, t, n);
}
async fitDataset(e, t) {
if (!this.built)
throw new fs("The model needs to be compiled before being used.");
return this.model.fitDataset(e, t);
}
async trainOnBatch(e, t) {
return this.model.trainOnBatch(e, t);
}
static fromConfig(e, t, n = {}, s = false) {
let r, a = {};
if (t instanceof Array) {
if (t[0].className == null || t[0].className === "Merge")
throw new G("Legacy serialization format not supported yet.");
r = t;
} else
w.assert(t.layers != null, () => "When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."), r = t.layers, delete t.layers, a = t;
let o = new e(a);
if (!(o instanceof zm))
throw new Fe(`Sequential.fromConfig called on non-Sequential input: ${o}`);
for (let i of r) {
let l = gs(i, void 0, s);
s && l.setFastWeightInitDuringBuild(true), o.add(l);
}
return o;
}
set stopTraining(e) {
if (this.model == null)
throw new G("Cannot set the stopTraining property of a sequential model before it is compiled.");
this.model.stopTraining = e;
}
get stopTraining() {
if (this.model == null)
throw new G("Cannot get the stopTraining property of a sequential model before it is compiled.");
return this.model.stopTraining;
}
getConfig() {
let e = [];
for (let t of this.layers) {
let n = {};
n.className = t.getClassName(), n.config = t.getConfig(), e.push(n);
}
return { name: this.name, layers: e };
}
};
var ty = zm;
ty.className = "Sequential";
re.registerClass(ty);
function Che(e) {
return new pr(e);
}
function Nhe(e) {
return new ty(e);
}
function The(e, t) {
return t == null && (t = {}), oV(e, t);
}
function lV(e) {
return fI(e);
}
function $he(e, t) {
Xb.registerCallbackConstructor(e, t);
}
var kn = class extends re.Serializable {
getConfig() {
return {};
}
};
var RI = class extends kn {
apply(e, t = 1) {
return kz(e, t);
}
};
RI.className = "elu";
re.registerClass(RI);
var DI = class extends kn {
apply(e) {
return OS(e);
}
};
DI.className = "selu";
re.registerClass(DI);
var FI = class extends kn {
apply(e) {
return Xs(e);
}
};
FI.className = "relu";
re.registerClass(FI);
var OI = class extends kn {
apply(e) {
return q(() => Np(6, Xs(e)));
}
};
OI.className = "relu6";
re.registerClass(OI);
var PI = class extends kn {
apply(e) {
return e;
}
};
PI.className = "linear";
re.registerClass(PI);
var zI = class extends kn {
apply(e) {
return qs(e);
}
};
zI.className = "sigmoid";
re.registerClass(zI);
var LI = class extends kn {
apply(e) {
return Iz(e);
}
};
LI.className = "hardSigmoid";
re.registerClass(LI);
var MI = class extends kn {
apply(e) {
return Vl(e);
}
};
MI.className = "softplus";
re.registerClass(MI);
var BI = class extends kn {
apply(e) {
return Sz(e);
}
};
BI.className = "softsign";
re.registerClass(BI);
var VI = class extends kn {
apply(e) {
return Qu(e);
}
};
VI.className = "tanh";
re.registerClass(VI);
var ny = class extends kn {
apply(e, t = -1) {
return xb(e, t);
}
};
ny.className = "softmax";
re.registerClass(ny);
var WI = class extends kn {
apply(e, t = -1) {
return TS(e, t);
}
};
WI.className = "logSoftmax";
re.registerClass(WI);
var UI = class extends kn {
apply(e, t = 1) {
return q(() => V(qs(V(e, t)), e));
}
};
UI.className = "swish";
re.registerClass(UI);
var GI = class extends kn {
apply(e) {
return q(() => V(e, Qu(Vl(e))));
}
};
GI.className = "mish";
re.registerClass(GI);
function vr(e) {
return e.getClassName();
}
function tm(e, t = {}) {
return Ul(e, re.SerializationMap.getMap().classNameMap, t, "activation");
}
function xr(e) {
if (e == null) {
let t = {};
return t.className = "linear", t.config = {}, tm(t);
}
if (typeof e == "string") {
let t = {};
return t.className = e, t.config = {}, tm(t);
} else
return e instanceof kn ? e : tm(e);
}
function sy(e) {
if (e != null && typeof e != "object")
throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`);
}
var HI = class extends re.Serializable {
};
var Kl = class extends HI {
constructor(e) {
super(), sy(e), this.l1 = e == null || e.l1 == null ? 0.01 : e.l1, this.l2 = e == null || e.l2 == null ? 0.01 : e.l2, this.hasL1 = this.l1 !== 0, this.hasL2 = this.l2 !== 0;
}
apply(e) {
return q(() => {
let t = $t([1]);
return this.hasL1 && (t = oe(t, ve(V(this.l1, Lt(e))))), this.hasL2 && (t = oe(t, ve(V(this.l2, Hl(e))))), U(t, []);
});
}
getConfig() {
return { l1: this.l1, l2: this.l2 };
}
static fromConfig(e, t) {
return new e({ l1: t.l1, l2: t.l2 });
}
};
Kl.className = "L1L2";
re.registerClass(Kl);
function cV(e) {
return sy(e), new Kl({ l1: e != null ? e.l1 : null, l2: 0 });
}
function dV(e) {
return sy(e), new Kl({ l2: e != null ? e.l2 : null, l1: 0 });
}
var Qx = { l1l2: "L1L2" };
function it(e) {
return Db(e);
}
function Zx(e, t = {}) {
return Ul(e, re.SerializationMap.getMap().classNameMap, t, "regularizer");
}
function mt(e) {
if (e == null)
return null;
if (typeof e == "string") {
let n = { className: e in Qx ? Qx[e] : e, config: {} };
return Zx(n);
} else
return e instanceof HI ? e : Zx(e);
}
var ry = class extends He {
constructor(e) {
super(e == null ? {} : e), this.supportsMasking = true, e != null && (this.maxValue = e.maxValue);
}
call(e, t) {
e = Oe(e);
let n = Xs(e);
return this.maxValue != null && (n = Wn(n, 0, this.maxValue)), n;
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = { maxValue: this.maxValue }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
ry.className = "ReLU";
re.registerClass(ry);
var ay = class extends He {
constructor(e) {
super(e == null ? {} : e), this.DEFAULT_ALPHA = 0.3, e == null && (e = {}), this.alpha = e.alpha == null ? this.DEFAULT_ALPHA : e.alpha;
}
call(e, t) {
let n = Oe(e);
return lb(n, this.alpha);
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = { alpha: this.alpha }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
ay.className = "LeakyReLU";
re.registerClass(ay);
var oy = class extends He {
constructor(e) {
if (super(e == null ? {} : e), this.DEFAULT_ALPHA_INITIALIZER = "zeros", e == null && (e = {}), this.supportsMasking = true, this.alphaInitializer = ft(e.alphaInitializer || this.DEFAULT_ALPHA_INITIALIZER), this.alphaRegularizer = mt(e.alphaRegularizer), this.alphaConstraint = Pt(e.alphaConstraint), e.sharedAxes == null)
this.sharedAxes = null;
else if (Array.isArray(e.sharedAxes))
this.sharedAxes = e.sharedAxes;
else if (typeof e.sharedAxes == "number")
this.sharedAxes = [e.sharedAxes];
else
throw new G(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);
}
build(e) {
e = nt(e);
let t = e.slice(1);
if (this.sharedAxes != null)
for (let s of this.sharedAxes)
t[s - 1] = 1;
this.alpha = this.addWeight("alpha", t, "float32", this.alphaInitializer, this.alphaRegularizer, true, this.alphaConstraint);
let n = {};
if (this.sharedAxes != null)
for (let s = 1; s < e.length; ++s)
n[s] = e[s];
this.inputSpec = [new Dt({ ndim: e.length, axes: n })], this.built = true;
}
call(e, t) {
return e = Oe(e), mb(e, this.alpha.read());
}
getConfig() {
let e = { alphaInitializer: yt(this.alphaInitializer), alphaRegularizer: it(this.alphaRegularizer), alphaConstraint: Ot(this.alphaConstraint), sharedAxes: this.sharedAxes }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
oy.className = "PReLU";
re.registerClass(oy);
var iy = class extends He {
constructor(e) {
if (super(e == null ? {} : e), this.DEFAULT_ALPHA = 1, e == null && (e = {}), e.alpha != null && e.alpha !== this.DEFAULT_ALPHA)
throw new Fe(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);
this.alpha = e.alpha == null ? this.DEFAULT_ALPHA : e.alpha;
}
call(e, t) {
let n = Oe(e);
return Sp(n);
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = { alpha: this.alpha }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
iy.className = "ELU";
re.registerClass(iy);
var uy = class extends He {
constructor(e) {
super(e == null ? {} : e), this.DEFAULT_THETA = 1, e == null && (e = {}), this.theta = e.theta == null ? this.DEFAULT_THETA : e.theta;
}
call(e, t) {
let n = Oe(e);
return V(n, le(Gn(n, this.theta), "float32"));
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = { theta: this.theta }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
uy.className = "ThresholdedReLU";
re.registerClass(uy);
var ly = class extends He {
constructor(e) {
super(e == null ? {} : e), this.DEFAULT_AXIS = 1, e == null && (e = {}), this.softmax = new ny().apply, this.axis = e.axis == null ? this.DEFAULT_AXIS : e.axis;
}
call(e, t) {
let n = Oe(e);
return this.softmax(n, this.axis);
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = { axis: this.axis }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
ly.className = "Softmax";
re.registerClass(ly);
function Jo(e, t, n) {
if (typeof e == "number")
return ma(e, t);
if (e.length !== t)
throw new G(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);
for (let s = 0; s < t; ++s) {
let r = e[s];
if (!yz(r))
throw new G(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${r}`);
}
return e;
}
function bs(e, t, n, s, r = 1) {
if (e == null)
return e;
let a = t + (t - 1) * (r - 1), o;
return n === "same" ? o = e : o = e - a + 1, Math.floor((o + s - 1) / s);
}
function Ns(e, t, n, s) {
if (e == null)
return null;
if (s === "valid")
e = e * t + yr([n - t, 0]);
else if (s === "same")
e = e * t;
else
throw new G(`Unsupport padding mode: ${s}.`);
return e;
}
function cy(e, t) {
return q(() => (Ct(t), t === "channelsFirst" ? Ge(e, [0, 2, 3, 1]) : e));
}
function qI(e, t) {
return q(() => (Ct(t), t === "channelsFirst" ? Ge(e, [0, 2, 3, 4, 1]) : e));
}
function pV(e, t, n, s = 1, r = "valid", a, o = 1) {
return q(() => {
if (a == null && (a = vs()), Ct(a), e.shape.length !== 3)
throw new G(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);
if (t.shape.length !== 3)
throw new G(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);
if (n != null && n.shape.length !== 1)
throw new G(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);
if (a === "channelsFirst" && (e = Ge(e, [0, 2, 1])), r === "causal")
throw new Fe("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");
let i = mS(e, t, s, r === "same" ? "same" : "valid", "NWC", o);
return n != null && (i = ks(i, n)), i;
});
}
function Jx(e, t, n, s = [1, 1], r = "valid", a, o, i = null) {
return q(() => {
if (a == null && (a = vs()), Ct(a), e.rank !== 3 && e.rank !== 4)
throw new G(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);
if (t.rank !== 3 && t.rank !== 4)
throw new G(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);
let u = cy(e, a);
if (r === "causal")
throw new Fe("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");
return u = fa.conv2d({ x: u, filter: t, strides: s, pad: r === "same" ? "same" : "valid", dilations: o, dataFormat: "NHWC", bias: n, activation: i }), a === "channelsFirst" && (u = Ge(u, [0, 3, 1, 2])), u;
});
}
function hV(e, t, n, s = [1, 1, 1], r = "valid", a, o) {
return q(() => {
if (a == null && (a = vs()), Ct(a), e.rank !== 4 && e.rank !== 5)
throw new G(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);
if (t.rank !== 4 && t.rank !== 5)
throw new G(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);
let i = qI(e, a);
if (r === "causal")
throw new Fe("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");
return i = bS(i, t, s, r === "same" ? "same" : "valid", "NDHWC", o), n != null && (i = ks(i, n)), a === "channelsFirst" && (i = Ge(i, [0, 4, 1, 2, 3])), i;
});
}
var dy = class extends He {
constructor(e, t) {
if (super(t), this.bias = null, this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", this.DEFAULT_BIAS_INITIALIZER = "zeros", dy.verifyArgs(t), this.rank = e, Bt(this.rank, "rank"), this.rank !== 1 && this.rank !== 2 && this.rank !== 3)
throw new Fe(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);
if (this.kernelSize = Jo(t.kernelSize, e, "kernelSize"), this.strides = Jo(t.strides == null ? 1 : t.strides, e, "strides"), this.padding = t.padding == null ? "valid" : t.padding, Hn(this.padding), this.dataFormat = t.dataFormat == null ? "channelsLast" : t.dataFormat, Ct(this.dataFormat), this.activation = xr(t.activation), this.useBias = t.useBias == null ? true : t.useBias, this.biasInitializer = ft(t.biasInitializer || this.DEFAULT_BIAS_INITIALIZER), this.biasConstraint = Pt(t.biasConstraint), this.biasRegularizer = mt(t.biasRegularizer), this.activityRegularizer = mt(t.activityRegularizer), this.dilationRate = Jo(t.dilationRate == null ? 1 : t.dilationRate, e, "dilationRate"), this.rank === 1 && Array.isArray(this.dilationRate) && this.dilationRate.length !== 1)
throw new G(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);
if (this.rank === 2) {
if (typeof this.dilationRate == "number")
this.dilationRate = [this.dilationRate, this.dilationRate];
else if (this.dilationRate.length !== 2)
throw new G(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`);
} else if (this.rank === 3) {
if (typeof this.dilationRate == "number")
this.dilationRate = [this.dilationRate, this.dilationRate, this.dilationRate];
else if (this.dilationRate.length !== 3)
throw new G(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`);
}
}
static verifyArgs(e) {
if (Cs("kernelSize" in e, "required key 'kernelSize' not in config"), typeof e.kernelSize != "number" && !Fb(e.kernelSize, "number", 1, 3))
throw new G(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`);
}
getConfig() {
let e = { kernelSize: this.kernelSize, strides: this.strides, padding: this.padding, dataFormat: this.dataFormat, dilationRate: this.dilationRate, activation: vr(this.activation), useBias: this.useBias, biasInitializer: yt(this.biasInitializer), biasRegularizer: it(this.biasRegularizer), activityRegularizer: it(this.activityRegularizer), biasConstraint: Ot(this.biasConstraint) }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
var Xl = class extends dy {
constructor(e, t) {
super(e, t), this.kernel = null, Xl.verifyArgs(t), this.filters = t.filters, Bt(this.filters, "filters"), this.kernelInitializer = ft(t.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.kernelConstraint = Pt(t.kernelConstraint), this.kernelRegularizer = mt(t.kernelRegularizer);
}
build(e) {
e = nt(e);
let t = this.dataFormat === "channelsFirst" ? 1 : e.length - 1;
if (e[t] == null)
throw new G(`The channel dimension of the input should be defined. Found ${e[t]}`);
let n = e[t], s = this.kernelSize.concat([n, this.filters]);
this.kernel = this.addWeight("kernel", s, null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint), this.useBias && (this.bias = this.addWeight("bias", [this.filters], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint)), this.inputSpec = [{ ndim: this.rank + 2, axes: { [t]: n } }], this.built = true;
}
call(e, t) {
return q(() => {
e = Oe(e);
let n, s = this.bias == null ? null : this.bias.read(), r = aI(this.activation.getClassName());
if (r != null && this.rank === 2)
n = Jx(e, this.kernel.read(), s, this.strides, this.padding, this.dataFormat, this.dilationRate, r);
else {
if (this.rank === 1)
n = pV(e, this.kernel.read(), s, this.strides[0], this.padding, this.dataFormat, this.dilationRate[0]);
else if (this.rank === 2)
n = Jx(e, this.kernel.read(), s, this.strides, this.padding, this.dataFormat, this.dilationRate);
else if (this.rank === 3)
n = hV(e, this.kernel.read(), s, this.strides, this.padding, this.dataFormat, this.dilationRate);
else
throw new Fe("convolutions greater than 3D are not implemented yet.");
this.activation != null && (n = this.activation.apply(n));
}
return n;
});
}
computeOutputShape(e) {
e = nt(e);
let t = [], n = this.dataFormat === "channelsLast" ? e.slice(1, e.length - 1) : e.slice(2);
for (let r = 0; r < n.length; ++r) {
let a = bs(n[r], this.kernelSize[r], this.padding, this.strides[r], typeof this.dilationRate == "number" ? this.dilationRate : this.dilationRate[r]);
t.push(a);
}
let s = [e[0]];
return this.dataFormat === "channelsLast" ? (s = s.concat(t), s.push(this.filters)) : (s.push(this.filters), s = s.concat(t)), s;
}
getConfig() {
let e = { filters: this.filters, kernelInitializer: yt(this.kernelInitializer), kernelRegularizer: it(this.kernelRegularizer), kernelConstraint: Ot(this.kernelConstraint) }, t = super.getConfig();
return Object.assign(e, t), e;
}
static verifyArgs(e) {
if (!("filters" in e) || typeof e.filters != "number" || e.filters < 1)
throw new G(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`);
}
};
var jI = class extends Xl {
constructor(e) {
super(2, e), jI.verifyArgs(e);
}
getConfig() {
let e = super.getConfig();
return delete e.rank, e;
}
static verifyArgs(e) {
if (typeof e.kernelSize != "number" && !Fb(e.kernelSize, "number", 1, 2))
throw new G(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`);
}
};
var qp = jI;
qp.className = "Conv2D";
re.registerClass(qp);
var KI = class extends Xl {
constructor(e) {
super(3, e), KI.verifyArgs(e);
}
getConfig() {
let e = super.getConfig();
return delete e.rank, e;
}
static verifyArgs(e) {
if (typeof e.kernelSize != "number" && !(Array.isArray(e.kernelSize) && (e.kernelSize.length === 1 || e.kernelSize.length === 3)))
throw new G(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`);
}
};
var jp = KI;
jp.className = "Conv3D";
re.registerClass(jp);
var py = class extends qp {
constructor(e) {
if (super(e), this.inputSpec = [new Dt({ ndim: 4 })], this.padding !== "same" && this.padding !== "valid")
throw new G(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`);
}
build(e) {
if (e = nt(e), e.length !== 4)
throw new G("Input should have rank 4; Received input shape: " + JSON.stringify(e));
let t = this.dataFormat === "channelsFirst" ? 1 : e.length - 1;
if (e[t] == null)
throw new G("The channel dimension of the inputs should be defined. Found `None`.");
let n = e[t], s = this.kernelSize.concat([this.filters, n]);
this.kernel = this.addWeight("kernel", s, "float32", this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint), this.useBias && (this.bias = this.addWeight("bias", [this.filters], "float32", this.biasInitializer, this.biasRegularizer, true, this.biasConstraint)), this.inputSpec = [new Dt({ ndim: 4, axes: { [t]: n } })], this.built = true;
}
call(e, t) {
return q(() => {
let n = Oe(e);
if (n.shape.length !== 4)
throw new G(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);
let s = n.shape, r = s[0], a, o;
this.dataFormat === "channelsFirst" ? (a = 2, o = 3) : (a = 1, o = 2);
let i = s[a], u = s[o], l = this.kernelSize[0], c = this.kernelSize[1], p = this.strides[0], d = this.strides[1], h = Ns(i, p, l, this.padding), f = Ns(u, d, c, this.padding), m = [r, h, f, this.filters];
this.dataFormat !== "channelsLast" && (n = Ge(n, [0, 2, 3, 1]));
let g = gS(n, this.kernel.read(), m, this.strides, this.padding);
return this.dataFormat !== "channelsLast" && (g = Ge(g, [0, 3, 1, 2])), this.bias != null && (g = ks(g, this.bias.read(), this.dataFormat)), this.activation != null && (g = this.activation.apply(g)), g;
});
}
computeOutputShape(e) {
e = nt(e);
let t = e.slice(), n, s, r;
this.dataFormat === "channelsFirst" ? (n = 1, s = 2, r = 3) : (n = 3, s = 1, r = 2);
let a = this.kernelSize[0], o = this.kernelSize[1], i = this.strides[0], u = this.strides[1];
return t[n] = this.filters, t[s] = Ns(t[s], i, a, this.padding), t[r] = Ns(t[r], u, o, this.padding), t;
}
getConfig() {
let e = super.getConfig();
return delete e.dilationRate, e;
}
};
py.className = "Conv2DTranspose";
re.registerClass(py);
var hy = class extends jp {
constructor(e) {
if (super(e), this.inputSpec = [new Dt({ ndim: 5 })], this.padding !== "same" && this.padding !== "valid")
throw new G(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`);
}
build(e) {
if (e = nt(e), e.length !== 5)
throw new G("Input should have rank 5; Received input shape: " + JSON.stringify(e));
let t = this.dataFormat === "channelsFirst" ? 1 : e.length - 1;
if (e[t] == null)
throw new G("The channel dimension of the inputs should be defined. Found `None`.");
let n = e[t], s = this.kernelSize.concat([this.filters, n]);
this.kernel = this.addWeight("kernel", s, "float32", this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint), this.useBias && (this.bias = this.addWeight("bias", [this.filters], "float32", this.biasInitializer, this.biasRegularizer, true, this.biasConstraint)), this.inputSpec = [new Dt({ ndim: 5, axes: { [t]: n } })], this.built = true;
}
call(e, t) {
return q(() => {
let n = Oe(e);
if (n.shape.length !== 5)
throw new G(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);
let s = n.shape, r = s[0], a, o, i;
this.dataFormat === "channelsFirst" ? (i = 2, a = 3, o = 4) : (i = 1, a = 2, o = 3);
let u = s[i], l = s[a], c = s[o], p = this.kernelSize[0], d = this.kernelSize[1], h = this.kernelSize[2], f = this.strides[0], m = this.strides[1], g = this.strides[2], b = Ns(u, f, p, this.padding), y = Ns(l, m, d, this.padding), v = Ns(c, g, h, this.padding), x = [r, b, y, v, this.filters];
this.dataFormat !== "channelsLast" && (n = Ge(n, [0, 2, 3, 4, 1]));
let k = SR(n, this.kernel.read(), x, this.strides, this.padding);
return this.dataFormat !== "channelsLast" && (k = Ge(k, [0, 4, 1, 2, 3])), this.bias !== null && (k = ks(k, this.bias.read(), this.dataFormat)), this.activation !== null && (k = this.activation.apply(k)), k;
});
}
computeOutputShape(e) {
e = nt(e);
let t = e.slice(), n, s, r, a;
this.dataFormat === "channelsFirst" ? (n = 1, s = 2, r = 3, a = 4) : (n = 4, s = 1, r = 2, a = 3);
let o = this.kernelSize[0], i = this.kernelSize[1], u = this.kernelSize[2], l = this.strides[0], c = this.strides[1], p = this.strides[2];
return t[n] = this.filters, t[s] = Ns(t[s], l, o, this.padding), t[r] = Ns(t[r], c, i, this.padding), t[a] = Ns(t[a], p, u, this.padding), t;
}
getConfig() {
let e = super.getConfig();
return delete e.dilationRate, e;
}
};
hy.className = "Conv3DTranspose";
re.registerClass(hy);
var XI = class extends Xl {
constructor(e, t) {
if (super(e, t), this.DEFAULT_DEPTHWISE_INITIALIZER = "glorotUniform", this.DEFAULT_POINTWISE_INITIALIZER = "glorotUniform", this.depthwiseKernel = null, this.pointwiseKernel = null, t.filters == null)
throw new G("The `filters` configuration field is required by SeparableConv, but is unspecified.");
if (t.kernelInitializer != null || t.kernelRegularizer != null || t.kernelConstraint != null)
throw new G("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");
if (t.padding != null && t.padding !== "same" && t.padding !== "valid")
throw new G(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);
this.depthMultiplier = t.depthMultiplier == null ? 1 : t.depthMultiplier, this.depthwiseInitializer = ft(t.depthwiseInitializer || this.DEFAULT_DEPTHWISE_INITIALIZER), this.depthwiseRegularizer = mt(t.depthwiseRegularizer), this.depthwiseConstraint = Pt(t.depthwiseConstraint), this.pointwiseInitializer = ft(t.depthwiseInitializer || this.DEFAULT_POINTWISE_INITIALIZER), this.pointwiseRegularizer = mt(t.pointwiseRegularizer), this.pointwiseConstraint = Pt(t.pointwiseConstraint);
}
build(e) {
if (e = nt(e), e.length < this.rank + 2)
throw new G(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank + 2}, but received input shape: ${JSON.stringify(e)}`);
let t = this.dataFormat === "channelsFirst" ? 1 : e.length - 1;
if (e[t] == null || e[t] < 0)
throw new G(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);
let n = e[t], s = this.kernelSize.concat([n, this.depthMultiplier]), r = [];
for (let o = 0; o < this.rank; ++o)
r.push(1);
r.push(n * this.depthMultiplier, this.filters);
let a = true;
this.depthwiseKernel = this.addWeight("depthwise_kernel", s, "float32", this.depthwiseInitializer, this.depthwiseRegularizer, a, this.depthwiseConstraint), this.pointwiseKernel = this.addWeight("pointwise_kernel", r, "float32", this.pointwiseInitializer, this.pointwiseRegularizer, a, this.pointwiseConstraint), this.useBias ? this.bias = this.addWeight("bias", [this.filters], "float32", this.biasInitializer, this.biasRegularizer, a, this.biasConstraint) : this.bias = null, this.inputSpec = [new Dt({ ndim: this.rank + 2, axes: { [t]: n } })], this.built = true;
}
call(e, t) {
return q(() => {
e = Oe(e);
let n;
if (this.rank === 1)
throw new Fe("1D separable convolution is not implemented yet.");
return this.rank === 2 && (this.dataFormat === "channelsFirst" && (e = Ge(e, [0, 2, 3, 1])), n = F3(e, this.depthwiseKernel.read(), this.pointwiseKernel.read(), this.strides, this.padding, this.dilationRate, "NHWC")), this.useBias && (n = ks(n, this.bias.read(), this.dataFormat)), this.activation != null && (n = this.activation.apply(n)), this.dataFormat === "channelsFirst" && (n = Ge(n, [0, 3, 1, 2])), n;
});
}
getConfig() {
let e = super.getConfig();
return delete e.rank, delete e.kernelInitializer, delete e.kernelRegularizer, delete e.kernelConstraint, e.depthwiseInitializer = yt(this.depthwiseInitializer), e.pointwiseInitializer = yt(this.pointwiseInitializer), e.depthwiseRegularizer = it(this.depthwiseRegularizer), e.pointwiseRegularizer = it(this.pointwiseRegularizer), e.depthwiseConstraint = Ot(this.depthwiseConstraint), e.pointwiseConstraint = Ot(this.pointwiseConstraint), e;
}
};
XI.className = "SeparableConv";
var fy = class extends XI {
constructor(e) {
super(2, e);
}
};
fy.className = "SeparableConv2D";
re.registerClass(fy);
var YI = class extends Xl {
constructor(e) {
super(1, e), YI.verifyArgs(e), this.inputSpec = [{ ndim: 3 }];
}
getConfig() {
let e = super.getConfig();
return delete e.rank, delete e.dataFormat, e;
}
static verifyArgs(e) {
if (typeof e.kernelSize != "number" && !Fb(e.kernelSize, "number", 1, 1))
throw new G(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`);
}
};
var my = YI;
my.className = "Conv1D";
re.registerClass(my);
var gy = class extends He {
constructor(e) {
super(e), typeof e.cropping == "number" ? this.cropping = [[e.cropping, e.cropping], [e.cropping, e.cropping]] : typeof e.cropping[0] == "number" ? this.cropping = [[e.cropping[0], e.cropping[0]], [e.cropping[1], e.cropping[1]]] : this.cropping = e.cropping, this.dataFormat = e.dataFormat === void 0 ? "channelsLast" : e.dataFormat, this.inputSpec = [{ ndim: 4 }];
}
computeOutputShape(e) {
return this.dataFormat === "channelsFirst" ? [e[0], e[1], e[2] - this.cropping[0][0] - this.cropping[0][1], e[3] - this.cropping[1][0] - this.cropping[1][1]] : [e[0], e[1] - this.cropping[0][0] - this.cropping[0][1], e[2] - this.cropping[1][0] - this.cropping[1][1], e[3]];
}
call(e, t) {
return q(() => {
if (e = Oe(e), this.dataFormat === "channelsLast") {
let n = Yc(e, this.cropping[0][0], e.shape[1] - this.cropping[0][0] - this.cropping[0][1], 2);
return Yc(n, this.cropping[1][0], e.shape[2] - this.cropping[1][1] - this.cropping[1][0], 3);
} else {
let n = Yc(e, this.cropping[0][0], e.shape[2] - this.cropping[0][0] - this.cropping[0][1], 3);
return Yc(n, this.cropping[1][0], e.shape[3] - this.cropping[1][1] - this.cropping[1][0], 4);
}
});
}
getConfig() {
let e = { cropping: this.cropping, dataFormat: this.dataFormat }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
gy.className = "Cropping2D";
re.registerClass(gy);
var by = class extends He {
constructor(e) {
super(e), this.DEFAULT_SIZE = [2, 2], this.inputSpec = [{ ndim: 4 }], this.size = e.size == null ? this.DEFAULT_SIZE : e.size, this.dataFormat = e.dataFormat == null ? "channelsLast" : e.dataFormat, Ct(this.dataFormat), this.interpolation = e.interpolation == null ? "nearest" : e.interpolation, mz(this.interpolation);
}
computeOutputShape(e) {
if (this.dataFormat === "channelsFirst") {
let t = e[2] == null ? null : this.size[0] * e[2], n = e[3] == null ? null : this.size[1] * e[3];
return [e[0], e[1], t, n];
} else {
let t = e[1] == null ? null : this.size[0] * e[1], n = e[2] == null ? null : this.size[1] * e[2];
return [e[0], t, n, e[3]];
}
}
call(e, t) {
return q(() => {
let n = Oe(e), s = n.shape;
if (this.dataFormat === "channelsFirst") {
n = Ge(n, [0, 2, 3, 1]);
let r = this.size[0] * s[2], a = this.size[1] * s[3], o = this.interpolation === "nearest" ? Kn.resizeNearestNeighbor(n, [r, a]) : Kn.resizeBilinear(n, [r, a]);
return Ge(o, [0, 3, 1, 2]);
} else {
let r = this.size[0] * s[1], a = this.size[1] * s[2];
return this.interpolation === "nearest" ? Kn.resizeNearestNeighbor(n, [r, a]) : Kn.resizeBilinear(n, [r, a]);
}
});
}
getConfig() {
let e = { size: this.size, dataFormat: this.dataFormat, interpolation: this.interpolation }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
by.className = "UpSampling2D";
re.registerClass(by);
function fV(e, t, n = [1, 1], s = "valid", r, a) {
return q(() => {
r == null && (r = vs()), Ct(r);
let o = cy(e, r);
if (e.rank !== 4)
throw new G(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);
if (t.rank !== 4)
throw new G(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);
return o = kp(o, t, n, s === "same" ? "same" : "valid", "NHWC", a), r === "channelsFirst" && (o = Ge(o, [0, 3, 1, 2])), o;
});
}
var yy = class extends dy {
constructor(e) {
super(2, e), this.depthwiseKernel = null, this.depthMultiplier = e.depthMultiplier == null ? 1 : e.depthMultiplier, this.depthwiseInitializer = ft(e.depthwiseInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.depthwiseConstraint = Pt(e.depthwiseConstraint), this.depthwiseRegularizer = mt(e.depthwiseRegularizer);
}
build(e) {
if (e = nt(e), e.length < 4)
throw new G(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);
let t = this.dataFormat === "channelsFirst" ? 1 : 3;
if (e[t] == null || e[t] < 0)
throw new G(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);
let n = e[t], s = [this.kernelSize[0], this.kernelSize[1], n, this.depthMultiplier];
this.depthwiseKernel = this.addWeight("depthwise_kernel", s, null, this.depthwiseInitializer, this.depthwiseRegularizer, true, this.depthwiseConstraint), this.useBias ? this.bias = this.addWeight("bias", [n * this.depthMultiplier], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint) : this.bias = null, this.built = true;
}
call(e, t) {
return q(() => {
e = Oe(e);
let n = fV(e, this.depthwiseKernel.read(), this.strides, this.padding, this.dataFormat, null);
return this.useBias && (n = ks(n, this.bias.read(), this.dataFormat)), this.activation != null && (n = this.activation.apply(n)), n;
});
}
computeOutputShape(e) {
e = nt(e);
let t = this.dataFormat === "channelsFirst" ? e[2] : e[1], n = this.dataFormat === "channelsFirst" ? e[3] : e[2], s = this.dataFormat === "channelsFirst" ? e[1] * this.depthMultiplier : e[3] * this.depthMultiplier, r = bs(t, this.kernelSize[0], this.padding, this.strides[0]), a = bs(n, this.kernelSize[1], this.padding, this.strides[1]);
return this.dataFormat === "channelsFirst" ? [e[0], s, r, a] : [e[0], r, a, s];
}
getConfig() {
let e = super.getConfig();
return e.depthMultiplier = this.depthMultiplier, e.depthwiseInitializer = yt(this.depthwiseInitializer), e.depthwiseRegularizer = it(this.depthwiseRegularizer), e.depthwiseConstraint = Ot(this.depthwiseRegularizer), e;
}
};
yy.className = "DepthwiseConv2D";
re.registerClass(yy);
function QI(e, t, n, s) {
if (Array.isArray(e)) {
if (t != null || n != null)
throw new G("When inputs is an array, neither initialState or constants should be provided");
s != null && (n = e.slice(e.length - s, e.length), e = e.slice(0, e.length - s)), e.length > 1 && (t = e.slice(1, e.length)), e = e[0];
}
function r(a) {
return a == null || Array.isArray(a) ? a : [a];
}
return t = r(t), n = r(n), { inputs: e, initialState: t, constants: n };
}
function ZI(e, t, n, s = false, r, a, o = false, i = false) {
return q(() => {
let u = t.shape.length;
if (u < 3)
throw new G(`Input should be at least 3D, but is ${u}D.`);
let l = [1, 0].concat(ys(2, u));
if (t = Ge(t, l), a != null)
throw new Fe("The rnn() functoin of the deeplearn.js backend does not support constants yet.");
o && console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."), r != null && (r = le(le(r, "bool"), "float32"), r.rank === u - 1 && (r = Pn(r, -1)), r = Ge(r, l)), s && (t = Jn(t, 0), r != null && (r = Jn(r, 0)));
let c = [], p, d = n, h = t.shape[0], f = Fs(t), m;
r != null && (m = Fs(r));
for (let b = 0; b < h; ++b) {
let y = f[b], v = q(() => e(y, d));
if (r == null)
p = v[0], d = v[1];
else {
let x = q(() => {
let k = m[b], I = ge(Zn(k), k), $ = oe(V(v[0], k), V(d[0], I)), R = d.map((E, P) => oe(V(v[1][P], k), V(E, I)));
return { output: $, newStates: R };
});
p = x.output, d = x.newStates;
}
i && c.push(p);
}
let g;
return i && (g = es(c, 1)), [p, g, d];
});
}
var JI = class extends He {
constructor(e) {
super(e);
let t;
if (e.cell == null)
throw new G("cell property is missing for the constructor of RNN.");
if (Array.isArray(e.cell) ? t = new Yp({ cells: e.cell }) : t = e.cell, t.stateSize == null)
throw new G("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");
this.cell = t, this.returnSequences = e.returnSequences == null ? false : e.returnSequences, this.returnState = e.returnState == null ? false : e.returnState, this.goBackwards = e.goBackwards == null ? false : e.goBackwards, this._stateful = e.stateful == null ? false : e.stateful, this.unroll = e.unroll == null ? false : e.unroll, this.supportsMasking = true, this.inputSpec = [new Dt({ ndim: 3 })], this.stateSpec = null, this.states_ = null, this.numConstants = null, this.keptStates = [];
}
getStates() {
if (this.states_ == null) {
let e = Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;
return ys(0, e).map((t) => null);
} else
return this.states_;
}
setStates(e) {
this.states_ = e;
}
computeOutputShape(e) {
Am(e) && (e = e[0]), e = e;
let t = this.cell.stateSize;
Array.isArray(t) || (t = [t]);
let n = t[0], s;
if (this.returnSequences ? s = [e[0], e[1], n] : s = [e[0], n], this.returnState) {
let r = [];
for (let a of t)
r.push([e[0], a]);
return [s].concat(r);
} else
return s;
}
computeMask(e, t) {
return q(() => {
Array.isArray(t) && (t = t[0]);
let n = this.returnSequences ? t : null;
if (this.returnState) {
let s = this.states.map((r) => null);
return [n].concat(s);
} else
return n;
});
}
get states() {
if (this.states_ == null) {
let e = Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1, t = [];
for (let n = 0; n < e; ++n)
t.push(null);
return t;
} else
return this.states_;
}
set states(e) {
this.states_ = e;
}
build(e) {
if (this.numConstants != null)
throw new Fe("Constants support is not implemented in RNN yet.");
Am(e) && (e = e[0]), e = e;
let n = this.stateful ? e[0] : null, s = e.slice(2);
this.inputSpec[0] = new Dt({ shape: [n, null, ...s] });
let r = [e[0]].concat(e.slice(2));
this.cell.build(r);
let a;
if (Array.isArray(this.cell.stateSize) ? a = this.cell.stateSize : a = [this.cell.stateSize], this.stateSpec != null) {
if (!w.arraysEqual(this.stateSpec.map((o) => o.shape[o.shape.length - 1]), a))
throw new G(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`);
} else
this.stateSpec = a.map((o) => new Dt({ shape: [null, o] }));
this.stateful && this.resetStates();
}
resetStates(e, t = false) {
q(() => {
if (!this.stateful)
throw new Bs("Cannot call resetStates() on an RNN Layer that is not stateful.");
let n = this.inputSpec[0].shape[0];
if (n == null)
throw new G("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");
if (this.states_ == null)
Array.isArray(this.cell.stateSize) ? this.states_ = this.cell.stateSize.map((s) => $t([n, s])) : this.states_ = [$t([n, this.cell.stateSize])];
else if (e == null)
De(this.states_), this.keptStates != null && (De(this.keptStates), this.keptStates = []), Array.isArray(this.cell.stateSize) ? this.states_ = this.cell.stateSize.map((s) => $t([n, s])) : this.states_[0] = $t([n, this.cell.stateSize]);
else {
if (Array.isArray(e) || (e = [e]), e.length !== this.states_.length)
throw new G(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);
t === true ? this.keptStates.push(this.states_.slice()) : De(this.states_);
for (let s = 0; s < this.states_.length; ++s) {
let r = e[s], a = Array.isArray(this.cell.stateSize) ? this.cell.stateSize[s] : this.cell.stateSize, o = [n, a];
if (!w.arraysEqual(r.shape, o))
throw new G(`State ${s} is incompatible with layer ${this.name}: expected shape=${o}, received shape=${r.shape}`);
this.states_[s] = r;
}
}
this.states_ = this.states_.map((s) => qt(s.clone()));
});
}
apply(e, t) {
let n = t == null ? null : t.initialState, s = t == null ? null : t.constants;
t == null && (t = {});
let r = QI(e, n, s, this.numConstants);
e = r.inputs, n = r.initialState, s = r.constants;
let a = [], o = [];
if (n != null) {
t.initialState = n, a = a.concat(n), this.stateSpec = [];
for (let u of n)
this.stateSpec.push(new Dt({ shape: u.shape }));
o = o.concat(this.stateSpec);
}
if (s != null && (t.constants = s, a = a.concat(s), this.numConstants = s.length), a[0] instanceof $s) {
let u = [e].concat(a), l = this.inputSpec.concat(o), c = this.inputSpec;
this.inputSpec = l;
let p = super.apply(u, t);
return this.inputSpec = c, p;
} else
return super.apply(e, t);
}
call(e, t) {
return q(() => {
let n = t == null ? null : t.mask, s = t == null ? null : t.training, r = t == null ? null : t.initialState;
e = Oe(e), r == null && (this.stateful ? r = this.states_ : r = this.getInitialState(e));
let a = Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;
if (r.length !== a)
throw new G(`RNN Layer has ${a} state(s) but was passed ${r.length} initial state(s).`);
this.unroll && console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");
let o = { training: s }, u = ZI((h, f) => {
let m = this.cell.call([h].concat(f), o);
return [m[0], m.slice(1)];
}, e, r, this.goBackwards, n, null, this.unroll, this.returnSequences), l = u[0], c = u[1], p = u[2];
this.stateful && this.resetStates(p, s);
let d = this.returnSequences ? c : l;
return this.returnState ? [d].concat(p) : d;
});
}
getInitialState(e) {
return q(() => {
let t = $t(e.shape);
return t = ve(t, [1, 2]), t = Gl(t), Array.isArray(this.cell.stateSize) ? this.cell.stateSize.map((n) => n > 1 ? $m(t, [1, n]) : t) : this.cell.stateSize > 1 ? [$m(t, [1, this.cell.stateSize])] : [t];
});
}
get trainableWeights() {
return this.trainable ? this.cell.trainableWeights : [];
}
get nonTrainableWeights() {
return this.trainable ? this.cell.nonTrainableWeights : this.cell.weights;
}
setFastWeightInitDuringBuild(e) {
super.setFastWeightInitDuringBuild(e), this.cell != null && this.cell.setFastWeightInitDuringBuild(e);
}
getConfig() {
let e = super.getConfig(), t = { returnSequences: this.returnSequences, returnState: this.returnState, goBackwards: this.goBackwards, stateful: this.stateful, unroll: this.unroll };
this.numConstants != null && (t.numConstants = this.numConstants);
let n = this.cell.getConfig();
return this.getClassName() === JI.className && (t.cell = { className: this.cell.getClassName(), config: n }), { ...n, ...e, ...t };
}
static fromConfig(e, t, n = {}) {
let s = t.cell, r = gs(s, n);
return new e(Object.assign(t, { cell: r }));
}
};
var Rr = JI;
Rr.className = "RNN";
re.registerClass(Rr);
var Yl = class extends He {
};
var Kp = class extends Yl {
constructor(e) {
super(e), this.DEFAULT_ACTIVATION = "tanh", this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", this.DEFAULT_RECURRENT_INITIALIZER = "orthogonal", this.DEFAULT_BIAS_INITIALIZER = "zeros", this.units = e.units, Bt(this.units, "units"), this.activation = xr(e.activation == null ? this.DEFAULT_ACTIVATION : e.activation), this.useBias = e.useBias == null ? true : e.useBias, this.kernelInitializer = ft(e.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.recurrentInitializer = ft(e.recurrentInitializer || this.DEFAULT_RECURRENT_INITIALIZER), this.biasInitializer = ft(e.biasInitializer || this.DEFAULT_BIAS_INITIALIZER), this.kernelRegularizer = mt(e.kernelRegularizer), this.recurrentRegularizer = mt(e.recurrentRegularizer), this.biasRegularizer = mt(e.biasRegularizer), this.kernelConstraint = Pt(e.kernelConstraint), this.recurrentConstraint = Pt(e.recurrentConstraint), this.biasConstraint = Pt(e.biasConstraint), this.dropout = ni([1, yr([0, e.dropout == null ? 0 : e.dropout])]), this.recurrentDropout = ni([1, yr([0, e.recurrentDropout == null ? 0 : e.recurrentDropout])]), this.dropoutFunc = e.dropoutFunc, this.stateSize = this.units, this.dropoutMask = null, this.recurrentDropoutMask = null;
}
build(e) {
e = nt(e), this.kernel = this.addWeight("kernel", [e[e.length - 1], this.units], null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint), this.recurrentKernel = this.addWeight("recurrent_kernel", [this.units, this.units], null, this.recurrentInitializer, this.recurrentRegularizer, true, this.recurrentConstraint), this.useBias ? this.bias = this.addWeight("bias", [this.units], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint) : this.bias = null, this.built = true;
}
call(e, t) {
return q(() => {
if (e = e, e.length !== 2)
throw new G(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);
let n = e[1];
e = e[0];
let s = t.training == null ? false : t.training;
0 < this.dropout && this.dropout < 1 && this.dropoutMask == null && (this.dropoutMask = wr({ ones: () => Zn(e), rate: this.dropout, training: s, dropoutFunc: this.dropoutFunc })), 0 < this.recurrentDropout && this.recurrentDropout < 1 && this.recurrentDropoutMask == null && (this.recurrentDropoutMask = wr({ ones: () => Zn(n), rate: this.recurrentDropout, training: s, dropoutFunc: this.dropoutFunc }));
let r, a = this.dropoutMask, o = this.recurrentDropoutMask;
a != null ? r = Es(V(e, a), this.kernel.read()) : r = Es(e, this.kernel.read()), this.bias != null && (r = ks(r, this.bias.read())), o != null && (n = V(n, o));
let i = oe(r, Es(n, this.recurrentKernel.read()));
return this.activation != null && (i = this.activation.apply(i)), [i, i];
});
}
getConfig() {
let e = super.getConfig(), t = { units: this.units, activation: vr(this.activation), useBias: this.useBias, kernelInitializer: yt(this.kernelInitializer), recurrentInitializer: yt(this.recurrentInitializer), biasInitializer: yt(this.biasInitializer), kernelRegularizer: it(this.kernelRegularizer), recurrentRegularizer: it(this.recurrentRegularizer), biasRegularizer: it(this.biasRegularizer), activityRegularizer: it(this.activityRegularizer), kernelConstraint: Ot(this.kernelConstraint), recurrentConstraint: Ot(this.recurrentConstraint), biasConstraint: Ot(this.biasConstraint), dropout: this.dropout, recurrentDropout: this.recurrentDropout };
return { ...e, ...t };
}
};
Kp.className = "SimpleRNNCell";
re.registerClass(Kp);
var vy = class extends Rr {
constructor(e) {
e.cell = new Kp(e), super(e);
}
call(e, t) {
return q(() => {
this.cell.dropoutMask != null && (De(this.cell.dropoutMask), this.cell.dropoutMask = null), this.cell.recurrentDropoutMask != null && (De(this.cell.recurrentDropoutMask), this.cell.recurrentDropoutMask = null);
let n = t == null ? null : t.mask, s = t == null ? null : t.training, r = t == null ? null : t.initialState;
return super.call(e, { mask: n, training: s, initialState: r });
});
}
static fromConfig(e, t) {
return new e(t);
}
};
vy.className = "SimpleRNN";
re.registerClass(vy);
var Xp = class extends Yl {
constructor(e) {
if (super(e), this.DEFAULT_ACTIVATION = "tanh", this.DEFAULT_RECURRENT_ACTIVATION = "hardSigmoid", this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", this.DEFAULT_RECURRENT_INITIALIZER = "orthogonal", this.DEFAULT_BIAS_INITIALIZER = "zeros", e.resetAfter)
throw new G("GRUCell does not support reset_after parameter set to true.");
this.units = e.units, Bt(this.units, "units"), this.activation = xr(e.activation === void 0 ? this.DEFAULT_ACTIVATION : e.activation), this.recurrentActivation = xr(e.recurrentActivation === void 0 ? this.DEFAULT_RECURRENT_ACTIVATION : e.recurrentActivation), this.useBias = e.useBias == null ? true : e.useBias, this.kernelInitializer = ft(e.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.recurrentInitializer = ft(e.recurrentInitializer || this.DEFAULT_RECURRENT_INITIALIZER), this.biasInitializer = ft(e.biasInitializer || this.DEFAULT_BIAS_INITIALIZER), this.kernelRegularizer = mt(e.kernelRegularizer), this.recurrentRegularizer = mt(e.recurrentRegularizer), this.biasRegularizer = mt(e.biasRegularizer), this.kernelConstraint = Pt(e.kernelConstraint), this.recurrentConstraint = Pt(e.recurrentConstraint), this.biasConstraint = Pt(e.biasConstraint), this.dropout = ni([1, yr([0, e.dropout == null ? 0 : e.dropout])]), this.recurrentDropout = ni([1, yr([0, e.recurrentDropout == null ? 0 : e.recurrentDropout])]), this.dropoutFunc = e.dropoutFunc, this.implementation = e.implementation, this.stateSize = this.units, this.dropoutMask = null, this.recurrentDropoutMask = null;
}
build(e) {
e = nt(e);
let t = e[e.length - 1];
this.kernel = this.addWeight("kernel", [t, this.units * 3], null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint), this.recurrentKernel = this.addWeight("recurrent_kernel", [this.units, this.units * 3], null, this.recurrentInitializer, this.recurrentRegularizer, true, this.recurrentConstraint), this.useBias ? this.bias = this.addWeight("bias", [this.units * 3], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint) : this.bias = null, this.built = true;
}
call(e, t) {
return q(() => {
if (e = e, e.length !== 2)
throw new G(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);
let n = t.training == null ? false : t.training, s = e[1];
e = e[0], 0 < this.dropout && this.dropout < 1 && this.dropoutMask == null && (this.dropoutMask = wr({ ones: () => Zn(e), rate: this.dropout, training: n, count: 3, dropoutFunc: this.dropoutFunc })), 0 < this.recurrentDropout && this.recurrentDropout < 1 && this.recurrentDropoutMask == null && (this.recurrentDropoutMask = wr({ ones: () => Zn(s), rate: this.recurrentDropout, training: n, count: 3, dropoutFunc: this.dropoutFunc }));
let r = this.dropoutMask, a = this.recurrentDropoutMask, o, i, u;
0 < this.dropout && this.dropout < 1 && (e = V(e, r[0]));
let l = Es(e, this.kernel.read());
this.useBias && (l = ks(l, this.bias.read())), 0 < this.recurrentDropout && this.recurrentDropout < 1 && (s = V(s, a[0]));
let c = this.recurrentKernel.read(), [p, d] = Bn(c, [2 * this.units, this.units], c.rank - 1), h = Es(s, p), [f, m, g] = Bn(l, 3, l.rank - 1), [b, y] = Bn(h, 2, h.rank - 1);
o = this.recurrentActivation.apply(oe(f, b)), i = this.recurrentActivation.apply(oe(m, y));
let v = Es(V(i, s), d);
u = this.activation.apply(oe(g, v));
let x = oe(V(o, s), V(oe(1, vt(o)), u));
return [x, x];
});
}
getConfig() {
let e = super.getConfig(), t = { units: this.units, activation: vr(this.activation), recurrentActivation: vr(this.recurrentActivation), useBias: this.useBias, kernelInitializer: yt(this.kernelInitializer), recurrentInitializer: yt(this.recurrentInitializer), biasInitializer: yt(this.biasInitializer), kernelRegularizer: it(this.kernelRegularizer), recurrentRegularizer: it(this.recurrentRegularizer), biasRegularizer: it(this.biasRegularizer), activityRegularizer: it(this.activityRegularizer), kernelConstraint: Ot(this.kernelConstraint), recurrentConstraint: Ot(this.recurrentConstraint), biasConstraint: Ot(this.biasConstraint), dropout: this.dropout, recurrentDropout: this.recurrentDropout, implementation: this.implementation, resetAfter: false };
return { ...e, ...t };
}
};
Xp.className = "GRUCell";
re.registerClass(Xp);
var xy = class extends Rr {
constructor(e) {
e.implementation === 0 && console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."), e.cell = new Xp(e), super(e);
}
call(e, t) {
return q(() => {
this.cell.dropoutMask != null && (De(this.cell.dropoutMask), this.cell.dropoutMask = null), this.cell.recurrentDropoutMask != null && (De(this.cell.recurrentDropoutMask), this.cell.recurrentDropoutMask = null);
let n = t == null ? null : t.mask, s = t == null ? null : t.training, r = t == null ? null : t.initialState;
return super.call(e, { mask: n, training: s, initialState: r });
});
}
static fromConfig(e, t) {
return t.implmentation === 0 && (t.implementation = 1), new e(t);
}
};
xy.className = "GRU";
re.registerClass(xy);
var Ql = class extends Yl {
constructor(e) {
super(e), this.DEFAULT_ACTIVATION = "tanh", this.DEFAULT_RECURRENT_ACTIVATION = "hardSigmoid", this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", this.DEFAULT_RECURRENT_INITIALIZER = "orthogonal", this.DEFAULT_BIAS_INITIALIZER = "zeros", this.units = e.units, Bt(this.units, "units"), this.activation = xr(e.activation === void 0 ? this.DEFAULT_ACTIVATION : e.activation), this.recurrentActivation = xr(e.recurrentActivation === void 0 ? this.DEFAULT_RECURRENT_ACTIVATION : e.recurrentActivation), this.useBias = e.useBias == null ? true : e.useBias, this.kernelInitializer = ft(e.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.recurrentInitializer = ft(e.recurrentInitializer || this.DEFAULT_RECURRENT_INITIALIZER), this.biasInitializer = ft(e.biasInitializer || this.DEFAULT_BIAS_INITIALIZER), this.unitForgetBias = e.unitForgetBias, this.kernelRegularizer = mt(e.kernelRegularizer), this.recurrentRegularizer = mt(e.recurrentRegularizer), this.biasRegularizer = mt(e.biasRegularizer), this.kernelConstraint = Pt(e.kernelConstraint), this.recurrentConstraint = Pt(e.recurrentConstraint), this.biasConstraint = Pt(e.biasConstraint), this.dropout = ni([1, yr([0, e.dropout == null ? 0 : e.dropout])]), this.recurrentDropout = ni([1, yr([0, e.recurrentDropout == null ? 0 : e.recurrentDropout])]), this.dropoutFunc = e.dropoutFunc, this.implementation = e.implementation, this.stateSize = [this.units, this.units], this.dropoutMask = null, this.recurrentDropoutMask = null;
}
build(e) {
var t;
e = nt(e);
let n = e[e.length - 1];
this.kernel = this.addWeight("kernel", [n, this.units * 4], null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint), this.recurrentKernel = this.addWeight("recurrent_kernel", [this.units, this.units * 4], null, this.recurrentInitializer, this.recurrentRegularizer, true, this.recurrentConstraint);
let s;
if (this.useBias) {
if (this.unitForgetBias) {
let r = this.biasInitializer, a = this.units;
s = new (t = class extends ns {
apply(o, i) {
let u = r.apply([a]), l = new Pp().apply([a]), c = r.apply([a * 2]);
return Ex(Ex(u, l), c);
}
}, t.className = "CustomInit", t)();
} else
s = this.biasInitializer;
this.bias = this.addWeight("bias", [this.units * 4], null, s, this.biasRegularizer, true, this.biasConstraint);
} else
this.bias = null;
this.built = true;
}
call(e, t) {
return q(() => {
let n = t.training == null ? false : t.training;
if (e = e, e.length !== 3)
throw new G(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);
let s = e[1], r = e[2];
e = e[0], 0 < this.dropout && this.dropout < 1 && this.dropoutMask == null && (this.dropoutMask = wr({ ones: () => Zn(e), rate: this.dropout, training: n, count: 4, dropoutFunc: this.dropoutFunc })), 0 < this.recurrentDropout && this.recurrentDropout < 1 && this.recurrentDropoutMask == null && (this.recurrentDropoutMask = wr({ ones: () => Zn(s), rate: this.recurrentDropout, training: n, count: 4, dropoutFunc: this.dropoutFunc }));
let a = this.dropoutMask, o = this.recurrentDropoutMask, i, u, l, c;
0 < this.dropout && this.dropout < 1 && (e = V(e, a[0]));
let p = Es(e, this.kernel.read());
0 < this.recurrentDropout && this.recurrentDropout < 1 && (s = V(s, o[0])), p = oe(p, Es(s, this.recurrentKernel.read())), this.useBias && (p = ks(p, this.bias.read()));
let [d, h, f, m] = Bn(p, 4, p.rank - 1);
i = this.recurrentActivation.apply(d), u = this.recurrentActivation.apply(h), l = oe(V(u, r), V(i, this.activation.apply(f))), c = this.recurrentActivation.apply(m);
let g = V(c, this.activation.apply(l));
return [g, g, l];
});
}
getConfig() {
let e = super.getConfig(), t = { units: this.units, activation: vr(this.activation), recurrentActivation: vr(this.recurrentActivation), useBias: this.useBias, kernelInitializer: yt(this.kernelInitializer), recurrentInitializer: yt(this.recurrentInitializer), biasInitializer: yt(this.biasInitializer), unitForgetBias: this.unitForgetBias, kernelRegularizer: it(this.kernelRegularizer), recurrentRegularizer: it(this.recurrentRegularizer), biasRegularizer: it(this.biasRegularizer), activityRegularizer: it(this.activityRegularizer), kernelConstraint: Ot(this.kernelConstraint), recurrentConstraint: Ot(this.recurrentConstraint), biasConstraint: Ot(this.biasConstraint), dropout: this.dropout, recurrentDropout: this.recurrentDropout, implementation: this.implementation };
return { ...e, ...t };
}
};
Ql.className = "LSTMCell";
re.registerClass(Ql);
var wy = class extends Rr {
constructor(e) {
e.implementation === 0 && console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."), e.cell = new Ql(e), super(e);
}
call(e, t) {
return q(() => {
this.cell.dropoutMask != null && (De(this.cell.dropoutMask), this.cell.dropoutMask = null), this.cell.recurrentDropoutMask != null && (De(this.cell.recurrentDropoutMask), this.cell.recurrentDropoutMask = null);
let n = t == null ? null : t.mask, s = t == null ? null : t.training, r = t == null ? null : t.initialState;
return super.call(e, { mask: n, training: s, initialState: r });
});
}
static fromConfig(e, t) {
return t.implmentation === 0 && (t.implementation = 1), new e(t);
}
};
wy.className = "LSTM";
re.registerClass(wy);
var Yp = class extends Yl {
constructor(e) {
super(e), this.cells = e.cells;
}
get stateSize() {
let e = [];
for (let t of this.cells.slice().reverse())
Array.isArray(t.stateSize) ? e.push(...t.stateSize) : e.push(t.stateSize);
return e;
}
call(e, t) {
return q(() => {
e = e;
let n = e.slice(1), s = [];
for (let o of this.cells.slice().reverse())
Array.isArray(o.stateSize) ? s.push(n.splice(0, o.stateSize.length)) : s.push(n.splice(0, 1));
s.reverse();
let r = [], a;
for (let o = 0; o < this.cells.length; ++o) {
let i = this.cells[o];
n = s[o], o === 0 ? a = [e[0]].concat(n) : a = [a[0]].concat(n), a = i.call(a, t), r.push(a.slice(1));
}
n = [];
for (let o of r.slice().reverse())
n.push(...o);
return [a[0]].concat(n);
});
}
build(e) {
Am(e) && (e = e[0]), e = e;
let t;
this.cells.forEach((n, s) => {
na(`RNNCell_${s}`, () => {
n.build(e), Array.isArray(n.stateSize) ? t = n.stateSize[0] : t = n.stateSize, e = [e[0], t];
});
}), this.built = true;
}
getConfig() {
let e = super.getConfig(), t = (r) => ({ className: r.getClassName(), config: r.getConfig() }), s = { cells: this.cells.map(t) };
return { ...e, ...s };
}
static fromConfig(e, t, n = {}) {
let s = [];
for (let r of t.cells)
s.push(gs(r, n));
return new e({ cells: s });
}
get trainableWeights() {
if (!this.trainable)
return [];
let e = [];
for (let t of this.cells)
e.push(...t.trainableWeights);
return e;
}
get nonTrainableWeights() {
let e = [];
for (let t of this.cells)
e.push(...t.nonTrainableWeights);
if (!this.trainable) {
let t = [];
for (let n of this.cells)
t.push(...n.trainableWeights);
return t.concat(e);
}
return e;
}
getWeights() {
let e = [];
for (let t of this.cells)
e.push(...t.weights);
return Em(e);
}
setWeights(e) {
let t = [];
for (let n of this.cells) {
let s = n.weights.length, r = e.splice(s);
for (let a = 0; a < n.weights.length; ++a)
t.push([n.weights[a], r[a]]);
}
Ub(t);
}
};
Yp.className = "StackedRNNCells";
re.registerClass(Yp);
function wr(e) {
let { ones: t, rate: n, training: s = false, count: r = 1, dropoutFunc: a } = e, o = () => a != null ? a(t(), n) : pI(t(), n), i = () => ql(o, t, s);
return !r || r <= 1 ? qt(i().clone()) : Array(r).fill(void 0).map(i).map((l) => qt(l.clone()));
}
var e0 = class extends Rr {
constructor(e) {
if (e.unroll)
throw new Fe("Unrolling is not possible with convolutional RNNs.");
if (Array.isArray(e.cell))
throw new Fe("It is not possible at the moment to stack convolutional cells.");
super(e), this.inputSpec = [new Dt({ ndim: 5 })];
}
call(e, t) {
return q(() => {
if (this.cell.dropoutMask != null && (De(this.cell.dropoutMask), this.cell.dropoutMask = null), this.cell.recurrentDropoutMask != null && (De(this.cell.recurrentDropoutMask), this.cell.recurrentDropoutMask = null), t && t.constants)
throw new G("ConvRNN2D cell does not support constants");
let n = t == null ? null : t.mask, s = t == null ? null : t.training, r = t == null ? null : t.initialState;
return super.call(e, { mask: n, training: s, initialState: r });
});
}
computeOutputShape(e) {
let t = this.computeSingleOutputShape(e);
return this.returnSequences || (t = [t[0], ...t.slice(2)]), this.returnState && (t = [t, ...Array(2).fill([e[0], ...t.slice(-3)])]), t;
}
getInitialState(e) {
return q(() => {
let { stateSize: t } = this.cell, n = e.shape, s = this.computeSingleOutputShape(n), r = [s[0], ...s.slice(2)], a = $t(r);
return Array.isArray(t) ? Array(t.length).fill(a) : [a];
});
}
resetStates(e, t = false) {
q(() => {
if (!this.stateful)
throw new Bs("Cannot call resetStates() on an RNN Layer that is not stateful.");
let n = this.inputSpec[0].shape, s = this.computeSingleOutputShape(n), r = [s[0], ...s.slice(2)];
if (n[0] == null)
throw new G("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");
if (this.getStates() == null)
Array.isArray(this.cell.stateSize) ? this.states_ = this.cell.stateSize.map(() => $t(r)) : this.states_ = [$t(r)];
else if (e == null)
De(this.states_), this.keptStates != null && (De(this.keptStates), this.keptStates = []), Array.isArray(this.cell.stateSize) ? this.states_ = this.cell.stateSize.map(() => $t(r)) : this.states_[0] = $t(r);
else {
if (Array.isArray(e) || (e = [e]), e.length !== this.states_.length)
throw new G(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);
t ? this.keptStates.push(this.states_.slice()) : De(this.states_);
for (let o = 0; o < this.states_.length; ++o) {
let i = e[o], u = r;
if (!w.arraysEqual(i.shape, u))
throw new G(`State ${o} is incompatible with layer ${this.name}: expected shape=${u}, received shape=${i.shape}`);
this.states_[o] = i;
}
}
this.states_ = this.states_.map((o) => qt(o.clone()));
});
}
computeSingleOutputShape(e) {
let { dataFormat: t, filters: n, kernelSize: s, padding: r, strides: a, dilationRate: o } = this.cell, i = t === "channelsFirst", u = e[i ? 3 : 2], l = e[i ? 4 : 3], c = bs(u, s[0], r, a[0], o[0]), p = bs(l, s[1], r, a[1], o[1]);
return [...e.slice(0, 2), ...i ? [n, c, p] : [c, p, n]];
}
};
e0.className = "ConvRNN2D";
var Qp = class extends Ql {
constructor(e) {
let { filters: t, kernelSize: n, strides: s, padding: r, dataFormat: a, dilationRate: o } = e;
super({ ...e, units: t }), this.filters = t, Bt(this.filters, "filters"), this.kernelSize = Jo(n, 2, "kernelSize"), this.kernelSize.forEach((i) => Bt(i, "kernelSize")), this.strides = Jo(s || 1, 2, "strides"), this.strides.forEach((i) => Bt(i, "strides")), this.padding = r || "valid", Hn(this.padding), this.dataFormat = a || "channelsLast", Ct(this.dataFormat), this.dilationRate = Jo(o || 1, 2, "dilationRate"), this.dilationRate.forEach((i) => Bt(i, "dilationRate"));
}
build(e) {
var t;
e = nt(e);
let n = this.dataFormat === "channelsFirst" ? 1 : e.length - 1;
if (e[n] == null)
throw new G(`The channel dimension of the input should be defined. Found ${e[n]}`);
let s = e[n], r = 4, a = this.kernelSize.concat([s, this.filters * r]);
this.kernel = this.addWeight("kernel", a, null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint);
let o = this.kernelSize.concat([this.filters, this.filters * r]);
if (this.recurrentKernel = this.addWeight("recurrent_kernel", o, null, this.recurrentInitializer, this.recurrentRegularizer, true, this.recurrentConstraint), this.useBias) {
let i;
if (this.unitForgetBias) {
let u = this.biasInitializer, l = this.filters;
i = new (t = class extends ns {
apply(c, p) {
let d = u.apply([l]), h = Ln([l]), f = u.apply([l * 2]);
return Ob([d, h, f]);
}
}, t.className = "CustomInit", t)();
} else
i = this.biasInitializer;
this.bias = this.addWeight("bias", [this.filters * r], null, i, this.biasRegularizer, true, this.biasConstraint);
}
this.built = true;
}
call(e, t) {
return q(() => {
if (e.length !== 3)
throw new G(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);
let n = t.training || false, s = e[0], r = e[1], a = e[2], o = 4;
0 < this.dropout && this.dropout < 1 && this.dropoutMask == null && (this.dropoutMask = wr({ ones: () => Zn(s), rate: this.dropout, training: n, count: o, dropoutFunc: this.dropoutFunc }));
let i = this.dropoutMask, u = (Z, ne, ee) => !ne || !ne[ee] ? Z : V(ne[ee], Z), l = u(s, i, 0), c = u(s, i, 1), p = u(s, i, 2), d = u(s, i, 3);
0 < this.recurrentDropout && this.recurrentDropout < 1 && this.recurrentDropoutMask == null && (this.recurrentDropoutMask = wr({ ones: () => Zn(r), rate: this.recurrentDropout, training: n, count: o, dropoutFunc: this.dropoutFunc }));
let h = this.recurrentDropoutMask, f = u(r, h, 0), m = u(r, h, 1), g = u(r, h, 2), b = u(r, h, 3), y = 3, [v, x, k, I] = Bn(this.kernel.read(), o, y), [$, R, E, P] = this.useBias ? Bn(this.bias.read(), o) : [null, null, null, null];
l = this.inputConv(l, v, $, this.padding), c = this.inputConv(c, x, R, this.padding), p = this.inputConv(p, k, E, this.padding), d = this.inputConv(d, I, P, this.padding);
let [A, D, T, L] = Bn(this.recurrentKernel.read(), o, y);
f = this.recurrentConv(f, A), m = this.recurrentConv(m, D), g = this.recurrentConv(g, T), b = this.recurrentConv(b, L);
let W = this.recurrentActivation.apply(oe(l, f)), j = this.recurrentActivation.apply(oe(c, m)), Y = oe(V(j, a), V(W, this.activation.apply(oe(p, g)))), X = V(this.recurrentActivation.apply(oe(d, b)), this.activation.apply(Y));
return [X, X, Y];
});
}
getConfig() {
let { units: e, ...t } = super.getConfig(), n = { filters: this.filters, kernelSize: this.kernelSize, padding: this.padding, dataFormat: this.dataFormat, dilationRate: this.dilationRate, strides: this.strides };
return { ...t, ...n };
}
inputConv(e, t, n, s) {
let r = da(e, t, this.strides, s || "valid", this.dataFormat === "channelsFirst" ? "NCHW" : "NHWC", this.dilationRate);
return n ? ks(r, n, this.dataFormat) : r;
}
recurrentConv(e, t) {
return da(e, t, 1, "same", this.dataFormat === "channelsFirst" ? "NCHW" : "NHWC");
}
};
Qp.className = "ConvLSTM2DCell";
re.registerClass(Qp);
var ky = class extends e0 {
constructor(e) {
let t = new Qp(e);
super({ ...e, cell: t });
}
static fromConfig(e, t) {
return new e(t);
}
};
ky.className = "ConvLSTM2D";
re.registerClass(ky);
var Zp = class extends He {
constructor(e) {
super(e), this.rate = Math.max(Math.min(e.rate, 1), 0), this.noiseShape = e.noiseShape, this.seed = e.seed, this.supportsMasking = true;
}
getNoiseShape(e) {
if (this.noiseShape == null)
return this.noiseShape;
let t = e.shape, n = [];
for (let s = 0; s < this.noiseShape.length; ++s)
n.push(this.noiseShape[s] == null ? t[s] : this.noiseShape[s]);
return n;
}
call(e, t) {
return q(() => {
this.invokeCallHook(e, t);
let n = Oe(e);
if (0 < this.rate && this.rate < 1) {
let s = t.training == null ? false : t.training, r = this.getNoiseShape(n);
return ql(() => pI(n, this.rate, r, this.seed), () => n, s);
}
return e;
});
}
getConfig() {
let e = { rate: this.rate, noiseShape: this.noiseShape, seed: this.seed }, t = super.getConfig();
return Object.assign(e, t), e;
}
dispose() {
return super.dispose();
}
};
Zp.className = "Dropout";
re.registerClass(Zp);
var Sy = class extends Zp {
constructor(e) {
super(e), this.inputSpec = [{ ndim: 3 }];
}
getNoiseShape(e) {
let t = e.shape;
return [t[0], 1, t[2]];
}
};
Sy.className = "SpatialDropout1D";
re.registerClass(Sy);
var Iy = class extends He {
constructor(e) {
if (super(e), this.activation = null, this.useBias = true, this.kernel = null, this.bias = null, this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", this.DEFAULT_BIAS_INITIALIZER = "zeros", e.batchInputShape == null && e.inputShape == null && e.inputDim != null) {
let t = null;
e.batchSize != null && (t = e.batchSize), this.batchInputShape = [t, e.inputDim];
}
this.units = e.units, Bt(this.units, "units"), this.activation = xr(e.activation), e.useBias != null && (this.useBias = e.useBias), this.kernelInitializer = ft(e.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.biasInitializer = ft(e.biasInitializer || this.DEFAULT_BIAS_INITIALIZER), this.kernelConstraint = Pt(e.kernelConstraint), this.biasConstraint = Pt(e.biasConstraint), this.kernelRegularizer = mt(e.kernelRegularizer), this.biasRegularizer = mt(e.biasRegularizer), this.activityRegularizer = mt(e.activityRegularizer), this.supportsMasking = true, this.inputSpec = [{ minNDim: 2 }];
}
build(e) {
e = nt(e);
let t = e[e.length - 1];
this.kernel == null && (this.kernel = this.addWeight("kernel", [t, this.units], null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint), this.useBias && (this.bias = this.addWeight("bias", [this.units], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint))), this.inputSpec = [{ minNDim: 2, axes: { [-1]: t } }], this.built = true;
}
computeOutputShape(e) {
e = nt(e);
let t = e.slice();
return t[t.length - 1] = this.units, t;
}
call(e, t) {
return q(() => {
this.invokeCallHook(e, t);
let n = Oe(e), s = aI(this.activation.getClassName()), r;
return s != null ? r = Es(n, this.kernel.read(), s, this.bias ? this.bias.read() : null) : (r = Es(n, this.kernel.read()), this.bias != null && (r = ks(r, this.bias.read())), this.activation != null && (r = this.activation.apply(r))), r;
});
}
getConfig() {
let e = { units: this.units, activation: vr(this.activation), useBias: this.useBias, kernelInitializer: yt(this.kernelInitializer), biasInitializer: yt(this.biasInitializer), kernelRegularizer: it(this.kernelRegularizer), biasRegularizer: it(this.biasRegularizer), activityRegularizer: it(this.activityRegularizer), kernelConstraint: Ot(this.kernelConstraint), biasConstraint: Ot(this.biasConstraint) }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Iy.className = "Dense";
re.registerClass(Iy);
var Cy = class extends He {
constructor(e) {
e = e || {}, super(e), this.inputSpec = [{ minNDim: 3 }], this.dataFormat = e.dataFormat;
}
computeOutputShape(e) {
e = nt(e);
for (let t of e.slice(1))
if (t == null)
throw new G(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);
return [e[0], dr(e, 1)];
}
call(e, t) {
return q(() => {
this.invokeCallHook(e, t);
let n = Oe(e);
if (this.dataFormat === "channelsFirst" && n.rank > 1) {
let s = [0];
for (let r = 2; r < n.rank; ++r)
s.push(r);
s.push(1), n = Ge(n, s);
}
return wz(n);
});
}
getConfig() {
let e = {};
this.dataFormat != null && (e.dataFormat = this.dataFormat);
let t = super.getConfig();
return Object.assign(e, t), e;
}
};
Cy.className = "Flatten";
re.registerClass(Cy);
var Ny = class extends He {
constructor(e) {
super(e), this.supportsMasking = true, this.activation = xr(e.activation);
}
call(e, t) {
return q(() => {
this.invokeCallHook(e, t);
let n = Oe(e);
return this.activation.apply(n);
});
}
getConfig() {
let e = { activation: vr(this.activation) }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Ny.className = "Activation";
re.registerClass(Ny);
var Ty = class extends He {
constructor(e) {
super(e), this.n = e.n, this.inputSpec = [{ ndim: 2 }];
}
computeOutputShape(e) {
return [e[0], this.n, e[1]];
}
call(e, t) {
return q(() => (e = Oe(e), vz(e, this.n)));
}
getConfig() {
let e = { n: this.n }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Ty.className = "RepeatVector";
re.registerClass(Ty);
var $y = class extends He {
constructor(e) {
super(e), this.targetShape = e.targetShape;
for (let t = 0; t < this.targetShape.length; ++t)
this.isUnknown(this.targetShape[t]) && (this.targetShape[t] = null);
}
isUnknown(e) {
return e < 0 || e == null;
}
fixUnknownDimension(e, t) {
let n = "Total size of new array must be unchanged.", s = t.slice(), r = 1, a = null;
for (let i = 0; i < s.length; ++i) {
let u = s[i];
if (this.isUnknown(u))
if (a === null)
a = i;
else
throw new G("Can only specifiy one unknown dimension.");
else
r *= u;
}
let o = dr(e);
if (a !== null) {
if (r === 0 || o % r !== 0)
throw new G(n);
s[a] = o / r;
} else if (o !== r)
throw new G(n);
return s;
}
computeOutputShape(e) {
let t = false;
for (let n = 0; n < e.length; ++n)
if (this.isUnknown(e[n])) {
t = true;
break;
}
return t ? e.slice(0, 1).concat(this.targetShape) : e.slice(0, 1).concat(this.fixUnknownDimension(e.slice(1), this.targetShape));
}
call(e, t) {
return q(() => {
this.invokeCallHook(e, t);
let n = Oe(e), s = n.shape, r = s.slice(0, 1).concat(this.fixUnknownDimension(s.slice(1), this.targetShape));
return U(n, r);
});
}
getConfig() {
let e = { targetShape: this.targetShape }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
$y.className = "Reshape";
re.registerClass($y);
var _y = class extends He {
constructor(e) {
if (super(e), e.dims == null)
throw new Error("Required configuration field `dims` is missing during Permute constructor call.");
if (!Array.isArray(e.dims))
throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);
let t = ys(1, e.dims.length + 1);
if (!w.arraysEqual(e.dims.slice().sort(), t))
throw new Error("Invalid permutation `dims`: " + JSON.stringify(e.dims) + " `dims` must contain consecutive integers starting from 1.");
this.dims = e.dims, this.dimsIncludingBatch = [0].concat(this.dims), this.inputSpec = [new Dt({ ndim: this.dims.length + 1 })];
}
computeOutputShape(e) {
e = nt(e);
let t = e.slice();
return this.dims.forEach((n, s) => {
t[s + 1] = e[n];
}), t;
}
call(e, t) {
return Ge(Oe(e), this.dimsIncludingBatch);
}
getConfig() {
let e = { dims: this.dims }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
_y.className = "Permute";
re.registerClass(_y);
var Ay = class extends He {
constructor(e) {
super(e == null ? {} : e), this.supportsMasking = true, e != null ? this.maskValue = e.maskValue == null ? 0 : e.maskValue : this.maskValue = 0;
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = super.getConfig(), t = { maskValue: this.maskValue };
return Object.assign(t, e), t;
}
computeMask(e, t) {
let n = Oe(e), s = -1;
return Sm(el(n, this.maskValue), s);
}
call(e, t) {
return q(() => {
this.invokeCallHook(e, t);
let n = Oe(e), s = -1, r = true, a = Sm(el(n, this.maskValue), s, r);
return V(n, le(a, n.dtype));
});
}
};
Ay.className = "Masking";
re.registerClass(Ay);
var Ey = class extends He {
constructor(e) {
if (super(e), this.embeddings = null, this.DEFAULT_EMBEDDINGS_INITIALIZER = "randomUniform", e.batchInputShape == null && e.inputShape == null) {
let t = null;
e.batchSize != null && (t = e.batchSize), e.inputLength == null ? this.batchInputShape = [t, null] : this.batchInputShape = [t].concat(ht(e.inputLength));
}
this.inputDim = e.inputDim, Bt(this.inputDim, "inputDim"), this.outputDim = e.outputDim, Bt(this.outputDim, "outputDim"), this.embeddingsInitializer = ft(e.embeddingsInitializer || this.DEFAULT_EMBEDDINGS_INITIALIZER), this.embeddingsRegularizer = mt(e.embeddingsRegularizer), this.activityRegularizer = mt(e.activityRegularizer), this.embeddingsConstraint = Pt(e.embeddingsConstraint), this.maskZero = e.maskZero, this.supportsMasking = e.maskZero, this.inputLength = e.inputLength;
}
build(e) {
this.embeddings = this.addWeight("embeddings", [this.inputDim, this.outputDim], this.dtype, this.embeddingsInitializer, this.embeddingsRegularizer, true, this.embeddingsConstraint), this.built = true;
}
warnOnIncompatibleInputShape(e) {
}
computeMask(e, t) {
return q(() => this.maskZero ? (e = Oe(e), el(e, je(e))) : null);
}
computeOutputShape(e) {
if (e = nt(e), this.inputLength == null)
return [...e, this.outputDim];
let t = ht(this.inputLength);
if (t.length !== e.length - 1)
throw new G(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);
{
let n = 0;
for (let s = 0; s < t.length; ++s) {
let r = t[s], a = e[s + 1];
if (r != null && a != null && r !== a)
throw new G(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);
r == null && (t[n] = a), n++;
}
}
return [e[0], ...t, this.outputDim];
}
call(e, t) {
return q(() => {
this.invokeCallHook(e, t);
let n = Oe(e);
n.dtype !== "int32" && (n = Fp(n, "int32"));
let s = dI(this.embeddings.read(), U(n, [n.size]));
return U(s, nt(this.computeOutputShape(n.shape)));
});
}
getConfig() {
let e = { inputDim: this.inputDim, outputDim: this.outputDim, embeddingsInitializer: yt(this.embeddingsInitializer), embeddingsRegularizer: it(this.embeddingsRegularizer), activityRegularizer: it(this.activityRegularizer), embeddingsConstraint: Ot(this.embeddingsConstraint), maskZero: this.maskZero, inputLength: this.inputLength }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Ey.className = "Embedding";
re.registerClass(Ey);
var xo = class extends He {
constructor(e) {
super(e || {}), this.supportsMasking = true;
}
mergeFunction(e) {
throw new Fe();
}
computeElementwiseOpOutputShape(e, t) {
if (e == null || t == null)
return null;
if (e.length < t.length)
return this.computeElementwiseOpOutputShape(t, e);
if (t.length === 0)
return e;
let n = e.slice(0, e.length - t.length);
for (let s = 0; s < t.length; ++s) {
let r = e[e.length - t.length + s], a = t[s];
if (r == null || a == null || r < 0 || a < 0)
n.push(null);
else if (r === 1)
n.push(a);
else if (a === 1)
n.push(r);
else {
if (r !== a)
throw new G("Operands could not be broadcast together with shapes " + JSON.stringify(e) + " " + JSON.stringify(t));
n.push(r);
}
}
return n;
}
build(e) {
if (Array.isArray(e) && !Array.isArray(e[0]) && (e = [nt(e)]), e = e, e.length < 2)
throw new G(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);
let t = [];
for (let r of e)
r != null && r[0] !== null && t.push(r[0]);
if (t = cr(t), t.length > 1)
throw new G(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);
let n = e[0] == null ? null : e[0].slice(1);
for (let r = 1; r < e.length; ++r) {
let a = e[r] == null ? null : e[r].slice(1);
n = this.computeElementwiseOpOutputShape(n, a);
}
let s = e.map((r) => r.length);
e.indexOf(null) === -1 && cr(s).length === 1 ? this.reshapeRequired = false : this.reshapeRequired = true;
}
call(e, t) {
return q(() => {
if (e = e, this.reshapeRequired) {
let n = [], s = e.map((r) => r.rank);
if (s.indexOf(null) === -1) {
let r = yr(s);
for (let a of e) {
let o = a.rank;
for (let i = 0; i < r - o; ++i)
a = Gl(a, 1);
n.push(a);
}
return this.mergeFunction(n);
} else {
let r = false;
for (let i of e) {
let u = i.rank;
if (u == null) {
let l = i.shape, c = l[0], p = l.slice(1).concat([c]), d = U(i, [c].concat(dr(l.slice(1))));
d = Ge(d, [1, 0]), d = U(d, p), n.push(d), r = true;
} else if (u > 1) {
let l = ys(1, u).concat([0]);
n.push(Ge(i, l)), r = true;
} else
n.push(i);
}
let a = this.mergeFunction(n), o = a.rank;
if (r) {
if (o == null) {
let i = a.shape, u = i.length, l = i[u - 1], c = [l].concat(i.slice(0, i.length - 1));
a = U(Ge(U(a, [-1, l]), [1, 0]), c);
} else if (o > 1) {
let i = [o - 1].concat(ys(0, o - 1));
a = Ge(a, i);
}
}
return a;
}
} else
return this.mergeFunction(e);
});
}
computeOutputShape(e) {
e = e;
let t;
e[0] == null ? t = null : t = e[0].slice(1);
for (let s = 1; s < e.length; ++s) {
let r = e[s] == null ? null : e[s].slice(1);
t = this.computeElementwiseOpOutputShape(t, r);
}
let n = [];
for (let s of e)
s != null && s[0] !== null && n.push(s[0]);
return n = cr(n), n.length === 1 ? t = n.concat(t) : t = [null].concat(t), t;
}
computeMask(e, t) {
return q(() => {
if (t == null)
return null;
if (!Array.isArray(t))
throw new G("`mask` should be an Array");
if (!Array.isArray(e))
throw new G("`inputs` should be an Array");
if (t.length !== e.length)
throw new G(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);
if (t.every((s) => s == null))
return null;
t = t.map((s) => s == null ? s : Pn(s, 0));
let n = t[0];
for (let s = 1; s < t.length - 1; ++s)
n = Ds(n, t[s]);
return n;
});
}
};
var Ry = class extends xo {
constructor(e) {
super(e);
}
mergeFunction(e) {
return q(() => {
let t = e[0].clone();
for (let n = 1; n < e.length; ++n)
t = oe(t, e[n]);
return t;
});
}
};
Ry.className = "Add";
re.registerClass(Ry);
var Dy = class extends xo {
constructor(e) {
super(e);
}
mergeFunction(e) {
return q(() => {
let t = e[0].clone();
for (let n = 1; n < e.length; ++n)
t = V(t, e[n]);
return t;
});
}
};
Dy.className = "Multiply";
re.registerClass(Dy);
var Fy = class extends xo {
constructor(e) {
super(e);
}
mergeFunction(e) {
return q(() => {
let t = e[0].clone();
for (let n = 1; n < e.length; ++n)
t = oe(t, e[n]);
return V(1 / e.length, t);
});
}
};
Fy.className = "Average";
re.registerClass(Fy);
var Oy = class extends xo {
constructor(e) {
super(e);
}
mergeFunction(e) {
return q(() => {
let t = e[0];
for (let n = 1; n < e.length; ++n)
t = Ar(t, e[n]);
return t;
});
}
};
Oy.className = "Maximum";
re.registerClass(Oy);
var Py = class extends xo {
constructor(e) {
super(e);
}
mergeFunction(e) {
return q(() => {
let t = e[0];
for (let n = 1; n < e.length; ++n)
t = Np(t, e[n]);
return t;
});
}
};
Py.className = "Minimum";
re.registerClass(Py);
var zy = class extends xo {
constructor(e) {
super(e), this.DEFAULT_AXIS = -1, e == null && (e = {}), this.axis = e.axis == null ? this.DEFAULT_AXIS : e.axis, this.supportsMasking = true, this.reshapeRequired = false;
}
build(e) {
if (!(Array.isArray(e) && Array.isArray(e[0])) || e.length === 1)
throw new G("A `Concatenate` layer should be called on a list of at least 2 inputs");
e = e;
let t = true;
for (let s of e)
if (s != null) {
t = false;
break;
}
if (t)
return;
let n = [];
for (let s = 0; s < e.length; ++s) {
let r = e[s].slice();
r.splice(this.axis, 1);
let a = false;
for (let o of n)
if (w.arraysEqual(o, r)) {
a = true;
break;
}
a || n.push(r);
}
if (n.length > 1)
throw new G("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: " + JSON.stringify(e));
}
mergeFunction(e) {
return q(() => Ob(e, this.axis));
}
computeOutputShape(e) {
if (!(Array.isArray(e) && Array.isArray(e[0])))
throw new G("A `Concatenate` layer should be called on a list of inputs.");
let t = e, n = t[0].slice(), s = this.axis < 0 ? n.length + this.axis : this.axis;
for (let r of t.slice(1)) {
if (n[s] == null || r[s] == null) {
n[s] = null;
break;
}
n[s] += r[s];
}
return n;
}
computeMask(e, t) {
if (t == null)
return null;
if (!Array.isArray(t))
throw new G("`mask` should be an array for Concatenate");
if (!Array.isArray(e))
throw new G("`inputs` should be an array for Concatenate");
if (t.length !== e.length)
throw new G(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);
return q(() => {
let n = true;
if (t.forEach((a) => {
if (a != null) {
n = false;
return;
}
}), n)
return null;
let s = [];
for (let a = 0; a < e.length; ++a)
t[a] == null ? s.push(le(Zn(e[a]), "bool")) : t[a].rank < e[a].rank ? s.push(Pn(t[a], -1)) : s.push(t[a]);
let r = Ft(s, this.axis);
return lS(r, -1, false);
});
}
getConfig() {
let e = { axis: this.axis }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
zy.className = "Concatenate";
re.registerClass(zy);
function _u(e, t) {
for (; e < 0; )
e += t;
return e;
}
function mV(e, t, n) {
if (e.shape.length > 3 || t.shape.length > 3)
throw new Fe("batchDot is not implemented for tensors of 4D or higher rank yet");
if (w.assert(e.shape.length >= 2, () => `batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`), w.assert(e.shape.length >= 2, () => `batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`), typeof n == "number" && (n = [n, n]), e.dtype === "complex64" || t.dtype === "complex64")
throw new Fe("batchDot is not implemented for complex64-type Tensors yet.");
let s = e.shape.length, r = t.shape.length;
n == null && (n = [s - 1, r - 2]);
let a = n;
return q(() => {
let o;
if (s > r) {
o = s - r;
let u = [];
for (let l = 0; l < o; ++l)
u.push(1);
t = U(t, t.shape.concat(u));
} else if (r > s) {
o = r - s;
let u = [];
for (let l = 0; l < o; ++l)
u.push(1);
e = U(e, e.shape.concat(u));
} else
o = 0;
let i;
if (e.shape.length === 2 && t.shape.length === 2)
a[0] === a[1] ? i = ve(V(e, t), a[0]) : i = ve(V(Ge(e, [1, 0]), t), a[1]);
else {
let u = a[0] !== e.shape.length - 1, l = a[1] === t.shape.length - 1;
i = We(e, t, u, l);
}
if (o > 0) {
let u;
s > r ? u = s + r - 3 : u = s - 1;
let l = [];
for (let c = u; c < u + o; ++c)
l.push(c);
i = br(i, l);
}
return i.shape.length === 1 && (i = Pn(i, 1)), i;
});
}
var Ly = class extends xo {
constructor(e) {
super(e), this.axes = e.axes, this.normalize = e.normalize == null ? false : e.normalize, this.supportsMasking = true, this.reshapeRequired = false;
}
build(e) {
w.assert(Array.isArray(e) && e.length === 2 && Array.isArray(e[0]) && Array.isArray(e[1]), () => "A `Dot` layer should be called on a list of exactly 2 inputs.");
let t = e[0], n = e[1];
if (t.length > 3 || n.length > 3)
throw new Fe("Dot layer does not support tensors of 4D or higher rank yet.");
let s = this.interpretAxes(t, n);
if (t[s[0]] !== n[s[1]])
throw new G(`Dimension incompatibility: ${t[s[0]]} !== ${n[s[1]]}`);
}
mergeFunction(e) {
if (e.length !== 2)
throw new G(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);
let t = e[0], n = e[1], s;
return Array.isArray(this.axes) ? s = this.axes.map((r, a) => _u(r, e[a].shape.length)) : s = [_u(this.axes, t.shape.length), _u(this.axes, n.shape.length)], this.normalize && (t = Dd(t, s[0]), n = Dd(n, s[1])), mV(t, n, s);
}
interpretAxes(e, t) {
let n;
return Array.isArray(this.axes) ? n = this.axes : n = [_u(this.axes, e.length), _u(this.axes, t.length)], n;
}
computeOutputShape(e) {
w.assert(Array.isArray(e) && e.length === 2 && Array.isArray(e[0]) && Array.isArray(e[1]), () => "A `Dot` layer should be called on a list of exactly 2 inputs.");
let t = e[0].slice(), n = e[1].slice();
if (t.length > 3 || n.length > 3)
throw new Fe("Dot layer does not support tensors of 4D or higher rank yet.");
let s = this.interpretAxes(t, n);
t.splice(s[0], 1), n.splice(s[1], 1), n.splice(0, 1);
let r = t.concat(n);
return r.length === 1 && r.push(1), r;
}
computeMask(e, t) {
return null;
}
getConfig() {
let e = { axes: this.axes, normalize: this.normalize }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Ly.className = "Dot";
re.registerClass(Ly);
var My = class extends He {
constructor(e) {
super(e), this.supportsMasking = true, this.stddev = e.stddev;
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = super.getConfig(), t = { stddev: this.stddev };
return Object.assign(t, e), t;
}
call(e, t) {
return q(() => {
this.invokeCallHook(e, t);
let n = Oe(e);
return ql(() => oe(Op(n.shape, 0, this.stddev), n), () => n, t.training || false);
});
}
};
My.className = "GaussianNoise";
re.registerClass(My);
var By = class extends He {
constructor(e) {
super(e), this.supportsMasking = true, this.rate = e.rate;
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = super.getConfig(), t = { rate: this.rate };
return Object.assign(t, e), t;
}
call(e, t) {
return q(() => {
this.invokeCallHook(e, t);
let n = Oe(e);
return this.rate > 0 && this.rate < 1 ? ql(() => {
let r = Math.sqrt(this.rate / (1 - this.rate));
return V(n, Op(n.shape, 1, r));
}, () => n, t.training || false) : n;
});
}
};
By.className = "GaussianDropout";
re.registerClass(By);
var Vy = class extends He {
constructor(e) {
super(e), this.supportsMasking = true, this.rate = e.rate, this.noiseShape = e.noiseShape;
}
_getNoiseShape(e) {
return this.noiseShape || Oe(e).shape;
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = super.getConfig(), t = { rate: this.rate };
return Object.assign(t, e), t;
}
call(e, t) {
return q(() => {
if (this.rate < 1 && this.rate > 0) {
let n = this._getNoiseShape(e);
return ql(() => {
let r = Oe(e), a = 1.6732632423543772, o = 1.0507009873554805, i = -a * o, u = Zi(Wl(n), this.rate);
u = Fp(u, "float32");
let l = ((1 - this.rate) * (1 + this.rate * i ** 2)) ** -0.5, c = -l * i * this.rate, p = oe(V(r, u), V(oe(u, -1), i));
return oe(V(p, l), c);
}, () => Oe(e), t.training || false);
}
return e;
});
}
};
Vy.className = "AlphaDropout";
re.registerClass(Vy);
function rl(e, t, n, s, r, a = 1e-3) {
let o;
if (e.rank === 2)
o = YE(e, t, n, s, r, a);
else if (e.rank === 3)
o = ZE(e, t, n, s, r, a);
else if (e.rank === 4)
o = eR(e, t, n, s, r, a);
else
throw new Fe(`batchNormalization is not implemented for array of rank ${e.rank} yet`);
return o;
}
function gV(e, t, n, s, r = 1e-3) {
return q(() => {
let a = hb(e, s), o = a.mean, i = a.variance;
return [rl(e, o, i, n, t, r), o, i];
});
}
function bV(e, t, n, s, r = 1e-3) {
return q(() => {
let a = hb(e, s), o = a.mean, i = a.variance, u = [];
for (let f of ys(0, e.rank))
s.indexOf(f) !== -1 ? u.push(1) : u.push(e.shape[f]);
let l = U(o, u), c = U(i, u), p = t == null ? null : U(t, u), d = n == null ? null : U(n, u);
return [rl(e, l, c, d, p, r), o, i];
});
}
function yV(e, t, n, s, r = 1e-3) {
return w.arraysEqual(s.slice().sort(), ys(0, e.rank - 1)) ? gV(e, t, n, s, r) : bV(e, t, n, s, r);
}
var Wy = class extends He {
constructor(e) {
e == null && (e = {}), super(e), this.supportsMasking = true, this.axis = e.axis == null ? -1 : e.axis, this.momentum = e.momentum == null ? 0.99 : e.momentum, this.epsilon = e.epsilon == null ? 1e-3 : e.epsilon, this.center = e.center == null ? true : e.center, this.scale = e.scale == null ? true : e.scale, this.betaInitializer = ft(e.betaInitializer || "zeros"), this.gammaInitializer = ft(e.gammaInitializer || "ones"), this.movingMeanInitializer = ft(e.movingMeanInitializer || "zeros"), this.movingVarianceInitializer = ft(e.movingVarianceInitializer || "ones"), this.betaConstraint = Pt(e.betaConstraint), this.gammaConstraint = Pt(e.gammaConstraint), this.betaRegularizer = mt(e.betaRegularizer), this.gammaRegularizer = mt(e.gammaRegularizer);
}
build(e) {
e = nt(e);
let t = this.axis >= 0 ? this.axis : this.axis + e.length, n = e[t];
if (n == null)
throw new G(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);
this.inputSpec = [new Dt({ ndim: e.length, axes: { [t]: n } })];
let s = [n];
this.scale && (this.gamma = this.addWeight("gamma", s, null, this.gammaInitializer, this.gammaRegularizer, true, this.gammaConstraint)), this.center && (this.beta = this.addWeight("beta", s, null, this.betaInitializer, this.betaRegularizer, true, this.betaConstraint)), this.movingMean = this.addWeight("moving_mean", s, null, this.movingMeanInitializer, null, false), this.movingVariance = this.addWeight("moving_variance", s, null, this.movingVarianceInitializer, null, false), this.built = true;
}
call(e, t) {
return q(() => {
let n = t.training == null ? false : t.training, s = Oe(e), r = s.shape, a = r.length, o = ys(0, a), i = this.axis >= 0 ? this.axis : this.axis + a;
o.splice(i, 1);
let u = ma(1, a);
u[i] = r[i];
let l = o.slice();
l.sort();
let c = !w.arraysEqual(l, ys(0, a).slice(0, a - 1)), p = () => {
if (c) {
let b = U(this.movingMean.read(), u), y = U(this.movingVariance.read(), u), v = this.center ? U(this.beta.read(), u) : null, x = this.scale ? U(this.gamma.read(), u) : null;
return rl(s, b, y, v, x, this.epsilon);
} else
return rl(s, this.movingMean.read(), this.movingVariance.read(), this.beta == null ? null : this.beta.read(), this.gamma == null ? null : this.gamma.read(), this.epsilon);
};
if (!n)
return p();
let [d, h, f] = yV(s, this.gamma.read(), this.beta.read(), o, this.epsilon), m = (b, y, v) => {
q(() => {
let x = 1 - v, k = b.read(), I = V(ge(k, y), x);
b.write(ge(k, I));
});
};
return (() => {
m(this.movingMean, h, this.momentum), m(this.movingVariance, f, this.momentum);
})(), d;
});
}
getConfig() {
let e = { axis: this.axis, momentum: this.momentum, epsilon: this.epsilon, center: this.center, scale: this.scale, betaInitializer: yt(this.betaInitializer), gammaInitializer: yt(this.gammaInitializer), movingMeanInitializer: yt(this.movingMeanInitializer), movingVarianceInitializer: yt(this.movingVarianceInitializer), betaRegularizer: it(this.betaRegularizer), gammaRegularizer: it(this.gammaRegularizer), betaConstraint: Ot(this.betaConstraint), gammaConstraint: Ot(this.gammaConstraint) }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Wy.className = "BatchNormalization";
re.registerClass(Wy);
var Uy = class extends He {
constructor(e) {
if (e == null && (e = {}), super(e), this.axis = e.axis == null ? -1 : e.axis, typeof this.axis == "number") {
if (!Number.isInteger(this.axis))
throw new Error(`Expected axis to be an integer, but received ${this.axis}`);
} else if (Array.isArray(this.axis)) {
for (let t of this.axis)
if (!Number.isInteger(t))
throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`);
} else
throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);
this.epsilon = e.epsilon == null ? 1e-3 : e.epsilon, this.center = e.center == null ? true : e.center, this.scale = e.scale == null ? true : e.scale, this.betaInitializer = ft(e.betaInitializer || "zeros"), this.gammaInitializer = ft(e.gammaInitializer || "ones"), this.betaRegularizer = mt(e.betaRegularizer), this.gammaRegularizer = mt(e.gammaRegularizer), this.supportsMasking = true;
}
build(e) {
e = nt(e);
let t = e.length;
typeof this.axis == "number" && (this.axis = [this.axis]);
for (let r = 0; r < this.axis.length; ++r)
this.axis[r] < 0 && (this.axis[r] += t);
for (let r of this.axis)
if (r < 0 || r >= t)
throw new Error(`Invalid axis: ${r}`);
if (this.axis.length !== cr(this.axis).length)
throw new Error(`Found duplicate axes in: ${this.axis}`);
let n = this.axis.map((r) => e[r]), s = true;
this.scale ? this.gamma = this.addWeight("gamma", n, "float32", this.gammaInitializer, this.gammaRegularizer, s) : this.gamma = null, this.center ? this.beta = this.addWeight("beta", n, "float32", this.betaInitializer, this.betaRegularizer, s) : this.beta = null, this.built = true;
}
call(e, t) {
let n = Oe(e), s = n.shape, r = s.length;
return q(() => {
let { mean: o, variance: i } = hb(n, this.axis, true), u = ma(1, r);
for (let f of this.axis)
u[f] = s[f];
let l = (f) => f != null && f.shape.length !== r ? U(f, u) : f, c = this.scale ? l(this.gamma.read()) : null, p = this.center ? l(this.beta.read()) : null, d = [], h = [];
for (let f = 0; f < r; ++f)
this.axis.indexOf(f) !== -1 ? (d.push(s[f]), h.push(1)) : (d.push(1), h.push(s[f]));
return o = hs(o, d), i = hs(i, d), c != null && (c = hs(c, h)), p != null && (p = hs(p, h)), rl(n, o, i, p, c, this.epsilon);
});
}
getConfig() {
let e = { axis: this.axis, epsilon: this.epsilon, center: this.center, scale: this.scale, betaInitializer: yt(this.betaInitializer), gammaInitializer: yt(this.gammaInitializer), betaRegularizer: it(this.betaRegularizer), gammaRegularizer: it(this.gammaRegularizer) }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Uy.className = "LayerNormalization";
re.registerClass(Uy);
function vV(e, t, n) {
return q(() => {
if (e.rank !== 4)
throw new G(`temporalPadding expects input tensor to be 4-D, but received a ${e.rank}-D tensor.`);
if (t == null && (t = [[1, 1], [1, 1]]), t.length !== 2 || t[0].length !== 2 || t[1].length !== 2)
throw new G("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");
if (n == null && (n = vs()), n !== "channelsLast" && n !== "channelsFirst")
throw new G(`Unknown data format: ${n}. Supported data formats are 'channelsLast' and 'channelsFirst.`);
let s;
return n === "channelsFirst" ? s = [[0, 0], [0, 0], t[0], t[1]] : s = [[0, 0], t[0], t[1], [0, 0]], bo(e, s);
});
}
var Gy = class extends He {
constructor(e) {
if (e == null && (e = {}), super(e), this.dataFormat = e.dataFormat == null ? vs() : e.dataFormat, e.padding == null)
this.padding = [[1, 1], [1, 1]];
else if (typeof e.padding == "number")
this.padding = [[e.padding, e.padding], [e.padding, e.padding]];
else {
if (e.padding = e.padding, e.padding.length !== 2)
throw new G(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);
let t, n;
if (typeof e.padding[0] == "number")
t = [e.padding[0], e.padding[0]], n = [e.padding[1], e.padding[1]];
else {
if (e.padding = e.padding, e.padding[0].length !== 2)
throw new G(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);
if (t = e.padding[0], e.padding[1].length !== 2)
throw new G(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);
n = e.padding[1];
}
this.padding = [t, n];
}
this.inputSpec = [new Dt({ ndim: 4 })];
}
computeOutputShape(e) {
e = nt(e);
let t, n;
return this.dataFormat === "channelsFirst" ? (e[2] != null && e[2] >= 0 ? t = e[2] + this.padding[0][0] + this.padding[0][1] : t = null, e[3] != null && e[3] >= 0 ? n = e[3] + this.padding[1][0] + this.padding[1][1] : n = null, [e[0], e[1], t, n]) : (e[1] != null && e[1] >= 0 ? t = e[1] + this.padding[0][0] + this.padding[0][1] : t = null, e[2] != null && e[2] >= 0 ? n = e[2] + this.padding[1][0] + this.padding[1][1] : n = null, [e[0], t, n, e[3]]);
}
call(e, t) {
return q(() => vV(Oe(e), this.padding, this.dataFormat));
}
getConfig() {
let e = { padding: this.padding, dataFormat: this.dataFormat }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Gy.className = "ZeroPadding2D";
re.registerClass(Gy);
function Jp(e, t, n, s, r, a) {
return q(() => {
Ct(r), iI(a), Hn(s), n == null && (n = [1, 1]), s == null && (s = "valid"), r == null && (r = vs()), a == null && (a = "max"), e = cy(e, r);
let o, i = s === "same" ? "same" : "valid";
return a === "max" ? o = pb(e, t, n, i) : o = nb(e, t, n, i), r === "channelsFirst" && (o = Ge(o, [0, 3, 1, 2])), o;
});
}
function t0(e, t, n, s, r, a) {
return q(() => {
Ct(r), iI(a), Hn(s), n == null && (n = [1, 1, 1]), s == null && (s = "valid"), r == null && (r = vs()), a == null && (a = "max"), e = qI(e, r);
let o, i = s === "same" ? "same" : "valid";
return a === "max" ? o = AS(e, t, n, i) : o = hS(e, t, n, i), r === "channelsFirst" && (o = Ge(o, [0, 4, 1, 2, 3])), o;
});
}
var n0 = class extends He {
constructor(e) {
if (e.poolSize == null && (e.poolSize = 2), super(e), typeof e.poolSize == "number")
this.poolSize = [e.poolSize];
else if (Array.isArray(e.poolSize) && e.poolSize.length === 1 && typeof e.poolSize[0] == "number")
this.poolSize = e.poolSize;
else
throw new G(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);
if (Bt(this.poolSize, "poolSize"), e.strides == null)
this.strides = this.poolSize;
else if (typeof e.strides == "number")
this.strides = [e.strides];
else if (Array.isArray(e.strides) && e.strides.length === 1 && typeof e.strides[0] == "number")
this.strides = e.strides;
else
throw new G(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);
Bt(this.strides, "strides"), this.padding = e.padding == null ? "valid" : e.padding, Hn(this.padding), this.inputSpec = [new Dt({ ndim: 3 })];
}
computeOutputShape(e) {
e = nt(e);
let t = bs(e[1], this.poolSize[0], this.padding, this.strides[0]);
return [e[0], t, e[2]];
}
call(e, t) {
return q(() => {
this.invokeCallHook(e, t), e = Gl(Oe(e), 2);
let n = this.poolingFunction(Oe(e), [this.poolSize[0], 1], [this.strides[0], 1], this.padding, "channelsLast");
return br(n, [2]);
});
}
getConfig() {
let e = { poolSize: this.poolSize, padding: this.padding, strides: this.strides }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
var Hy = class extends n0 {
constructor(e) {
super(e);
}
poolingFunction(e, t, n, s, r) {
return Ct(r), Hn(s), Jp(e, t, n, s, r, "max");
}
};
Hy.className = "MaxPooling1D";
re.registerClass(Hy);
var qy = class extends n0 {
constructor(e) {
super(e);
}
poolingFunction(e, t, n, s, r) {
return Ct(r), Hn(s), Jp(e, t, n, s, r, "avg");
}
};
qy.className = "AveragePooling1D";
re.registerClass(qy);
var s0 = class extends He {
constructor(e) {
if (e.poolSize == null && (e.poolSize = [2, 2]), super(e), this.poolSize = Array.isArray(e.poolSize) ? e.poolSize : [e.poolSize, e.poolSize], e.strides == null)
this.strides = this.poolSize;
else if (Array.isArray(e.strides)) {
if (e.strides.length !== 2)
throw new G(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);
this.strides = e.strides;
} else
this.strides = [e.strides, e.strides];
Bt(this.poolSize, "poolSize"), Bt(this.strides, "strides"), this.padding = e.padding == null ? "valid" : e.padding, this.dataFormat = e.dataFormat == null ? "channelsLast" : e.dataFormat, Ct(this.dataFormat), Hn(this.padding), this.inputSpec = [new Dt({ ndim: 4 })];
}
computeOutputShape(e) {
e = nt(e);
let t = this.dataFormat === "channelsFirst" ? e[2] : e[1], n = this.dataFormat === "channelsFirst" ? e[3] : e[2];
return t = bs(t, this.poolSize[0], this.padding, this.strides[0]), n = bs(n, this.poolSize[1], this.padding, this.strides[1]), this.dataFormat === "channelsFirst" ? [e[0], e[1], t, n] : [e[0], t, n, e[3]];
}
call(e, t) {
return q(() => (this.invokeCallHook(e, t), this.poolingFunction(Oe(e), this.poolSize, this.strides, this.padding, this.dataFormat)));
}
getConfig() {
let e = { poolSize: this.poolSize, padding: this.padding, strides: this.strides, dataFormat: this.dataFormat }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
var jy = class extends s0 {
constructor(e) {
super(e);
}
poolingFunction(e, t, n, s, r) {
return Ct(r), Hn(s), Jp(e, t, n, s, r, "max");
}
};
jy.className = "MaxPooling2D";
re.registerClass(jy);
var Ky = class extends s0 {
constructor(e) {
super(e);
}
poolingFunction(e, t, n, s, r) {
return Ct(r), Hn(s), Jp(e, t, n, s, r, "avg");
}
};
Ky.className = "AveragePooling2D";
re.registerClass(Ky);
var r0 = class extends He {
constructor(e) {
if (e.poolSize == null && (e.poolSize = [2, 2, 2]), super(e), this.poolSize = Array.isArray(e.poolSize) ? e.poolSize : [e.poolSize, e.poolSize, e.poolSize], e.strides == null)
this.strides = this.poolSize;
else if (Array.isArray(e.strides)) {
if (e.strides.length !== 3)
throw new G(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);
this.strides = e.strides;
} else
this.strides = [e.strides, e.strides, e.strides];
Bt(this.poolSize, "poolSize"), Bt(this.strides, "strides"), this.padding = e.padding == null ? "valid" : e.padding, this.dataFormat = e.dataFormat == null ? "channelsLast" : e.dataFormat, Ct(this.dataFormat), Hn(this.padding), this.inputSpec = [new Dt({ ndim: 5 })];
}
computeOutputShape(e) {
e = nt(e);
let t = this.dataFormat === "channelsFirst" ? e[2] : e[1], n = this.dataFormat === "channelsFirst" ? e[3] : e[2], s = this.dataFormat === "channelsFirst" ? e[4] : e[3];
return t = bs(t, this.poolSize[0], this.padding, this.strides[0]), n = bs(n, this.poolSize[1], this.padding, this.strides[1]), s = bs(s, this.poolSize[2], this.padding, this.strides[2]), this.dataFormat === "channelsFirst" ? [e[0], e[1], t, n, s] : [e[0], t, n, s, e[4]];
}
call(e, t) {
return q(() => (this.invokeCallHook(e, t), this.poolingFunction(Oe(e), this.poolSize, this.strides, this.padding, this.dataFormat)));
}
getConfig() {
let e = { poolSize: this.poolSize, padding: this.padding, strides: this.strides, dataFormat: this.dataFormat }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
var Xy = class extends r0 {
constructor(e) {
super(e);
}
poolingFunction(e, t, n, s, r) {
return Ct(r), Hn(s), t0(e, t, n, s, r, "max");
}
};
Xy.className = "MaxPooling3D";
re.registerClass(Xy);
var Yy = class extends r0 {
constructor(e) {
super(e);
}
poolingFunction(e, t, n, s, r) {
return Ct(r), Hn(s), t0(e, t, n, s, r, "avg");
}
};
Yy.className = "AveragePooling3D";
re.registerClass(Yy);
var a0 = class extends He {
constructor(e) {
super(e), this.inputSpec = [new Dt({ ndim: 3 })];
}
computeOutputShape(e) {
return [e[0], e[2]];
}
call(e, t) {
throw new Fe();
}
};
var Qy = class extends a0 {
constructor(e) {
super(e || {});
}
call(e, t) {
return q(() => {
let n = Oe(e);
return It(n, 1);
});
}
};
Qy.className = "GlobalAveragePooling1D";
re.registerClass(Qy);
var Zy = class extends a0 {
constructor(e) {
super(e || {});
}
call(e, t) {
return q(() => {
let n = Oe(e);
return As(n, 1);
});
}
};
Zy.className = "GlobalMaxPooling1D";
re.registerClass(Zy);
var o0 = class extends He {
constructor(e) {
super(e), this.dataFormat = e.dataFormat == null ? "channelsLast" : e.dataFormat, Ct(this.dataFormat), this.inputSpec = [new Dt({ ndim: 4 })];
}
computeOutputShape(e) {
return e = e, this.dataFormat === "channelsLast" ? [e[0], e[3]] : [e[0], e[1]];
}
call(e, t) {
throw new Fe();
}
getConfig() {
let e = { dataFormat: this.dataFormat }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
var Jy = class extends o0 {
call(e, t) {
return q(() => {
let n = Oe(e);
return this.dataFormat === "channelsLast" ? It(n, [1, 2]) : It(n, [2, 3]);
});
}
};
Jy.className = "GlobalAveragePooling2D";
re.registerClass(Jy);
var ev = class extends o0 {
call(e, t) {
return q(() => {
let n = Oe(e);
return this.dataFormat === "channelsLast" ? As(n, [1, 2]) : As(n, [2, 3]);
});
}
};
ev.className = "GlobalMaxPooling2D";
re.registerClass(ev);
var i0 = class extends He {
constructor(e) {
super(e), this.layer = e.layer;
}
build(e) {
this.built = true;
}
get trainable() {
return this.layer != null ? this.layer.trainable : false;
}
set trainable(e) {
this.layer != null && (this.layer.trainable = e);
}
get trainableWeights() {
return this.layer.trainableWeights;
}
get nonTrainableWeights() {
return this.layer.nonTrainableWeights;
}
get updates() {
return this.layer._updates;
}
get losses() {
return this.layer.losses;
}
getWeights() {
return this.layer.getWeights();
}
setWeights(e) {
this.layer.setWeights(e);
}
getConfig() {
let e = { layer: { className: this.layer.getClassName(), config: this.layer.getConfig() } }, t = super.getConfig();
return Object.assign(e, t), e;
}
setFastWeightInitDuringBuild(e) {
super.setFastWeightInitDuringBuild(e), this.layer != null && this.layer.setFastWeightInitDuringBuild(e);
}
static fromConfig(e, t, n = {}) {
let s = t.layer, r = gs(s, n);
delete t.layer;
let a = { layer: r };
return Object.assign(a, t), new e(a);
}
};
var tv = class extends i0 {
constructor(e) {
super(e), this.supportsMasking = true;
}
build(e) {
if (e = nt(e), e.length < 3)
throw new G(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);
this.inputSpec = [{ shape: e }];
let t = [e[0]].concat(e.slice(2));
this.layer.built || (this.layer.build(t), this.layer.built = true), super.build(e);
}
computeOutputShape(e) {
e = nt(e);
let t = [e[0]].concat(e.slice(2)), n = this.layer.computeOutputShape(t), s = e[1];
return [n[0], s].concat(n.slice(1));
}
call(e, t) {
return q(() => (e = Oe(e), ZI((a, o) => [Oe(this.layer.call(a, t)), []], e, [], false, null, null, false, true)[1]));
}
};
tv.className = "TimeDistributed";
re.registerClass(tv);
function xV(e) {
yo(fz, "BidirectionalMergeMode", e);
}
var wV = "concat";
var nv = class extends i0 {
constructor(e) {
super(e);
let t = e.layer.getConfig(), n = {};
n.className = e.layer.getClassName(), n.config = t, this.forwardLayer = gs(n), t.goBackwards = t.goBackwards !== true;
let s = {};
if (s.className = e.layer.getClassName(), s.config = t, this.backwardLayer = gs(s), this.forwardLayer.name = "forward_" + this.forwardLayer.name, this.backwardLayer.name = "backward_" + this.backwardLayer.name, this.mergeMode = e.mergeMode === void 0 ? wV : e.mergeMode, xV(this.mergeMode), e.weights)
throw new Fe("weights support is not implemented for Bidirectional layer yet.");
this._stateful = e.layer.stateful, this.returnSequences = e.layer.returnSequences, this.returnState = e.layer.returnState, this.supportsMasking = true, this._trainable = true, this.inputSpec = e.layer.inputSpec, this.numConstants = null;
}
get trainable() {
return this._trainable;
}
set trainable(e) {
this._trainable = e, this.forwardLayer != null && (this.forwardLayer.trainable = e), this.backwardLayer != null && (this.backwardLayer.trainable = e);
}
getWeights() {
return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights());
}
setWeights(e) {
let t = e.length, n = Math.floor(t / 2);
this.forwardLayer.setWeights(e.slice(0, n)), this.backwardLayer.setWeights(e.slice(n));
}
computeOutputShape(e) {
let t = this.forwardLayer.computeOutputShape(e);
Array.isArray(t) && Array.isArray(t[0]) || (t = [t]), t = t;
let n, s, r;
return this.returnState && (r = t.slice(1)), n = t[0], n = n, this.mergeMode === "concat" ? (n[n.length - 1] *= 2, s = [n]) : this.mergeMode == null ? s = [n, n.slice()] : s = [n], this.returnState ? this.mergeMode == null ? s.concat(r).concat(r.slice()) : [n].concat(r).concat(r.slice()) : bn(s);
}
apply(e, t) {
let n = t == null ? null : t.initialState, s = t == null ? null : t.constants;
t == null && (t = {});
let r = QI(e, n, s, this.numConstants);
if (e = r.inputs, n = r.initialState, s = r.constants, Array.isArray(e) && (n = e.slice(1), e = e[0]), (n == null || n.length === 0) && s == null)
return super.apply(e, t);
let a = [], o = [];
if (n != null) {
let u = n.length;
if (u % 2 > 0)
throw new G("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");
t.initialState = n, a.push(...n);
let l = n.map((c) => new Dt({ shape: c.shape }));
this.forwardLayer.stateSpec = l.slice(0, u / 2), this.backwardLayer.stateSpec = l.slice(u / 2), o.push(...l);
}
if (s != null)
throw new Fe("Support for constants in Bidirectional layers is not implemented yet.");
let i = a[0] instanceof $s;
for (let u of a)
if (u instanceof $s !== i)
throw new G("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");
if (i) {
let u = [e].concat(a), l = this.inputSpec.concat(o), c = this.inputSpec;
this.inputSpec = l;
let p = super.apply(u, t);
return this.inputSpec = c, p;
} else
return super.apply(e, t);
}
call(e, t) {
return q(() => {
let n = t.initialState, s, r;
if (n == null)
s = this.forwardLayer.call(e, t), r = this.backwardLayer.call(e, t);
else {
let i = n.slice(0, n.length / 2), u = n.slice(n.length / 2);
s = this.forwardLayer.call(e, Object.assign(t, { initialState: i })), r = this.backwardLayer.call(e, Object.assign(t, { initialState: u }));
}
let a;
this.returnState && (Array.isArray(s) && (a = s.slice(1).concat(r.slice(1))), s = s[0], r = r[0]), this.returnSequences && (r = Jn(r, 1));
let o;
return this.mergeMode === "concat" ? o = Ob([s, r]) : this.mergeMode === "sum" ? o = oe(s, r) : this.mergeMode === "ave" ? o = V(0.5, oe(s, r)) : this.mergeMode === "mul" ? o = V(s, r) : this.mergeMode == null && (o = [s, r]), this.returnState ? this.mergeMode == null ? o.concat(a) : [o].concat(a) : o;
});
}
resetStates(e) {
this.forwardLayer.resetStates(), this.backwardLayer.resetStates();
}
build(e) {
na(this.forwardLayer.name, () => {
this.forwardLayer.build(e);
}), na(this.backwardLayer.name, () => {
this.backwardLayer.build(e);
}), this.built = true;
}
computeMask(e, t) {
Array.isArray(t) && (t = t[0]);
let n;
if (this.returnSequences ? this.mergeMode == null ? n = [t, t] : n = t : this.mergeMode == null ? n = [null, null] : n = null, this.returnState) {
let r = this.forwardLayer.states.map((a) => null);
return Array.isArray(n) ? n.concat(r).concat(r) : [n].concat(r).concat(r);
} else
return n;
}
get trainableWeights() {
return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights);
}
get nonTrainableWeights() {
return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights);
}
setFastWeightInitDuringBuild(e) {
super.setFastWeightInitDuringBuild(e), this.forwardLayer != null && this.forwardLayer.setFastWeightInitDuringBuild(e), this.backwardLayer != null && this.backwardLayer.setFastWeightInitDuringBuild(e);
}
getConfig() {
let e = { mergeMode: this.mergeMode }, t = super.getConfig();
return Object.assign(e, t), e;
}
static fromConfig(e, t) {
let n = gs(t.layer);
if (delete t.layer, t.numConstants != null)
throw new Fe("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");
let s = t;
return s.layer = n, new e(s);
}
};
nv.className = "Bidirectional";
re.registerClass(nv);
function kV(e) {
return new tu(e);
}
function SV(e) {
return new iy(e);
}
function IV(e) {
return new ry(e);
}
function CV(e) {
return new ay(e);
}
function NV(e) {
return new oy(e);
}
function TV(e) {
return new ly(e);
}
function $V(e) {
return new uy(e);
}
function _V(e) {
return new my(e);
}
function AV(e) {
return new qp(e);
}
function EV(e) {
return new py(e);
}
function RV(e) {
return new jp(e);
}
function DV(e) {
return new hy(e);
}
function FV(e) {
return new fy(e);
}
function OV(e) {
return new gy(e);
}
function PV(e) {
return new by(e);
}
function zV(e) {
return new yy(e);
}
function LV(e) {
return new Ny(e);
}
function MV(e) {
return new Iy(e);
}
function BV(e) {
return new Zp(e);
}
function VV(e) {
return new Sy(e);
}
function WV(e) {
return new Cy(e);
}
function UV(e) {
return new Ty(e);
}
function GV(e) {
return new $y(e);
}
function HV(e) {
return new _y(e);
}
function qV(e) {
return new Ey(e);
}
function jV(e) {
return new Ry(e);
}
function KV(e) {
return new Fy(e);
}
function XV(e) {
return new zy(e);
}
function YV(e) {
return new Oy(e);
}
function QV(e) {
return new Py(e);
}
function ZV(e) {
return new Dy(e);
}
function JV(e) {
return new Ly(e);
}
function eW(e) {
return new Wy(e);
}
function tW(e) {
return new Uy(e);
}
function nW(e) {
return new Gy(e);
}
function sv(e) {
return new qy(e);
}
function sW(e) {
return sv(e);
}
function rW(e) {
return sv(e);
}
function rv(e) {
return new Ky(e);
}
function aW(e) {
return rv(e);
}
function oW(e) {
return rv(e);
}
function av(e) {
return new Yy(e);
}
function iW(e) {
return av(e);
}
function uW(e) {
return av(e);
}
function lW(e) {
return new Qy(e);
}
function cW(e) {
return new Jy(e);
}
function u0(e) {
return new Zy(e);
}
function l0(e) {
return new ev(e);
}
function c0(e) {
return new Hy(e);
}
function d0(e) {
return new jy(e);
}
function dW(e) {
return new Xy(e);
}
function pW(e) {
return new xy(e);
}
function hW(e) {
return new Xp(e);
}
function fW(e) {
return new wy(e);
}
function mW(e) {
return new Ql(e);
}
function gW(e) {
return new vy(e);
}
function bW(e) {
return new Kp(e);
}
function yW(e) {
return new ky(e);
}
function vW(e) {
return new Qp(e);
}
function xW(e) {
return new Rr(e);
}
function wW(e) {
return new Yp(e);
}
function kW(e) {
return new nv(e);
}
function SW(e) {
return new tv(e);
}
var IW = u0;
var CW = l0;
var NW = c0;
var TW = d0;
function $W(e) {
return new My(e);
}
function _W(e) {
return new By(e);
}
function AW(e) {
return new Vy(e);
}
function EW(e) {
return new Ay(e);
}
var RW = {};
Ee(RW, { MAPE: () => UW, MSE: () => qW, binaryAccuracy: () => DW, binaryCrossentropy: () => FW, categoricalAccuracy: () => PW, categoricalCrossentropy: () => zW, cosineProximity: () => BW, mape: () => GW, meanAbsoluteError: () => VW, meanAbsolutePercentageError: () => WW, meanSquaredError: () => HW, mse: () => jW, precision: () => LW, recall: () => MW, sparseCategoricalAccuracy: () => OW });
function DW(e, t) {
return Qb(e, t);
}
function FW(e, t) {
return kI(e, t);
}
function OW(e, t) {
return SI(e, t);
}
function PW(e, t) {
return Zb(e, t);
}
function zW(e, t) {
return Jb(e, t);
}
function LW(e, t) {
return wI(e, t);
}
function MW(e, t) {
return _B(e, t);
}
function BW(e, t) {
return Yb(e, t);
}
function VW(e, t) {
return Gp(e, t);
}
function WW(e, t) {
return nu(e, t);
}
function UW(e, t) {
return nu(e, t);
}
function GW(e, t) {
return nu(e, t);
}
function HW(e, t) {
return vo(e, t);
}
function qW(e, t) {
return vo(e, t);
}
function jW(e, t) {
return vo(e, t);
}
var KW = {};
Ee(KW, { modelFromJSON: () => aV });
var XW = {};
Ee(XW, { l1: () => QW, l1l2: () => YW, l2: () => ZW });
function YW(e) {
return new Kl(e);
}
function QW(e) {
return cV(e);
}
function ZW(e) {
return dV(e);
}
var JW = class extends si {
constructor() {
super(...arguments), this.model = null;
}
setModel(e) {
if (!(e instanceof pr))
throw new Error("model must be a LayersModel, not some other Container");
this.model = e;
}
};
function Zc(e, t) {
return e < t;
}
function ew(e, t) {
return e > t;
}
var e4 = class extends JW {
constructor(e) {
if (super(), e == null && (e = {}), e.restoreBestWeights)
throw new Fe("restoreBestWeights = True is not implemented in EarlyStopping yet.");
this.monitor = e.monitor || "val_loss", this.minDelta = Math.abs(e.minDelta || 0), this.patience = e.patience || 0, this.verbose = e.verbose || 0, this.mode = e.mode || "auto", this.baseline = e.baseline, ["auto", "min", "max"].indexOf(this.mode) === -1 && (console.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`), this.mode = "auto"), this.mode === "min" ? this.monitorFunc = Zc : this.mode === "max" ? this.monitorFunc = ew : this.monitor.indexOf("acc") !== -1 ? this.monitorFunc = ew : this.monitorFunc = Zc, this.monitorFunc === Zc && (this.minDelta *= -1);
}
async onTrainBegin(e) {
this.wait = 0, this.stoppedEpoch = 0, this.baseline != null ? this.best = this.baseline : this.best = this.monitorFunc === Zc ? 1 / 0 : -1 / 0;
}
async onEpochEnd(e, t) {
await rr(t);
let n = this.getMonitorValue(t);
n != null && (this.monitorFunc(n - this.minDelta, this.best) ? (this.best = n, this.wait = 0) : (this.wait++, this.wait >= this.patience && (this.stoppedEpoch = e, this.model.stopTraining = true)));
}
async onTrainEnd(e) {
this.stoppedEpoch > 0 && this.verbose && console.log(`Epoch ${this.stoppedEpoch}: early stopping.`);
}
getMonitorValue(e) {
e == null && (e = {});
let t = e[this.monitor];
return t == null && console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`), t;
}
};
function t4(e) {
return new e4(e);
}
var _he = { earlyStopping: t4 };
var n4 = K();
n4.registerFlag("KEEP_INTERMEDIATE_TENSORS", () => false, (e) => {
e && console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.");
});
var p0 = ((e) => (e[e.DT_INVALID = 0] = "DT_INVALID", e[e.DT_FLOAT = 1] = "DT_FLOAT", e[e.DT_DOUBLE = 2] = "DT_DOUBLE", e[e.DT_INT32 = 3] = "DT_INT32", e[e.DT_UINT8 = 4] = "DT_UINT8", e[e.DT_INT16 = 5] = "DT_INT16", e[e.DT_INT8 = 6] = "DT_INT8", e[e.DT_STRING = 7] = "DT_STRING", e[e.DT_COMPLEX64 = 8] = "DT_COMPLEX64", e[e.DT_INT64 = 9] = "DT_INT64", e[e.DT_BOOL = 10] = "DT_BOOL", e[e.DT_QINT8 = 11] = "DT_QINT8", e[e.DT_QUINT8 = 12] = "DT_QUINT8", e[e.DT_QINT32 = 13] = "DT_QINT32", e[e.DT_BFLOAT16 = 14] = "DT_BFLOAT16", e[e.DT_QINT16 = 15] = "DT_QINT16", e[e.DT_QUINT16 = 16] = "DT_QUINT16", e[e.DT_UINT16 = 17] = "DT_UINT16", e[e.DT_COMPLEX128 = 18] = "DT_COMPLEX128", e[e.DT_HALF = 19] = "DT_HALF", e[e.DT_RESOURCE = 20] = "DT_RESOURCE", e[e.DT_VARIANT = 21] = "DT_VARIANT", e[e.DT_UINT32 = 22] = "DT_UINT32", e[e.DT_UINT64 = 23] = "DT_UINT64", e[e.DT_FLOAT_REF = 101] = "DT_FLOAT_REF", e[e.DT_DOUBLE_REF = 102] = "DT_DOUBLE_REF", e[e.DT_INT32_REF = 103] = "DT_INT32_REF", e[e.DT_UINT8_REF = 104] = "DT_UINT8_REF", e[e.DT_INT16_REF = 105] = "DT_INT16_REF", e[e.DT_INT8_REF = 106] = "DT_INT8_REF", e[e.DT_STRING_REF = 107] = "DT_STRING_REF", e[e.DT_COMPLEX64_REF = 108] = "DT_COMPLEX64_REF", e[e.DT_INT64_REF = 109] = "DT_INT64_REF", e[e.DT_BOOL_REF = 110] = "DT_BOOL_REF", e[e.DT_QINT8_REF = 111] = "DT_QINT8_REF", e[e.DT_QUINT8_REF = 112] = "DT_QUINT8_REF", e[e.DT_QINT32_REF = 113] = "DT_QINT32_REF", e[e.DT_BFLOAT16_REF = 114] = "DT_BFLOAT16_REF", e[e.DT_QINT16_REF = 115] = "DT_QINT16_REF", e[e.DT_QUINT16_REF = 116] = "DT_QUINT16_REF", e[e.DT_UINT16_REF = 117] = "DT_UINT16_REF", e[e.DT_COMPLEX128_REF = 118] = "DT_COMPLEX128_REF", e[e.DT_HALF_REF = 119] = "DT_HALF_REF", e[e.DT_RESOURCE_REF = 120] = "DT_RESOURCE_REF", e[e.DT_VARIANT_REF = 121] = "DT_VARIANT_REF", e[e.DT_UINT32_REF = 122] = "DT_UINT32_REF", e[e.DT_UINT64_REF = 123] = "DT_UINT64_REF", e))(p0 || {});
var tw;
((e) => {
let t;
((n) => {
n[n.LEGACY = 0] = "LEGACY", n[n.V1 = 1] = "V1", n[n.V2 = 2] = "V2";
})(t = e.CheckpointFormatVersion || (e.CheckpointFormatVersion = {}));
})(tw || (tw = {}));
var ov = {};
function Ahe(e, t) {
let n = { tfOpName: e, category: "custom", inputs: [], attrs: [], customExecutor: t };
ov[e] = n;
}
function h0(e) {
return ov[e];
}
function Ehe(e) {
delete ov[e];
}
function S(e, t, n, s, r) {
let a = t.inputParams[e];
if (a && a.inputIndexStart !== void 0) {
let i = a.inputIndexStart, u = a.inputIndexEnd === 0 ? void 0 : a.inputIndexEnd === void 0 ? i + 1 : a.inputIndexEnd;
if (a.type === "tensor")
return un(t.inputNames[a.inputIndexStart], n, s, r);
if (a.type === "tensors")
return t.inputNames.slice(i, u).map((d) => un(d, n, s, r));
let l = un(t.inputNames.slice(i)[0], n, s, r), c = l.dataSync();
return a.type === "number" ? c[0] : w.toNestedArray(l.shape, c);
}
let o = t.attrParams[e];
return o && o.value;
}
function un(e, t, n, s) {
let [r, a] = _n(e);
if (s != null) {
let i = s.getHashTableHandleByName(r);
if (i != null)
return i;
}
let o = n.currentContextIds.find((i) => !!t[Ld(r, i)]);
return o !== void 0 ? t[Ld(r, o)][a] : void 0;
}
function s4(e, t, n) {
return t[Ld(e, n.currentContextId)];
}
function Ts(e, t) {
let [n, s, r] = _n(e);
return [Ld(n, t && t.currentContextId), s, r];
}
function Ld(e, t) {
return t ? `${e}-${t}` : e;
}
function _n(e) {
let t = e.split(":");
if (t.length === 1)
return [e, 0, void 0];
let n = t[0], s = t.length === 3 ? t[1] : void 0, r = Number(t[t.length - 1]);
return [n, r, s];
}
function ud(e, t, n) {
let s = S("pad", e, t, n);
if (s === "explicit") {
s = S("explicitPaddings", e, t, n);
let r = [[0, 0], [0, 0], [0, 0], [0, 0]];
for (let a = 0; a < 4; a++)
r[a][0] = s[a * 2], r[a][1] = s[a * 2 + 1];
return r;
}
return s;
}
function Ws(e) {
return e.kept ? e : lr(e);
}
var f0 = {};
Ee(f0, { json: () => r4 });
var r4 = [{ 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 }] }];
var m0 = {};
Ee(m0, { json: () => a4 });
var a4 = [{ 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 }] }];
var g0 = {};
Ee(g0, { json: () => o4 });
var o4 = [{ tfOpName: "EmptyTensorList", category: "control", inputs: [{ start: 0, name: "elementShape", type: "shape" }, { start: 1, name: "maxNumElements", type: "number" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "LoopCond", category: "control", inputs: [{ start: 0, name: "pred", type: "tensor" }] }, { tfOpName: "Switch", category: "control", inputs: [{ start: 0, name: "data", type: "tensor" }, { start: 1, name: "pred", type: "tensor" }] }, { tfOpName: "Merge", category: "control", inputs: [{ start: 0, end: 0, name: "tensors", type: "tensors" }] }, { tfOpName: "Enter", category: "control", inputs: [{ start: 0, name: "tensor", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }, { tfName: "frame_name", name: "frameName", type: "string" }, { tfName: "is_constant", name: "isConstant", type: "bool" }] }, { tfOpName: "Exit", category: "control", inputs: [{ start: 0, name: "tensor", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "NextIteration", category: "control", inputs: [{ start: 0, name: "tensor", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "TensorArrayV3", category: "control", inputs: [{ start: 0, name: "size", type: "number" }], attrs: [{ tfName: "dtype", name: "dtype", type: "dtype" }, { tfName: "element_shape", name: "elementShape", type: "shape" }, { tfName: "dynamic_size", name: "dynamicSize", type: "bool" }, { tfName: "clear_after_read", name: "clearAfterRead", type: "bool" }, { tfName: "identical_element_shapes", name: "identicalElementShapes", type: "bool" }, { tfName: "tensor_array_name", name: "name", type: "string" }] }, { tfOpName: "TensorArrayWriteV3", category: "control", inputs: [{ start: 0, name: "tensorArrayId", type: "tensor" }, { start: 1, name: "index", type: "number" }, { start: 2, name: "tensor", type: "tensor" }, { start: 3, name: "flowIn", type: "number" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "TensorArrayReadV3", category: "control", inputs: [{ start: 0, name: "tensorArrayId", type: "tensor" }, { start: 1, name: "index", type: "number" }, { start: 2, name: "flowIn", type: "number" }], attrs: [{ tfName: "dtype", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "TensorArrayGatherV3", category: "control", inputs: [{ start: 0, name: "tensorArrayId", type: "tensor" }, { start: 1, name: "indices", type: "number[]" }, { start: 2, name: "flowIn", type: "number" }], attrs: [{ tfName: "dtype", name: "dtype", type: "dtype" }, { tfName: "element_shape", name: "elementShape", type: "shape" }] }, { tfOpName: "TensorArrayScatterV3", category: "control", inputs: [{ start: 0, name: "tensorArrayId", type: "tensor" }, { start: 1, name: "indices", type: "number[]" }, { start: 2, name: "tensor", type: "tensor" }, { start: 3, name: "flowIn", type: "number" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype" }] }, { tfOpName: "TensorArrayConcatV3", category: "control", inputs: [{ start: 0, name: "tensorArrayId", type: "tensor" }, { start: 1, name: "flowIn", type: "number" }], attrs: [{ tfName: "dtype", name: "dtype", type: "dtype" }, { tfName: "element_shape_except0", name: "elementShapeExcept0", type: "shape", notSupported: true }] }, { tfOpName: "TensorArraySplitV3", category: "control", inputs: [{ start: 0, name: "tensorArrayId", type: "tensor" }, { start: 1, name: "tensor", type: "tensor" }, { start: 2, name: "lengths", type: "number[]" }, { start: 3, name: "flowIn", type: "number" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype" }] }, { tfOpName: "TensorArraySizeV3", category: "control", inputs: [{ start: 0, name: "tensorArrayId", type: "tensor" }, { start: 1, name: "flowIn", type: "number" }] }, { tfOpName: "TensorArrayCloseV3", category: "control", inputs: [{ start: 0, name: "tensorArrayId", type: "tensor" }] }, { tfOpName: "StatelessIf", category: "control", inputs: [{ start: 0, name: "cond", type: "tensor" }, { start: 1, end: 0, name: "args", type: "tensors" }], attrs: [{ tfName: "then_branch", name: "thenBranch", type: "func" }, { tfName: "else_branch", name: "elseBranch", type: "func" }] }, { tfOpName: "If", category: "control", inputs: [{ start: 0, name: "cond", type: "tensor" }, { start: 1, end: 0, name: "args", type: "tensors" }], attrs: [{ tfName: "then_branch", name: "thenBranch", type: "func" }, { tfName: "else_branch", name: "elseBranch", type: "func" }] }, { tfOpName: "StatelessWhile", category: "control", inputs: [{ start: 0, end: 0, name: "args", type: "tensors" }], attrs: [{ tfName: "cond", name: "cond", type: "func" }, { tfName: "body", name: "body", type: "func" }] }, { tfOpName: "While", category: "control", inputs: [{ start: 0, end: 0, name: "args", type: "tensors" }], attrs: [{ tfName: "cond", name: "cond", type: "func" }, { tfName: "body", name: "body", type: "func" }] }, { tfOpName: "TensorListScatter", category: "control", inputs: [{ start: 0, name: "tensor", type: "tensor" }, { start: 1, name: "indices", type: "number[]" }, { start: 2, name: "elementShape", type: "shape" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListScatterV2", category: "control", inputs: [{ start: 0, name: "tensor", type: "tensor" }, { start: 1, name: "indices", type: "number[]" }, { start: 2, name: "elementShape", type: "shape" }, { start: 3, name: "numElements", type: "number" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListGather", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }, { start: 1, name: "indices", type: "number[]" }, { start: 2, name: "elementShape", type: "shape" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListGetItem", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }, { start: 1, name: "index", type: "number" }, { start: 2, name: "elementShape", type: "shape" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListSetItem", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }, { start: 1, name: "index", type: "number" }, { start: 2, name: "tensor", type: "tensor" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListReserve", category: "control", inputs: [{ start: 0, name: "elementShape", type: "shape" }, { start: 1, name: "numElements", type: "number" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListFromTensor", category: "control", inputs: [{ start: 0, name: "tensor", type: "tensor" }, { start: 1, name: "elementShape", type: "shape" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListStack", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }, { start: 1, name: "elementShape", type: "shape" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }, { tfName: "num_elements", name: "numElements", type: "dtype" }] }, { tfOpName: "TensorListSplit", category: "control", inputs: [{ start: 0, name: "tensor", type: "tensor" }, { start: 1, name: "elementShape", type: "shape" }, { start: 2, name: "lengths", type: "number[]" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListConcat", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }], attrs: [{ tfName: "element_shape", name: "elementShape", type: "shape" }, { tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListConcatV2", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }], attrs: [{ tfName: "element_shape", name: "elementShape", type: "shape" }, { tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListPopBack", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }, { start: 1, name: "elementShape", type: "shape" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListPushBack", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }, { start: 1, name: "tensor", type: "tensor" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListLength", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }] }, { tfOpName: "TensorListResize", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }, { start: 1, name: "size", type: "number" }] }];
var b0 = {};
Ee(b0, { json: () => i4 });
var i4 = [{ 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: 1e-4 }, { tfName: "leakyrelu_alpha", name: "leakyreluAlpha", type: "number", defaultValue: 0.2 }] }, { tfOpName: "Conv2DBackpropInput", category: "convolution", inputs: [{ start: 2, name: "x", type: "tensor" }, { start: 1, name: "filter", type: "tensor" }, { start: 0, name: "outputShape", type: "number[]" }], attrs: [{ tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "data_format", name: "dataFormat", type: "string", notSupported: true }, { tfName: "explicit_paddings", name: "explicitPaddings", type: "number[]", defaultValue: [] }, { tfName: "dilations", name: "dilations", type: "number[]", notSupported: true }] }, { tfOpName: "DepthwiseConv2d", category: "convolution", inputs: [{ start: 0, name: "input", type: "tensor" }, { start: 1, name: "filter", type: "tensor" }], attrs: [{ tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "data_format", name: "dataFormat", type: "string", defaultValue: "NHWC" }, { tfName: "explicit_paddings", name: "explicitPaddings", type: "number[]", defaultValue: [] }, { tfName: "dilations", name: "dilations", type: "number[]" }] }, { tfOpName: "DepthwiseConv2dNative", category: "convolution", inputs: [{ start: 0, name: "input", type: "tensor" }, { start: 1, name: "filter", type: "tensor" }], attrs: [{ tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "data_format", name: "dataFormat", type: "string", defaultValue: "NHWC" }, { tfName: "explicit_paddings", name: "explicitPaddings", type: "number[]", defaultValue: [] }, { tfName: "dilations", name: "dilations", type: "number[]" }] }, { tfOpName: "FusedDepthwiseConv2dNative", category: "convolution", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "filter", type: "tensor" }, { start: 2, end: 0, name: "args", type: "tensors" }], attrs: [{ tfName: "num_args", name: "numArgs", type: "number" }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }, { tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "data_format", name: "dataFormat", type: "string", defaultValue: "NHWC" }, { tfName: "dilations", name: "dilations", type: "number[]", defaultValue: [1, 1, 1, 1] }, { tfName: "fused_ops", name: "fusedOps", type: "string[]", defaultValue: [] }, { tfName: "explicit_paddings", name: "explicitPaddings", type: "number[]", defaultValue: [] }] }, { tfOpName: "Conv3D", category: "convolution", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "filter", type: "tensor" }], attrs: [{ tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "data_format", name: "dataFormat", type: "string", defaultValue: "NHWC" }, { tfName: "dilations", name: "dilations", type: "number[]" }] }, { tfOpName: "Dilation2D", category: "convolution", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "filter", type: "tensor" }], attrs: [{ tfName: "strides", name: "strides", type: "number[]" }, { tfName: "rates", name: "dilations", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }] }];
var y0 = {};
Ee(y0, { json: () => u4 });
var u4 = [{ 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 }, { tfName: "stddev", name: "stdDev", type: "number", defaultValue: 1 }, { tfName: "seed", name: "seed", type: "number" }, { tfName: "seed2", name: "seed2", type: "number", defaultValue: 0, notSupported: true }, { tfName: "dtype", name: "dtype", type: "dtype" }, { tfName: "T", name: "T", type: "number", notSupported: true }] }, { tfOpName: "Zeros", category: "creation", inputs: [{ start: 0, name: "shape", type: "number[]" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype" }] }, { tfOpName: "ZerosLike", category: "creation", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype" }] }, { tfOpName: "Multinomial", category: "creation", inputs: [{ start: 0, name: "logits", type: "tensor" }, { start: 1, name: "numSamples", type: "number" }], attrs: [{ tfName: "seed", name: "seed", type: "number" }, { tfName: "seed2", name: "seed2", type: "number" }, { tfName: "T", name: "dtype", type: "dtype" }, { tfName: "output_dtype", name: "output_dtype", type: "dtype" }] }];
var v0 = {};
Ee(v0, { json: () => l4 });
var l4 = [{ 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 }] }];
var x0 = {};
Ee(x0, { json: () => c4 });
var c4 = [{ tfOpName: "LowerBound", category: "evaluation", inputs: [{ start: 0, name: "sortedSequence", type: "tensor" }, { start: 1, name: "values", type: "tensor" }] }, { tfOpName: "TopKV2", category: "evaluation", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "k", type: "number" }], attrs: [{ tfName: "sorted", name: "sorted", type: "bool" }] }, { tfOpName: "UpperBound", category: "evaluation", inputs: [{ start: 0, name: "sortedSequence", type: "tensor" }, { start: 1, name: "values", type: "tensor" }] }, { tfOpName: "Unique", category: "evaluation", inputs: [{ start: 0, name: "x", type: "tensor" }] }, { tfOpName: "UniqueV2", category: "evaluation", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number" }] }];
var w0 = {};
Ee(w0, { json: () => d4 });
var d4 = [{ 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" }] }];
var k0 = {};
Ee(k0, { json: () => p4 });
var p4 = [{ 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" }] }];
var S0 = {};
Ee(S0, { json: () => h4 });
var h4 = [{ tfOpName: "ResizeBilinear", category: "image", inputs: [{ start: 0, name: "images", type: "tensor" }, { start: 1, name: "size", type: "number[]" }], attrs: [{ tfName: "align_corners", name: "alignCorners", type: "bool" }, { tfName: "half_pixel_centers", name: "halfPixelCenters", type: "bool" }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "ResizeNearestNeighbor", category: "image", inputs: [{ start: 0, name: "images", type: "tensor" }, { start: 1, name: "size", type: "number[]" }], attrs: [{ tfName: "align_corners", name: "alignCorners", type: "bool" }, { tfName: "half_pixel_centers", name: "halfPixelCenters", type: "bool" }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "CropAndResize", category: "image", inputs: [{ start: 0, name: "image", type: "tensor" }, { start: 1, name: "boxes", type: "tensor" }, { start: 2, name: "boxInd", type: "tensor" }, { start: 3, name: "cropSize", type: "number[]" }], attrs: [{ tfName: "method", name: "method", type: "string" }, { tfName: "extrapolation_value", name: "extrapolationValue", type: "number" }] }, { tfOpName: "ImageProjectiveTransformV3", category: "image", inputs: [{ start: 0, name: "images", type: "tensor" }, { start: 1, name: "transforms", type: "tensor" }, { start: 2, name: "outputShape", type: "number[]" }, { start: 3, name: "fillValue", type: "number" }], attrs: [{ tfName: "interpolation", name: "interpolation", type: "string" }, { tfName: "fill_mode", name: "fillMode", type: "string" }] }];
var I0 = {};
Ee(I0, { json: () => f4 });
var f4 = [{ 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 }] }];
var C0 = {};
Ee(C0, { json: () => m4 });
var m4 = [{ 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: 1e-4 }, { tfName: "transpose_a", name: "transposeA", type: "bool", defaultValue: false }, { tfName: "transpose_b", name: "transposeB", type: "bool", defaultValue: false }, { tfName: "leakyrelu_alpha", name: "leakyreluAlpha", type: "number", defaultValue: 0.2 }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "MatMul", category: "matrices", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "transpose_a", name: "transposeA", type: "bool", defaultValue: false }, { tfName: "transpose_b", name: "transposeB", type: "bool", defaultValue: false }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "BatchMatMul", category: "matrices", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "adj_x", name: "transposeA", type: "bool", defaultValue: false }, { tfName: "adj_y", name: "transposeB", type: "bool", defaultValue: false }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "BatchMatMulV2", category: "matrices", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "adj_x", name: "transposeA", type: "bool", defaultValue: false }, { tfName: "adj_y", name: "transposeB", type: "bool", defaultValue: false }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Transpose", category: "matrices", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "perm", type: "number[]" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Einsum", category: "matrices", inputs: [{ start: 0, end: 0, name: "tensors", type: "tensors" }], attrs: [{ tfName: "equation", name: "equation", type: "string" }, { tfName: "N", name: "n", type: "number", defaultValue: 2 }, { tfName: "T", name: "dtype", type: "dtype" }] }];
var N0 = {};
Ee(N0, { json: () => g4 });
var g4 = [{ tfOpName: "EuclideanNorm", category: "normalization", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number[]" }], attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool", defaultValue: false }] }, { tfOpName: "FusedBatchNorm", category: "normalization", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "scale", type: "tensor" }, { start: 2, name: "offset", type: "tensor" }, { start: 3, name: "mean", type: "tensor" }, { start: 4, name: "variance", type: "tensor" }], attrs: [{ tfName: "epsilon", name: "epsilon", type: "number", defaultValue: 1e-3 }, { 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: 1e-3 }, { 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: 1e-3 }, { tfName: "data_format", name: "dataFormat", type: "string", notSupported: true }] }, { tfOpName: "LRN", category: "normalization", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "depth_radius", name: "radius", type: "number", defaultValue: 5 }, { tfName: "bias", name: "bias", type: "number", defaultValue: 1 }, { tfName: "alpha", name: "alpha", type: "number", defaultValue: 1 }, { tfName: "beta", name: "beta", type: "number", defaultValue: 0.5 }] }, { tfOpName: "Softmax", category: "normalization", inputs: [{ start: 0, name: "x", type: "tensor" }] }, { tfOpName: "LogSoftmax", category: "normalization", inputs: [{ start: 0, name: "x", type: "tensor" }] }, { 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 }] }];
var T0 = {};
Ee(T0, { json: () => b4 });
var b4 = [{ 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: "Cumprod", category: "reduction", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number" }], attrs: [{ tfName: "exclusive", name: "exclusive", type: "bool" }, { tfName: "reverse", name: "reverse", type: "bool" }] }, { tfOpName: "Cumsum", category: "reduction", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number" }], attrs: [{ tfName: "exclusive", name: "exclusive", type: "bool" }, { tfName: "reverse", name: "reverse", type: "bool" }] }];
var $0 = {};
Ee($0, { json: () => y4 });
var y4 = [{ 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 }] }];
var _0 = {};
Ee(_0, { json: () => v4 });
var v4 = [{ tfOpName: "SparseFillEmptyRows", category: "sparse", inputs: [{ start: 0, name: "indices", type: "tensor" }, { start: 1, name: "values", type: "tensor" }, { start: 2, name: "denseShape", type: "tensor" }, { start: 3, name: "defaultValue", type: "tensor" }] }, { tfOpName: "SparseReshape", category: "sparse", inputs: [{ start: 0, name: "inputIndices", type: "tensor" }, { start: 1, name: "inputShape", type: "tensor" }, { start: 2, name: "newShape", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "SparseSegmentMean", category: "sparse", inputs: [{ start: 0, name: "data", type: "tensor" }, { start: 1, name: "indices", type: "tensor" }, { start: 2, name: "segmentIds", type: "tensor" }] }, { tfOpName: "SparseSegmentSum", category: "sparse", inputs: [{ start: 0, name: "data", type: "tensor" }, { start: 1, name: "indices", type: "tensor" }, { start: 2, name: "segmentIds", type: "tensor" }] }];
var A0 = {};
Ee(A0, { json: () => x4 });
var x4 = [{ 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 }] }];
var E0 = {};
Ee(E0, { json: () => w4 });
var w4 = [{ tfOpName: "StringNGrams", category: "string", inputs: [{ start: 0, name: "data", type: "tensor" }, { start: 1, name: "dataSplits", type: "tensor" }], attrs: [{ tfName: "separator", name: "separator", type: "string" }, { tfName: "ngram_widths", name: "nGramWidths", type: "number[]" }, { tfName: "left_pad", name: "leftPad", type: "string" }, { tfName: "right_pad", name: "rightPad", type: "string" }, { tfName: "pad_width", name: "padWidth", type: "number" }, { tfName: "preserve_short_sequences", name: "preserveShortSequences", type: "bool" }], outputs: ["ngrams", "ngrams_splits"] }, { tfOpName: "StringSplit", category: "string", inputs: [{ start: 0, name: "input", type: "tensor" }, { start: 1, name: "delimiter", type: "tensor" }], attrs: [{ tfName: "skip_empty", name: "skipEmpty", type: "bool" }], outputs: ["indices", "values", "shape"] }, { tfOpName: "StringToHashBucketFast", category: "string", inputs: [{ start: 0, name: "input", type: "tensor" }], attrs: [{ tfName: "num_buckets", name: "numBuckets", type: "number" }] }];
var R0 = {};
Ee(R0, { json: () => k4 });
var k4 = [{ 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: [] }, { tfOpName: "BroadcastArgs", category: "transformation", inputs: [{ start: 0, name: "s0", type: "tensor" }, { start: 1, name: "s1", type: "tensor" }], attrs: [] }];
var nw = class {
static get Instance() {
return this._instance || (this._instance = new this());
}
constructor() {
let e = [f0, m0, g0, b0, y0, v0, x0, w0, k0, S0, I0, C0, N0, T0, $0, _0, A0, E0, R0], t = [].concat(...e.map((n) => n.json));
this.opMappers = t.reduce((n, s) => (n[s.tfOpName] = s, n), {});
}
transformGraph(e, t = {}) {
let n = e.node, s = [], r = [], a = [], o = n.reduce((f, m) => (f[m.name] = this.mapNode(m), m.op.startsWith("Placeholder") ? s.push(f[m.name]) : m.op === "Const" ? r.push(f[m.name]) : (m.input == null || m.input.length === 0) && a.push(f[m.name]), f), {}), i = [], u = [], l = {}, c = {};
t != null && (l = this.mapSignatureEntries(t.inputs), c = this.mapSignatureEntries(t.outputs));
let p = Object.keys(o);
p.forEach((f) => {
let m = o[f];
m.inputNames.forEach((g, b) => {
let [y, , v] = Ts(g), x = o[y];
if (x.outputs != null) {
let k = x.outputs.indexOf(v);
if (k !== -1) {
let I = `${y}:${k}`;
m.inputNames[b] = I;
}
}
m.inputs.push(x), x.children.push(m);
});
}), Object.keys(c).length === 0 ? p.forEach((f) => {
let m = o[f];
m.children.length === 0 && u.push(m);
}) : Object.keys(c).forEach((f) => {
let [m] = Ts(f), g = o[m];
g != null && (g.signatureKey = c[f], u.push(g));
}), Object.keys(l).length > 0 ? Object.keys(l).forEach((f) => {
let [m] = Ts(f), g = o[m];
g && (g.signatureKey = l[f], i.push(g));
}) : i = s;
let d = {};
e.library != null && e.library.function != null && (d = e.library.function.reduce((f, m) => (f[m.signature.name] = this.mapFunction(m), f), {}));
let h = { nodes: o, inputs: i, outputs: u, weights: r, placeholders: s, signature: t, functions: d };
return a.length > 0 && (h.initNodes = a), h;
}
mapSignatureEntries(e) {
return Object.keys(e || {}).reduce((t, n) => (t[e[n].name] = n, t), {});
}
mapNode(e) {
let t = h0(e.op) || this.opMappers[e.op] || {};
e.attr == null && (e.attr = {});
let n = { name: e.name, op: e.op, category: t.category, inputNames: (e.input || []).map((s) => s.startsWith("^") ? s.slice(1) : s), inputs: [], children: [], inputParams: {}, attrParams: {}, rawAttrs: e.attr, outputs: t.outputs };
return t.inputs != null && (n.inputParams = t.inputs.reduce((s, r) => (s[r.name] = { type: r.type, inputIndexStart: r.start, inputIndexEnd: r.end }, s), {})), t.attrs != null && (n.attrParams = t.attrs.reduce((s, r) => {
let a = r.type, o;
switch (r.type) {
case "string":
o = Lm(e.attr, r.tfName, r.defaultValue), o === void 0 && !!r.tfDeprecatedName && (o = Lm(e.attr, r.tfDeprecatedName, r.defaultValue));
break;
case "string[]":
o = Hm(e.attr, r.tfName, r.defaultValue), o === void 0 && !!r.tfDeprecatedName && (o = Hm(e.attr, r.tfDeprecatedName, r.defaultValue));
break;
case "number":
o = Bm(e.attr, r.tfName, r.defaultValue || 0), o === void 0 && !!r.tfDeprecatedName && (o = Bm(e.attr, r.tfDeprecatedName, r.defaultValue));
break;
case "number[]":
o = Gm(e.attr, r.tfName, r.defaultValue), o === void 0 && !!r.tfDeprecatedName && (o = Gm(e.attr, r.tfDeprecatedName, r.defaultValue));
break;
case "bool":
o = Mm(e.attr, r.tfName, r.defaultValue), o === void 0 && !!r.tfDeprecatedName && (o = Mm(e.attr, r.tfDeprecatedName, r.defaultValue));
break;
case "bool[]":
o = jm(e.attr, r.tfName, r.defaultValue), o === void 0 && !!r.tfDeprecatedName && (o = jm(e.attr, r.tfDeprecatedName, r.defaultValue));
break;
case "shape":
o = Um(e.attr, r.tfName, r.defaultValue), o === void 0 && !!r.tfDeprecatedName && (o = Um(e.attr, r.tfDeprecatedName, r.defaultValue));
break;
case "shape[]":
o = qm(e.attr, r.tfName, r.defaultValue), o === void 0 && !!r.tfDeprecatedName && (o = qm(e.attr, r.tfDeprecatedName, r.defaultValue));
break;
case "dtype":
o = Vm(e.attr, r.tfName, r.defaultValue), o === void 0 && !!r.tfDeprecatedName && (o = Vm(e.attr, r.tfDeprecatedName, r.defaultValue));
break;
case "dtype[]":
o = Wm(e.attr, r.tfName, r.defaultValue), o === void 0 && !!r.tfDeprecatedName && (o = Wm(e.attr, r.tfDeprecatedName, r.defaultValue));
break;
case "func":
o = sw(e.attr, r.tfName, r.defaultValue), o === void 0 && !!r.tfDeprecatedName && (o = sw(e.attr, r.tfDeprecatedName, r.defaultValue));
break;
case "tensor":
case "tensors":
break;
default:
throw new Error(`Unsupported param type: ${r.type} for op: ${e.op}`);
}
return s[r.name] = { value: o, type: a }, s;
}, {})), n;
}
mapFunction(e) {
let t = e.nodeDef, n = [], s = [], r = {};
t != null && (r = t.reduce((c, p) => (c[p.name] = this.mapNode(p), p.op === "Const" && s.push(c[p.name]), c), {}));
let a = [], o = [];
e.signature.inputArg.forEach((c) => {
let [p] = Ts(c.name), d = { name: p, op: "Placeholder", inputs: [], inputNames: [], category: "graph", inputParams: {}, attrParams: { dtype: { value: iv(c.type), type: "dtype" } }, children: [] };
d.signatureKey = c.name, a.push(d), r[p] = d;
}), Object.keys(r).forEach((c) => {
let p = r[c];
p.inputNames.forEach((d, h) => {
let [f, , m] = Ts(d), g = r[f];
if (g.outputs != null) {
let b = g.outputs.indexOf(m);
if (b !== -1) {
let y = `${f}:${b}`;
p.inputNames[h] = y;
}
}
p.inputs.push(g), g.children.push(p);
});
});
let u = e.ret;
e.signature.outputArg.forEach((c) => {
let [p, d] = Ts(u[c.name]), h = r[p];
h != null && (h.defaultOutput = d, o.push(h));
});
let l = this.mapArgsToSignature(e);
return { nodes: r, inputs: a, outputs: o, weights: s, placeholders: n, signature: l };
}
mapArgsToSignature(e) {
return { methodName: e.signature.name, inputs: e.signature.inputArg.reduce((t, n) => (t[n.name] = this.mapArgToTensorInfo(n), t), {}), outputs: e.signature.outputArg.reduce((t, n) => (t[n.name] = this.mapArgToTensorInfo(n, e.ret), t), {}) };
}
mapArgToTensorInfo(e, t) {
let n = e.name;
return t != null && (n = t[n]), { name: n, dtype: e.type };
}
};
function S4(e) {
let t = K().global;
if (typeof t.atob != "undefined")
return t.atob(e);
if (typeof Buffer != "undefined")
return new Buffer(e, "base64").toString();
throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()");
}
function D0(e, t) {
let n = Array.isArray(e) ? String.fromCharCode.apply(null, e) : S4(e);
return t ? n : n.toLowerCase();
}
function Lm(e, t, n, s = false) {
let r = e[t];
return r != null ? D0(r.s, s) : n;
}
function Mm(e, t, n) {
let s = e[t];
return s ? s.b : n;
}
function Bm(e, t, n) {
let s = e[t] || {}, r = s.i != null ? s.i : s.f != null ? s.f : n;
return typeof r == "number" ? r : parseInt(r, 10);
}
function iv(e) {
switch (typeof e == "string" && (e = p0[e]), e) {
case 1:
case 19:
return "float32";
case 3:
case 9:
case 6:
case 4:
return "int32";
case 10:
return "bool";
case 2:
return "float32";
case 7:
return "string";
default:
return null;
}
}
function sw(e, t, n) {
let s = e[t];
return s && s.func ? s.func.name : n;
}
function Vm(e, t, n) {
let s = e[t];
return s && s.type ? iv(s.type) : n;
}
function Wm(e, t, n) {
let s = e[t];
return s && s.list && s.list.type ? s.list.type.map((r) => iv(r)) : n;
}
function F0(e) {
if (!e.unknownRank)
return e.dim != null ? e.dim.map((t) => typeof t.size == "number" ? t.size : parseInt(t.size, 10)) : [];
}
function Um(e, t, n) {
let s = e[t];
return s && s.shape ? F0(s.shape) : n;
}
function Gm(e, t, n) {
let s = e[t];
return s ? ((s.list.f && s.list.f.length ? s.list.f : s.list.i) || []).map((r) => typeof r == "number" ? r : parseInt(r, 10)) : n;
}
function Hm(e, t, n, s = false) {
let r = e[t];
return r && r.list && r.list.s ? r.list.s.map((a) => D0(a, s)) : n;
}
function qm(e, t, n) {
let s = e[t];
return s && s.list && s.list.shape ? s.list.shape.map((r) => F0(r)) : n;
}
function jm(e, t, n) {
let s = e[t];
return s && s.list && s.list.b ? s.list.b : n;
}
var I4 = class {
constructor(e, t, n) {
this.node = e, this.tensorMap = t, this.context = n, this.inputs = [], this.attrs = {}, this.inputs = e.inputNames.map((s) => this.getInput(s)), e.rawAttrs != null && (this.attrs = Object.keys(e.rawAttrs).reduce((s, r) => (s[r] = this.getAttr(r), s), {}));
}
getInput(e) {
return un(e, this.tensorMap, this.context);
}
getAttr(e, t) {
let n = this.node.rawAttrs[e];
if (n.tensor != null)
return un(e, this.tensorMap, this.context);
if (n.i != null || n.f != null)
return Bm(this.node.rawAttrs, e, t);
if (n.s != null)
return Lm(this.node.rawAttrs, e, t);
if (n.b != null)
return Mm(this.node.rawAttrs, e, t);
if (n.shape != null)
return Um(this.node.rawAttrs, e, t);
if (n.type != null)
return Vm(this.node.rawAttrs, e, t);
if (n.list != null) {
if (n.list.i != null || n.list.f != null)
return Gm(this.node.rawAttrs, e, t);
if (n.list.s != null)
return Hm(this.node.rawAttrs, e, t);
if (n.list.shape != null)
return qm(this.node.rawAttrs, e, t);
if (n.list.b != null)
return jm(this.node.rawAttrs, e, t);
if (n.list.type != null)
return Wm(this.node.rawAttrs, e, t);
}
return t;
}
};
var C4 = (e, t, n) => {
switch (e.op) {
case "BiasAdd":
case "AddV2":
case "Add":
return [oe(S("a", e, t, n), S("b", e, t, n))];
case "AddN":
return [gE(S("tensors", e, t, n))];
case "FloorMod":
case "Mod":
return [XD(S("a", e, t, n), S("b", e, t, n))];
case "Mul":
return [V(S("a", e, t, n), S("b", e, t, n))];
case "RealDiv":
case "Div":
return [xe(S("a", e, t, n), S("b", e, t, n))];
case "DivNoNan":
return [BR(S("a", e, t, n), S("b", e, t, n))];
case "FloorDiv":
return [uS(S("a", e, t, n), S("b", e, t, n))];
case "Sub":
return [ge(S("a", e, t, n), S("b", e, t, n))];
case "Minimum":
return [Np(S("a", e, t, n), S("b", e, t, n))];
case "Maximum":
return [Ar(S("a", e, t, n), S("b", e, t, n))];
case "Pow":
return [ha(S("a", e, t, n), S("b", e, t, n))];
case "SquaredDifference":
return [BS(S("a", e, t, n), S("b", e, t, n))];
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
var N4 = (e, t, n) => {
switch (e.op) {
case "Abs":
case "ComplexAbs":
return [Lt(S("x", e, t, n))];
case "Acos":
return [pE(S("x", e, t, n))];
case "Acosh":
return [fE(S("x", e, t, n))];
case "Asin":
return [SE(S("x", e, t, n))];
case "Asinh":
return [CE(S("x", e, t, n))];
case "Atan":
return [TE(S("x", e, t, n))];
case "Atan2":
return [_E(S("x", e, t, n), S("y", e, t, n))];
case "Atanh":
return [EE(S("x", e, t, n))];
case "Ceil":
return [oR(S("x", e, t, n))];
case "Complex":
return [mr(S("real", e, t, n), S("imag", e, t, n))];
case "Cos":
return [ab(S("x", e, t, n))];
case "Cosh":
return [vS(S("x", e, t, n))];
case "Elu":
return [Sp(S("x", e, t, n))];
case "Erf":
return [qR(S("x", e, t, n))];
case "Exp":
return [Yn(S("x", e, t, n))];
case "Expm1":
return [iD(S("x", e, t, n))];
case "Floor":
return [Ip(S("x", e, t, n))];
case "Log":
return [Qn(S("x", e, t, n))];
case "Log1p":
return [cb(S("x", e, t, n))];
case "Imag":
return [wp(S("x", e, t, n))];
case "Neg":
return [vt(S("x", e, t, n))];
case "Reciprocal":
return [k3(S("x", e, t, n))];
case "Real":
return [Xu(S("x", e, t, n))];
case "Relu":
return [Xs(S("x", e, t, n))];
case "Round":
return [DS(S("x", e, t, n))];
case "Selu":
return [OS(S("x", e, t, n))];
case "Sigmoid":
return [qs(S("x", e, t, n))];
case "Sin":
return [PS(S("x", e, t, n))];
case "Sign":
return [L3(S("x", e, t, n))];
case "Sinh":
return [zS(S("x", e, t, n))];
case "Softplus":
return [Vl(S("x", e, t, n))];
case "Sqrt":
return [dn(S("x", e, t, n))];
case "Square":
return [ct(S("x", e, t, n))];
case "Tanh":
return [Qu(S("x", e, t, n))];
case "Tan":
return [rF(S("x", e, t, n))];
case "ClipByValue":
return [Wn(S("x", e, t, n), S("clipValueMin", e, t, n), S("clipValueMax", e, t, n))];
case "Relu6":
return [RS(S("x", e, t, n))];
case "Rsqrt":
return [FS(un(e.inputNames[0], t, n))];
case "Prod":
return [ES(S("x", e, t, n), S("axes", e, t, n))];
case "LeakyRelu":
return [lb(S("x", e, t, n), S("alpha", e, t, n))];
case "Prelu":
return [mb(S("x", e, t, n), S("alpha", e, t, n))];
case "IsNan":
return [bD(un(e.inputNames[0], t, n))];
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
function jn(e, t, n = "") {
if (!(typeof e == "number" || typeof t == "number")) {
w.assert(e.length === t.length, () => n + ` Shapes ${e} and ${t} must match`);
for (let s = 0; s < e.length; s++) {
let r = e[s], a = t[s];
w.assert(r < 0 || a < 0 || r === a, () => n + ` Shapes ${e} and ${t} must match`);
}
}
}
function rw(e) {
return !(typeof e == "number" || e.some((t) => t < 0));
}
function Au(e, t, n) {
let s = Km(e, n), r = !rw(s);
if (r && t.length === 0)
throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${s}`);
if (r && t.forEach((a) => {
s = Km(a.shape, s);
}), !rw(s))
throw new Error(`Non-fully-defined elementShape: ${s}`);
return s;
}
function Km(e, t) {
if (typeof e == "number")
return t;
if (typeof t == "number")
return e;
if (e.length !== t.length)
throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);
let n = [];
for (let s = 0; s < e.length; ++s) {
let r = e[s], a = t[s];
if (r >= 0 && a >= 0 && r !== a)
throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);
n[s] = r >= 0 ? r : a;
}
return n;
}
var T4 = class {
constructor(e, t, n, s, r, a, o) {
this.name = e, this.dtype = t, this.maxSize = n, this.elementShape = s, this.identicalElementShapes = r, this.dynamicSize = a, this.clearAfterRead = o, this.tensors = [], this.closed_ = false, this.idTensor = we(0), qt(this.idTensor);
}
get id() {
return this.idTensor.id;
}
get closed() {
return this.closed_;
}
clearAndClose(e) {
this.tensors.forEach((t) => {
(e == null || !e.has(t.tensor.id)) && t.tensor.dispose();
}), this.tensors = [], this.closed_ = true, this.idTensor.dispose();
}
size() {
return this.tensors.length;
}
read(e) {
if (this.closed_)
throw new Error(`TensorArray ${this.name} has already been closed.`);
if (e < 0 || e >= this.size())
throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);
let t = this.tensors[e];
if (t.cleared)
throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);
return this.clearAfterRead && (t.cleared = true), t.read = true, t.tensor;
}
readMany(e) {
return e.map((t) => this.read(t));
}
write(e, t) {
if (this.closed_)
throw new Error(`TensorArray ${this.name} has already been closed.`);
if (e < 0 || !this.dynamicSize && e >= this.maxSize)
throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);
let n = this.tensors[e] || {};
if (t.dtype !== this.dtype)
throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},
because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);
if (this.size() === 0 && (this.elementShape == null || this.elementShape.length === 0) && (this.elementShape = t.shape), jn(this.elementShape, t.shape, `TensorArray ${this.name}: Could not write to TensorArray index ${e}.`), n.read)
throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);
if (n.written)
throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);
n.tensor = t, qt(t), n.written = true, this.tensors[e] = n;
}
writeMany(e, t) {
if (e.length !== t.length)
throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);
e.forEach((n, s) => this.write(n, t[s]));
}
gather(e, t) {
if (!!t && t !== this.dtype)
throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);
if (e)
e = e.slice(0, this.size());
else {
e = [];
for (let s = 0; s < this.size(); s++)
e.push(s);
}
if (e.length === 0)
return ms([], [0].concat(this.elementShape));
let n = this.readMany(e);
return jn(this.elementShape, n[0].shape, "TensorArray shape mismatch: "), es(n, 0);
}
concat(e) {
if (!!e && e !== this.dtype)
throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);
if (this.size() === 0)
return ms([], [0].concat(this.elementShape));
let t = [];
for (let s = 0; s < this.size(); s++)
t.push(s);
let n = this.readMany(t);
return jn(this.elementShape, n[0].shape, `TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`), Ft(n, 0);
}
scatter(e, t) {
if (t.dtype !== this.dtype)
throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);
if (e.length !== t.shape[0])
throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);
let n = Math.max(...e);
if (!this.dynamicSize && n >= this.maxSize)
throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);
this.writeMany(e, Fs(t, 0));
}
split(e, t) {
if (t.dtype !== this.dtype)
throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);
let n = 0, s = e.map((i) => (n += i, n));
if (n !== t.shape[0])
throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${n}, and tensor's shape is: ${t.shape}`);
if (!this.dynamicSize && e.length !== this.maxSize)
throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);
let r = n === 0 ? 0 : t.size / n, a = [];
q(() => {
t = U(t, [1, n, r]);
for (let i = 0; i < e.length; ++i) {
let u = i === 0 ? 0 : s[i - 1], l = [0, u, 0], c = [1, e[i], r];
a[i] = U(qe(t, l, c), this.elementShape);
}
return a;
});
let o = [];
for (let i = 0; i < e.length; i++)
o[i] = i;
this.writeMany(o, a);
}
};
var ri = class {
constructor(e, t, n, s = -1) {
this.tensors = e, this.elementShape = t, this.elementDtype = n, e != null && e.forEach((r) => {
if (n !== r.dtype)
throw new Error(`Invalid data types; op elements ${n}, but list elements ${r.dtype}`);
jn(t, r.shape, "TensorList shape mismatch: "), qt(r);
}), this.idTensor = we(0), this.maxNumElements = s, qt(this.idTensor);
}
get id() {
return this.idTensor.id;
}
copy() {
return new ri([...this.tensors], this.elementShape, this.elementDtype);
}
clearAndClose(e) {
this.tensors.forEach((t) => {
(e == null || !e.has(t.id)) && t.dispose();
}), this.tensors.length = 0, this.idTensor.dispose();
}
size() {
return this.tensors.length;
}
stack(e, t, n = -1) {
if (t !== this.elementDtype)
throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);
if (n !== -1 && this.tensors.length !== n)
throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);
jn(e, this.elementShape, "TensorList shape mismatch: ");
let s = Au(this.elementShape, this.tensors, e);
return q(() => {
let r = this.tensors.map((a) => U(a, s));
return es(r, 0);
});
}
popBack(e, t) {
if (t !== this.elementDtype)
throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);
if (this.size() === 0)
throw new Error("Trying to pop from an empty list.");
let n = Au(this.elementShape, this.tensors, e), s = this.tensors.pop();
return jn(s.shape, e, "TensorList shape mismatch: "), U(s, n);
}
pushBack(e) {
if (e.dtype !== this.elementDtype)
throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);
if (jn(e.shape, this.elementShape, "TensorList shape mismatch: "), this.maxNumElements === this.size())
throw new Error("Trying to push element into a full list.");
qt(e), this.tensors.push(e);
}
resize(e) {
if (e < 0)
throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);
if (this.maxNumElements !== -1 && e > this.maxNumElements)
throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);
let t = new ri([], this.elementShape, this.elementDtype, this.maxNumElements);
t.tensors.length = e;
for (let n = 0; n < Math.min(this.tensors.length, e); ++n)
t.tensors[n] = this.tensors[n];
return t;
}
getItem(e, t, n) {
if (n !== this.elementDtype)
throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);
if (e < 0 || e > this.tensors.length)
throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);
if (this.tensors[e] == null)
throw new Error(`element at index ${e} is null.`);
jn(this.tensors[e].shape, t, "TensorList shape mismatch: ");
let s = Au(this.elementShape, this.tensors, t);
return U(this.tensors[e], s);
}
setItem(e, t) {
if (t.dtype !== this.elementDtype)
throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);
if (e < 0 || this.maxNumElements !== -1 && e >= this.maxNumElements)
throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);
jn(this.elementShape, t.shape, "TensorList shape mismatch: "), qt(t), this.tensors[e] = t;
}
gather(e, t, n) {
if (t !== this.elementDtype)
throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);
jn(this.elementShape, n, "TensorList shape mismatch: "), e = e.slice(0, this.size());
let s = Au(this.elementShape, this.tensors, n);
return e.length === 0 ? ms([], [0].concat(s)) : q(() => {
let r = e.map((a) => U(this.tensors[a], s));
return es(r, 0);
});
}
concat(e, t) {
if (!!e && e !== this.elementDtype)
throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);
jn(this.elementShape, t, "TensorList shape mismatch: ");
let n = Au(this.elementShape, this.tensors, t);
return this.size() === 0 ? ms([], [0].concat(n)) : q(() => {
let s = this.tensors.map((r) => U(r, n));
return Ft(s, 0);
});
}
};
function $4(e, t, n) {
let s = e.dtype;
if (e.shape.length < 1)
throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);
if (e.dtype !== n)
throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);
let r = e.shape.slice(1);
jn(r, t, "TensorList shape mismatch: ");
let a = Fs(e);
return new ri(a, t, s);
}
function _4(e, t, n) {
return new ri([], e, t, n);
}
function A4(e, t, n, s) {
if (t.length !== e.shape[0])
throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);
let r = Math.max(...t);
if (s != null && s !== -1 && r >= s)
throw new Error(`Max index must be < array size (${r} vs. ${s})`);
let a = new ri([], n, e.dtype, s), o = Fs(e, 0);
return t.forEach((i, u) => {
a.setItem(i, o[u]);
}), a;
}
function E4(e, t, n) {
let s = 0, r = t.map((c) => (s += c, s));
if (s !== e.shape[0])
throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${s}, and tensor's shape is: ${e.shape}`);
let a = e.shape.slice(1), o = Km(a, n), i = s === 0 ? 0 : e.size / s, u = q(() => {
let c = [];
e = U(e, [1, s, i]);
for (let p = 0; p < t.length; ++p) {
let d = p === 0 ? 0 : r[p - 1], h = [0, d, 0], f = [1, t[p], i];
c[p] = U(qe(e, h, f), o);
}
return e.dispose(), c;
}), l = new ri([], n, e.dtype, t.length);
for (let c = 0; c < u.length; c++)
l.setItem(c, u[c]);
return l;
}
var R4 = async (e, t, n) => {
switch (e.op) {
case "If":
case "StatelessIf": {
let s = S("thenBranch", e, t, n), r = S("elseBranch", e, t, n), a = S("cond", e, t, n), o = S("args", e, t, n);
return (await a.data())[0] ? n.functionMap[s].executeFunctionAsync(o, n.tensorArrayMap, n.tensorListMap) : n.functionMap[r].executeFunctionAsync(o, n.tensorArrayMap, n.tensorListMap);
}
case "While":
case "StatelessWhile": {
let s = S("body", e, t, n), r = S("cond", e, t, n), a = S("args", e, t, n), o = await n.functionMap[r].executeFunctionAsync(a, n.tensorArrayMap, n.tensorListMap), i = a.map((c) => c.id), u = await o[0].data();
o.forEach((c) => {
!c.kept && i.indexOf(c.id) === -1 && c.dispose();
});
let l = a;
for (; u[0]; ) {
let c = l;
l = await n.functionMap[s].executeFunctionAsync(l, n.tensorArrayMap, n.tensorListMap);
let p = l.map((h) => h.id);
c.forEach((h) => {
!h.kept && i.indexOf(h.id) === -1 && p.indexOf(h.id) === -1 && h.dispose();
});
let d = await n.functionMap[r].executeFunctionAsync(l, n.tensorArrayMap, n.tensorListMap);
u = await d[0].data(), d.forEach((h) => {
!h.kept && i.indexOf(h.id) === -1 && p.indexOf(h.id) === -1 && h.dispose();
});
}
return l;
}
case "LoopCond": {
let s = S("pred", e, t, n);
return [Ws(s)];
}
case "Switch": {
let s = S("pred", e, t, n), r = S("data", e, t, n);
return r.kept || (r = Ws(r)), (await s.data())[0] ? [void 0, r] : [r, void 0];
}
case "Merge": {
let s = e.inputNames.find((r) => un(r, t, n) !== void 0);
if (s) {
let r = un(s, t, n);
return [Ws(r)];
}
return;
}
case "Enter": {
let s = S("frameName", e, t, n), r = S("tensor", e, t, n);
return n.enterFrame(s), [Ws(r)];
}
case "Exit": {
let s = S("tensor", e, t, n);
return n.exitFrame(), [Ws(s)];
}
case "NextIteration": {
let s = S("tensor", e, t, n);
return n.nextIteration(), [Ws(s)];
}
case "TensorArrayV3": {
let s = S("size", e, t, n), r = S("dtype", e, t, n), a = S("elementShape", e, t, n), o = S("dynamicSize", e, t, n), i = S("clearAfterRead", e, t, n), u = S("identicalElementShapes", e, t, n), l = S("name", e, t, n), c = new T4(l, r, s, a, u, o, i);
return n.addTensorArray(c), [c.idTensor, we(1)];
}
case "TensorArrayWriteV3": {
let s = S("tensorArrayId", e, t, n), r = S("index", e, t, n), a = S("tensor", e, t, n), o = n.getTensorArray(s.id);
return o.write(r, a), [o.idTensor];
}
case "TensorArrayReadV3": {
let s = S("tensorArrayId", e, t, n), r = S("index", e, t, n);
return [n.getTensorArray(s.id).read(r)];
}
case "TensorArrayGatherV3": {
let s = S("tensorArrayId", e, t, n), r = S("indices", e, t, n), a = S("dtype", e, t, n);
return [n.getTensorArray(s.id).gather(r, a)];
}
case "TensorArrayScatterV3": {
let s = S("tensorArrayId", e, t, n), r = S("indices", e, t, n), a = S("tensor", e, t, n), o = n.getTensorArray(s.id);
return o.scatter(r, a), [o.idTensor];
}
case "TensorArrayConcatV3": {
let s = S("tensorArrayId", e, t, n), r = n.getTensorArray(s.id), a = S("dtype", e, t, n);
return [r.concat(a)];
}
case "TensorArraySplitV3": {
let s = S("tensorArrayId", e, t, n), r = S("tensor", e, t, n), a = S("lengths", e, t, n), o = n.getTensorArray(s.id);
return o.split(a, r), [o.idTensor];
}
case "TensorArraySizeV3": {
let s = S("tensorArrayId", e, t, n), r = n.getTensorArray(s.id);
return [we(r.size(), "int32")];
}
case "TensorArrayCloseV3": {
let s = S("tensorArrayId", e, t, n), r = n.getTensorArray(s.id);
return r.clearAndClose(), [r.idTensor];
}
case "TensorListSetItem": {
let s = S("tensorListId", e, t, n), r = S("index", e, t, n), a = S("tensor", e, t, n), o = n.getTensorList(s.id);
return o.setItem(r, a), [o.idTensor];
}
case "TensorListGetItem": {
let s = S("tensorListId", e, t, n), r = S("index", e, t, n), a = S("elementShape", e, t, n), o = S("elementDType", e, t, n);
return [n.getTensorList(s.id).getItem(r, a, o)];
}
case "TensorListScatterV2":
case "TensorListScatter": {
let s = S("indices", e, t, n), r = S("tensor", e, t, n), a = S("elementShape", e, t, n), o = S("numElements", e, t, n), i = A4(r, s, a, o);
return n.addTensorList(i), [i.idTensor];
}
case "TensorListReserve":
case "EmptyTensorList": {
let s = S("elementShape", e, t, n), r = S("elementDType", e, t, n), a;
e.op === "TensorListReserve" ? a = "numElements" : a = "maxNumElements";
let o = S(a, e, t, n), i = _4(s, r, o);
return n.addTensorList(i), [i.idTensor];
}
case "TensorListGather": {
let s = S("tensorListId", e, t, n), r = S("indices", e, t, n), a = S("elementShape", e, t, n), o = S("elementDType", e, t, n);
return [n.getTensorList(s.id).gather(r, o, a)];
}
case "TensorListStack": {
let s = S("tensorListId", e, t, n), r = S("elementShape", e, t, n), a = S("elementDType", e, t, n), o = S("numElements", e, t, n);
return [n.getTensorList(s.id).stack(r, a, o)];
}
case "TensorListFromTensor": {
let s = S("tensor", e, t, n), r = S("elementShape", e, t, n), a = S("elementDType", e, t, n), o = $4(s, r, a);
return n.addTensorList(o), [o.idTensor];
}
case "TensorListConcat":
case "TensorListConcatV2": {
let s = S("tensorListId", e, t, n), r = n.getTensorList(s.id), a = S("dtype", e, t, n), o = S("elementShape", e, t, n);
return [r.concat(a, o)];
}
case "TensorListPushBack": {
let s = S("tensorListId", e, t, n), r = S("tensor", e, t, n), a = n.getTensorList(s.id);
return a.pushBack(r), [a.idTensor];
}
case "TensorListPopBack": {
let s = S("tensorListId", e, t, n), r = S("elementShape", e, t, n), a = S("elementDType", e, t, n);
return [n.getTensorList(s.id).popBack(r, a)];
}
case "TensorListSplit": {
let s = S("tensor", e, t, n), r = S("elementShape", e, t, n), a = S("lengths", e, t, n), o = E4(s, a, r);
return n.addTensorList(o), [o.idTensor];
}
case "TensorListLength": {
let s = S("tensorListId", e, t, n), r = n.getTensorList(s.id);
return [we(r.size(), "int32")];
}
case "TensorListResize": {
let s = S("tensorListId", e, t, n), r = S("size", e, t, n), o = n.getTensorList(s.id).resize(r);
return n.addTensorList(o), [o.idTensor];
}
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
function aw(e, t, n) {
let [s, r] = S("fusedOps", e, t, n), a = s === "biasadd", o = !a, i = r === "prelu", u = s === "fusedbatchnorm", l = S("numArgs", e, t, n);
if (a) {
if (i && l !== 2)
throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");
if (!i && a && l !== 1)
throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.");
}
if (u)
throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");
let c = S("strides", e, t, n), p = ud(e, t, n), d = S("dataFormat", e, t, n).toUpperCase(), h = S("dilations", e, t, n), [f, m] = S("args", e, t, n);
o && (m = f, f = void 0);
let g = S("leakyreluAlpha", e, t, n);
return { stride: c, pad: p, dataFormat: d, dilations: h, biasArg: f, preluArg: m, activationFunc: r, leakyreluAlpha: g };
}
var D4 = (e, t, n) => {
switch (e.op) {
case "Conv1D": {
let s = S("stride", e, t, n), r = S("pad", e, t, n), a = S("dataFormat", e, t, n).toUpperCase(), o = S("dilation", e, t, n);
return [mS(S("x", e, t, n), S("filter", e, t, n), s, r, a, o)];
}
case "Conv2D": {
let s = S("strides", e, t, n), r = ud(e, t, n), a = S("dataFormat", e, t, n).toUpperCase(), o = S("dilations", e, t, n);
return [da(S("x", e, t, n), S("filter", e, t, n), [s[1], s[2]], r, a, [o[1], o[2]])];
}
case "_FusedConv2D": {
let { stride: s, pad: r, dataFormat: a, dilations: o, biasArg: i, preluArg: u, activationFunc: l, leakyreluAlpha: c } = aw(e, t, n);
return [fa.conv2d({ x: S("x", e, t, n), filter: S("filter", e, t, n), strides: [s[1], s[2]], pad: r, dataFormat: a, dilations: [o[1], o[2]], bias: i, activation: l, preluActivationWeights: u, leakyreluAlpha: c })];
}
case "FusedDepthwiseConv2dNative": {
let { stride: s, pad: r, dataFormat: a, dilations: o, biasArg: i, preluArg: u, activationFunc: l, leakyreluAlpha: c } = aw(e, t, n);
return [fa.depthwiseConv2d({ x: S("x", e, t, n), filter: S("filter", e, t, n), strides: [s[1], s[2]], pad: r, dataFormat: a, dilations: [o[1], o[2]], bias: i, activation: l, preluActivationWeights: u, leakyreluAlpha: c })];
}
case "Conv2DBackpropInput":
case "Conv2dTranspose": {
let s = S("outputShape", e, t, n), r = S("strides", e, t, n), a = ud(e, t, n);
return [gS(S("x", e, t, n), S("filter", e, t, n), s, [r[1], r[2]], a)];
}
case "DepthwiseConv2dNative":
case "DepthwiseConv2d": {
let s = S("strides", e, t, n), r = ud(e, t, n), a = S("dilations", e, t, n), o = S("dataFormat", e, t, n).toUpperCase();
return [kp(S("input", e, t, n), S("filter", e, t, n), [s[1], s[2]], r, o, [a[1], a[2]])];
}
case "Conv3D": {
let s = S("strides", e, t, n), r = S("pad", e, t, n), a = S("dataFormat", e, t, n).toUpperCase(), o = S("dilations", e, t, n);
return [bS(S("x", e, t, n), S("filter", e, t, n), [s[1], s[2], s[3]], r, a, [o[1], o[2], o[3]])];
}
case "AvgPool": {
let s = S("strides", e, t, n), r = S("pad", e, t, n), a = S("kernelSize", e, t, n);
return [nb(S("x", e, t, n), [a[1], a[2]], [s[1], s[2]], r)];
}
case "MaxPool": {
let s = S("strides", e, t, n), r = S("pad", e, t, n), a = S("kernelSize", e, t, n);
return [pb(S("x", e, t, n), [a[1], a[2]], [s[1], s[2]], r)];
}
case "MaxPoolWithArgmax": {
let s = S("strides", e, t, n), r = S("pad", e, t, n), a = S("kernelSize", e, t, n), o = S("includeBatchInIndex", e, t, n), { result: i, indexes: u } = WD(S("x", e, t, n), [a[1], a[2]], [s[1], s[2]], r, o);
return [i, u];
}
case "AvgPool3D": {
let s = S("strides", e, t, n), r = S("pad", e, t, n), a = S("kernelSize", e, t, n);
return [hS(S("x", e, t, n), [a[1], a[2], a[3]], [s[1], s[2], s[3]], r)];
}
case "MaxPool3D": {
let s = S("strides", e, t, n), r = S("pad", e, t, n), a = S("kernelSize", e, t, n);
return [AS(S("x", e, t, n), [a[1], a[2], a[3]], [s[1], s[2], s[3]], r)];
}
case "Dilation2D": {
let s = S("strides", e, t, n), r = S("pad", e, t, n), a = S("dilations", e, t, n), o = s[1], i = s[2], u = a[1], l = a[2];
return [OR(S("x", e, t, n), S("filter", e, t, n), [o, i], r, [u, l], "NHWC")];
}
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
var F4 = (e, t, n) => {
switch (e.op) {
case "Fill": {
let s = S("shape", e, t, n), r = S("dtype", e, t, n), a = S("value", e, t, n);
return [Bl(s, a, r)];
}
case "LinSpace": {
let s = S("start", e, t, n), r = S("stop", e, t, n), a = S("num", e, t, n);
return [wD(s, r, a)];
}
case "Multinomial": {
let s = S("logits", e, t, n), r = S("numSamples", e, t, n), a = S("seed", e, t, n);
return [JD(s, r, a)];
}
case "OneHot": {
let s = S("indices", e, t, n), r = S("depth", e, t, n), a = S("onValue", e, t, n), o = S("offValue", e, t, n);
return [Cd(s, r, a, o)];
}
case "Ones":
return [Ln(S("shape", e, t, n), S("dtype", e, t, n))];
case "OnesLike":
return [Zn(S("x", e, t, n))];
case "RandomUniform":
return [Wl(S("shape", e, t, n), S("minval", e, t, n), S("maxval", e, t, n), S("dtype", e, t, n))];
case "Range": {
let s = S("start", e, t, n), r = S("stop", e, t, n), a = S("step", e, t, n);
return [tl(s, r, a, S("dtype", e, t, n))];
}
case "TruncatedNormal": {
let s = S("shape", e, t, n), r = S("mean", e, t, n), a = S("stdDev", e, t, n), o = S("seed", e, t, n);
return [Sb(s, r, a, S("dtype", e, t, n), o)];
}
case "Zeros":
return [$t(S("shape", e, t, n), S("dtype", e, t, n))];
case "ZerosLike":
return [je(S("x", e, t, n))];
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
function nm(e, t, n) {
let s = S("boxes", e, t, n), r = S("scores", e, t, n), a = S("maxOutputSize", e, t, n), o = S("iouThreshold", e, t, n), i = S("scoreThreshold", e, t, n), u = S("softNmsSigma", e, t, n);
return { boxes: s, scores: r, maxOutputSize: a, iouThreshold: o, scoreThreshold: i, softNmsSigma: u };
}
var O4 = async (e, t, n) => {
switch (e.op) {
case "NonMaxSuppressionV5": {
let { boxes: s, scores: r, maxOutputSize: a, iouThreshold: o, scoreThreshold: i, softNmsSigma: u } = nm(e, t, n), l = await Kn.nonMaxSuppressionWithScoreAsync(s, r, a, o, i, u);
return [l.selectedIndices, l.selectedScores];
}
case "NonMaxSuppressionV4": {
let { boxes: s, scores: r, maxOutputSize: a, iouThreshold: o, scoreThreshold: i } = nm(e, t, n), u = S("padToMaxOutputSize", e, t, n), l = await Kn.nonMaxSuppressionPaddedAsync(s, r, a, o, i, u);
return [l.selectedIndices, l.validOutputs];
}
case "NonMaxSuppressionV3":
case "NonMaxSuppressionV2": {
let { boxes: s, scores: r, maxOutputSize: a, iouThreshold: o, scoreThreshold: i } = nm(e, t, n);
return [await Kn.nonMaxSuppressionAsync(s, r, a, o, i)];
}
case "Where": {
let s = le(S("condition", e, t, n), "bool"), r = [await WS(s)];
return s.dispose(), r;
}
case "ListDiff":
return P3(S("x", e, t, n), S("y", e, t, n));
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
var P4 = (e, t, n) => {
switch (e.op) {
case "LowerBound": {
let s = S("sortedSequence", e, t, n), r = S("values", e, t, n);
return [LD(s, r)];
}
case "TopKV2": {
let s = S("x", e, t, n), r = S("k", e, t, n), a = S("sorted", e, t, n), o = oF(s, r, a);
return [o.values, o.indices];
}
case "UpperBound": {
let s = S("sortedSequence", e, t, n), r = S("values", e, t, n);
return [pF(s, r)];
}
case "Unique": {
let s = S("x", e, t, n), r = Ix(s);
return [r.values, r.indices];
}
case "UniqueV2": {
let s = S("x", e, t, n), r = S("axis", e, t, n), a = Ix(s, r);
return [a.values, a.indices];
}
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
var z4 = (e, t, n) => {
switch (e.op) {
case "Const":
return t[e.name];
case "PlaceholderWithDefault":
let s = S("default", e, t, n);
return [un(e.name, t, n) || s];
case "Placeholder":
return [un(e.name, t, n)];
case "Identity":
case "StopGradient":
case "FakeQuantWithMinMaxVars": {
let l = S("x", e, t, n);
return [Ws(l)];
}
case "IdentityN":
return S("x", e, t, n).map((l) => Ws(l));
case "Snapshot":
let r = S("x", e, t, n);
return [Ws(r)];
case "Shape":
return [Zt(S("x", e, t, n).shape, "int32")];
case "ShapeN":
return S("x", e, t, n).map((l) => Zt(l.shape));
case "Size":
return [we(S("x", e, t, n).size, "int32")];
case "Rank":
return [we(S("x", e, t, n).rank, "int32")];
case "NoOp":
return [we(1)];
case "Print":
let a = S("x", e, t, n), o = S("data", e, t, n), i = S("message", e, t, n), u = S("summarize", e, t, n);
console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."), console.log(i);
for (let l = 0; l < o.length; l++)
console.log(Array.prototype.slice.call(o[l].dataSync()).slice(0, u));
return [a];
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
var L4 = class {
constructor(e, t) {
this.keyDType = e, this.valueDType = t, this.handle = we(0), this.tensorMap = /* @__PURE__ */ new Map(), qt(this.handle);
}
get id() {
return this.handle.id;
}
clearAndClose() {
this.tensorMap.forEach((e) => e.dispose()), this.tensorMap.clear(), this.handle.dispose();
}
size() {
return this.tensorMap.size;
}
tensorSize() {
return we(this.size(), "int32");
}
async import(e, t) {
this.checkKeyAndValueTensor(e, t);
let n = await e.data();
return this.tensorMap.forEach((s) => s.dispose()), this.tensorMap.clear(), q(() => {
let s = Fs(t), r = n.length, a = s.length;
w.assert(r === a, () => `The number of elements doesn't match, keys has ${r} elements, the values has ${a} elements.`);
for (let o = 0; o < r; o++) {
let i = n[o], u = s[o];
qt(u), this.tensorMap.set(i, u);
}
return this.handle;
});
}
async find(e, t) {
this.checkKeyAndValueTensor(e, t);
let n = await e.data();
return q(() => {
let s = [];
for (let r = 0; r < n.length; r++) {
let a = n[r], o = this.findWithDefault(a, t);
s.push(o);
}
return es(s);
});
}
findWithDefault(e, t) {
let n = this.tensorMap.get(e);
return n != null ? n : t;
}
checkKeyAndValueTensor(e, t) {
if (e.dtype !== this.keyDType)
throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);
if (t.dtype !== this.valueDType)
throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`);
}
};
var M4 = async (e, t, n, s) => {
switch (e.op) {
case "HashTable":
case "HashTableV2": {
let r = S("keyDType", e, t, n), a = S("valueDType", e, t, n), o = new L4(r, a);
return s.addHashTable(e.name, o), [o.handle];
}
case "LookupTableImport":
case "LookupTableImportV2": {
let r = S("tableHandle", e, t, n, s), a = S("keys", e, t, n), o = S("values", e, t, n);
return [await s.getHashTableById(r.id).import(a, o)];
}
case "LookupTableFind":
case "LookupTableFindV2": {
let r = S("tableHandle", e, t, n, s), a = S("keys", e, t, n), o = S("defaultValue", e, t, n);
return [await s.getHashTableById(r.id).find(a, o)];
}
case "LookupTableSize":
case "LookupTableSizeV2": {
let r = S("tableHandle", e, t, n, s);
return [s.getHashTableById(r.id).tensorSize()];
}
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
var B4 = (e, t, n) => {
switch (e.op) {
case "ResizeBilinear": {
let s = S("images", e, t, n), r = S("size", e, t, n), a = S("alignCorners", e, t, n), o = S("halfPixelCenters", e, t, n);
return [Kn.resizeBilinear(s, [r[0], r[1]], a, o)];
}
case "ResizeNearestNeighbor": {
let s = S("images", e, t, n), r = S("size", e, t, n), a = S("alignCorners", e, t, n), o = S("halfPixelCenters", e, t, n);
return [Kn.resizeNearestNeighbor(s, [r[0], r[1]], a, o)];
}
case "CropAndResize": {
let s = S("image", e, t, n), r = S("boxes", e, t, n), a = S("boxInd", e, t, n), o = S("cropSize", e, t, n), i = S("method", e, t, n), u = S("extrapolationValue", e, t, n);
return [Kn.cropAndResize(s, r, a, o, i, u)];
}
case "ImageProjectiveTransformV3": {
let s = S("images", e, t, n), r = S("transforms", e, t, n), a = S("outputShape", e, t, n), o = S("fillValue", e, t, n), i = S("interpolation", e, t, n), u = S("fillMode", e, t, n);
return [Kn.transform(s, r, i.toLowerCase(), u.toLowerCase(), o, a)];
}
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
var V4 = (e, t, n) => {
switch (e.op) {
case "Equal":
return [Xn(S("a", e, t, n), S("b", e, t, n))];
case "NotEqual":
return [el(S("a", e, t, n), S("b", e, t, n))];
case "Greater":
return [Gn(S("a", e, t, n), S("b", e, t, n))];
case "GreaterEqual":
return [Zi(S("a", e, t, n), S("b", e, t, n))];
case "Less":
return [NS(S("a", e, t, n), S("b", e, t, n))];
case "LessEqual":
return [Ji(S("a", e, t, n), S("b", e, t, n))];
case "LogicalAnd":
return [Ds(S("a", e, t, n), S("b", e, t, n))];
case "LogicalNot":
return [db(S("a", e, t, n))];
case "LogicalOr":
return [$S(S("a", e, t, n), S("b", e, t, n))];
case "Select":
case "SelectV2":
return [vn(S("condition", e, t, n), S("a", e, t, n), S("b", e, t, n))];
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
var W4 = (e, t, n) => {
switch (e.op) {
case "BatchMatMul":
case "BatchMatMulV2":
case "MatMul":
return [We(S("a", e, t, n), S("b", e, t, n), S("transposeA", e, t, n), S("transposeB", e, t, n))];
case "Einsum":
return [UR(S("equation", e, t, n), ...S("tensors", e, t, n))];
case "Transpose":
return [Ge(S("x", e, t, n), S("perm", e, t, n))];
case "_FusedMatMul":
let [s, r] = S("fusedOps", e, t, n), a = s === "biasadd", o = r === "prelu", i = S("numArgs", e, t, n), u = S("leakyreluAlpha", e, t, n);
if (a) {
if (o && i !== 2)
throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");
if (!o && i !== 1)
throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.");
}
let [l, c] = S("args", e, t, n);
return [fa.matMul({ a: S("a", e, t, n), b: S("b", e, t, n), transposeA: S("transposeA", e, t, n), transposeB: S("transposeB", e, t, n), bias: l, activation: r, preluActivationWeights: c, leakyreluAlpha: u })];
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
var U4 = (e, t, n) => {
switch (e.op) {
case "EuclideanNorm":
return [sD(S("x", e, t, n), S("axis", e, t, n), S("keepDims", e, t, n))];
case "FusedBatchNorm":
case "FusedBatchNormV2":
return [Zu(S("x", e, t, n), S("mean", e, t, n), S("variance", e, t, n), S("offset", e, t, n), S("scale", e, t, n), S("epsilon", e, t, n))];
case "FusedBatchNormV3":
return [Zu(S("x", e, t, n), S("mean", e, t, n), S("variance", e, t, n), S("offset", e, t, n), S("scale", e, t, n), S("epsilon", e, t, n))];
case "LRN":
return [SD(S("x", e, t, n), S("radius", e, t, n), S("bias", e, t, n), S("alpha", e, t, n), S("beta", e, t, n))];
case "Softmax":
return [xb(S("x", e, t, n))];
case "LogSoftmax":
return [TS(S("x", e, t, n))];
case "SparseToDense":
return [US(S("sparseIndices", e, t, n), S("outputShape", e, t, n), S("sparseValues", e, t, n), S("defaultValue", e, t, n))];
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
var G4 = (e, t, n) => {
switch (e.op) {
case "Max": {
let o = S("axis", e, t, n), i = S("keepDims", e, t, n);
return [As(S("x", e, t, n), o, i)];
}
case "Mean": {
let o = S("axis", e, t, n), i = S("keepDims", e, t, n);
return [It(S("x", e, t, n), o, i)];
}
case "Min": {
let o = S("axis", e, t, n), i = S("keepDims", e, t, n);
return [Nm(S("x", e, t, n), o, i)];
}
case "Sum": {
let o = S("axis", e, t, n), i = S("keepDims", e, t, n);
return [ve(S("x", e, t, n), o, i)];
}
case "All": {
let o = S("axis", e, t, n), i = S("keepDims", e, t, n);
return [lS(S("x", e, t, n), o, i)];
}
case "Any": {
let o = S("axis", e, t, n), i = S("keepDims", e, t, n);
return [Sm(S("x", e, t, n), o, i)];
}
case "ArgMax": {
let o = S("axis", e, t, n);
return [Yu(S("x", e, t, n), o)];
}
case "ArgMin": {
let o = S("axis", e, t, n);
return [wE(S("x", e, t, n), o)];
}
case "Prod": {
let o = S("axis", e, t, n), i = S("keepDims", e, t, n);
return [ES(S("x", e, t, n), o, i)];
}
case "Cumprod": {
let o = S("axis", e, t, n), i = S("exclusive", e, t, n), u = S("reverse", e, t, n);
return [Cm(S("x", e, t, n), o, i, u)];
}
case "Cumsum": {
let o = S("axis", e, t, n), i = S("exclusive", e, t, n), u = S("reverse", e, t, n);
return [xS(S("x", e, t, n), o, i, u)];
}
case "Bincount":
let s = S("x", e, t, n), r = S("weights", e, t, n), a = S("size", e, t, n);
return [fS(s, r, a)];
case "DenseBincount": {
let o = S("x", e, t, n), i = S("weights", e, t, n), u = S("size", e, t, n), l = S("binaryOutput", e, t, n);
return [_R(o, i, u, l)];
}
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
var H4 = (e, t, n) => {
switch (e.op) {
case "ConcatV2":
case "Concat": {
let s = S("n", e, t, n), r = S("axis", e, t, n), a = S("tensors", e, t, n);
return a = a.slice(0, s), [Ft(a, r)];
}
case "Gather": {
let s = S("x", e, t, n), r = S("indices", e, t, n);
return [Ju(s, le(r, "int32"), 0)];
}
case "GatherV2": {
let s = S("axis", e, t, n), r = S("batchDims", e, t, n), a = S("x", e, t, n), o = S("indices", e, t, n);
return [Ju(a, le(o, "int32"), s, r)];
}
case "Reverse": {
let s = S("dims", e, t, n), r = [];
for (let o = 0; o < s.length; o++)
s[o] && r.push(o);
let a = S("x", e, t, n);
return [Jn(a, r)];
}
case "ReverseV2": {
let s = S("axis", e, t, n), r = S("x", e, t, n);
return [Jn(r, s)];
}
case "Slice": {
let s = S("begin", e, t, n), r = S("size", e, t, n);
return [qe(S("x", e, t, n), s, r)];
}
case "StridedSlice": {
let s = S("begin", e, t, n), r = S("end", e, t, n), a = S("strides", e, t, n), o = S("beginMask", e, t, n), i = S("endMask", e, t, n), u = S("ellipsisMask", e, t, n), l = S("newAxisMask", e, t, n), c = S("shrinkAxisMask", e, t, n), p = S("x", e, t, n);
return [nF(p, s, r, a, o, i, u, l, c)];
}
case "Pack":
return q(() => {
let s = S("axis", e, t, n), r = S("tensors", e, t, n), a = r[0].shape, o = br(r[0]).shape, i = r.map((u) => {
let l = w.arraysEqual(u.shape, a);
if (!l && !w.arraysEqual(br(u).shape, o))
throw new Error("the input tensors shape does not match");
return l ? u : U(u, a);
});
return [es(i, s)];
});
case "Unpack": {
let s = S("axis", e, t, n), r = S("tensor", e, t, n);
return Fs(r, s);
}
case "Tile": {
let s = S("reps", e, t, n);
return [hs(S("x", e, t, n), s)];
}
case "Split":
case "SplitV": {
let s = S("axis", e, t, n), r = S("numOrSizeSplits", e, t, n), a = S("x", e, t, n);
return Bn(a, r, s);
}
case "ScatterNd": {
let s = S("indices", e, t, n), r = S("values", e, t, n), a = S("shape", e, t, n);
return [yF(s, r, a)];
}
case "GatherNd": {
let s = S("x", e, t, n), r = S("indices", e, t, n);
return [kF(s, r)];
}
case "SparseToDense": {
let s = S("sparseIndices", e, t, n), r = S("outputShape", e, t, n), a = S("sparseValues", e, t, n), o = S("defaultValue", e, t, n);
return [US(s, a, r, a.dtype === o.dtype ? o : le(o, a.dtype))];
}
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
var q4 = (e, t, n) => {
switch (e.op) {
case "SparseFillEmptyRows": {
let { outputIndices: s, outputValues: r, emptyRowIndicator: a, reverseIndexMap: o } = jc.sparseFillEmptyRows(S("indices", e, t, n), S("values", e, t, n), S("denseShape", e, t, n), S("defaultValue", e, t, n));
return [s, r, a, o];
}
case "SparseReshape": {
let { outputIndices: s, outputShape: r } = jc.sparseReshape(S("inputIndices", e, t, n), S("inputShape", e, t, n), S("newShape", e, t, n));
return [s, r];
}
case "SparseSegmentMean":
return [jc.sparseSegmentMean(S("data", e, t, n), S("indices", e, t, n), S("segmentIds", e, t, n))];
case "SparseSegmentSum":
return [jc.sparseSegmentSum(S("data", e, t, n), S("indices", e, t, n), S("segmentIds", e, t, n))];
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
var j4 = (e, t, n) => {
switch (e.op) {
case "FFT":
return [wb(S("x", e, t, n))];
case "IFFT":
return [$d(S("x", e, t, n))];
case "RFFT":
return [kb(S("x", e, t, n))];
case "IRFFT":
return [MS(S("x", e, t, n))];
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
var K4 = (e, t, n) => {
switch (e.op) {
case "StringNGrams": {
let { nGrams: s, nGramsSplits: r } = Yf.stringNGrams(S("data", e, t, n), S("dataSplits", e, t, n), S("separator", e, t, n), S("nGramWidths", e, t, n), S("leftPad", e, t, n), S("rightPad", e, t, n), S("padWidth", e, t, n), S("preserveShortSequences", e, t, n));
return [s, r];
}
case "StringSplit": {
let { indices: s, values: r, shape: a } = Yf.stringSplit(S("input", e, t, n), S("delimiter", e, t, n), S("skipEmpty", e, t, n));
return [s, r, a];
}
case "StringToHashBucketFast":
return [Yf.stringToHashBucketFast(S("input", e, t, n), S("numBuckets", e, t, n))];
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
var X4 = (e, t, n) => {
switch (e.op) {
case "Cast":
return [le(S("x", e, t, n), S("dtype", e, t, n))];
case "ExpandDims": {
let s = S("axis", e, t, n);
return [Pn(S("x", e, t, n), s)];
}
case "Squeeze": {
let s = S("axis", e, t, n);
return [br(S("x", e, t, n), s)];
}
case "Reshape":
return [U(S("x", e, t, n), S("shape", e, t, n))];
case "MirrorPad":
return [jD(S("x", e, t, n), S("padding", e, t, n), S("mode", e, t, n))];
case "PadV2":
case "Pad":
return [bo(S("x", e, t, n), S("padding", e, t, n), S("constantValue", e, t, n))];
case "SpaceToBatchND": {
let s = S("blockShape", e, t, n), r = S("paddings", e, t, n);
return [fb(S("x", e, t, n), s, r)];
}
case "BatchToSpaceND": {
let s = S("blockShape", e, t, n), r = S("crops", e, t, n);
return [sb(S("x", e, t, n), s, r)];
}
case "DepthToSpace": {
let s = S("blockSize", e, t, n), r = S("dataFormat", e, t, n).toUpperCase();
return [ER(S("x", e, t, n), s, r)];
}
case "BroadcastTo":
return [id(S("x", e, t, n), S("shape", e, t, n))];
case "BroadcastArgs":
return [sR(S("s0", e, t, n), S("s1", e, t, n))];
default:
throw TypeError(`Node type ${e.op} is not implemented`);
}
};
function ow(e, t, n, s) {
let r = ((a, o, i) => {
switch (a.category) {
case "arithmetic":
return q(() => C4(a, o, i));
case "basic_math":
return q(() => N4(a, o, i));
case "control":
return R4(a, o, i);
case "convolution":
return q(() => D4(a, o, i));
case "creation":
return q(() => F4(a, o, i));
case "dynamic":
return O4(a, o, i);
case "evaluation":
return q(() => P4(a, o, i));
case "image":
return q(() => B4(a, o, i));
case "graph":
return q(() => z4(a, o, i));
case "logical":
return q(() => V4(a, o, i));
case "matrices":
return q(() => W4(a, o, i));
case "normalization":
return q(() => U4(a, o, i));
case "reduction":
return q(() => G4(a, o, i));
case "slice_join":
return q(() => H4(a, o, i));
case "sparse":
return q(() => q4(a, o, i));
case "spectral":
return q(() => j4(a, o, i));
case "string":
return q(() => K4(a, o, i));
case "transformation":
return q(() => X4(a, o, i));
case "hash_table":
return M4(a, o, i, s);
case "custom":
let u = h0(a.op);
if (u && u.customExecutor)
return u.customExecutor(new I4(a, o, i));
throw TypeError(`Custom op ${a.op} is not registered.`);
default:
throw TypeError(`Unknown op '${a.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`);
}
})(e, t, n);
return w.isPromise(r) ? r.then((a) => [].concat(a)) : [].concat(r);
}
var iw = class {
constructor(e = {}, t = {}, n = {}, s = {}) {
this.weightMap = e, this.tensorArrayMap = t, this.tensorListMap = n, this.functionMap = s, this.rootContext = { id: 0, frameName: "", iterationId: 0 }, this.contexts = [this.rootContext], this.lastId = 0, this.generateCurrentContextIds();
}
newFrame(e, t) {
return { id: e, frameName: t, iterationId: 0 };
}
set currentContext(e) {
this.contexts !== e && (this.contexts = e, this.generateCurrentContextIds());
}
get currentContext() {
return this.contexts;
}
get currentContextId() {
return this._currentContextIds[0];
}
get currentContextIds() {
return this._currentContextIds;
}
generateCurrentContextIds() {
let e = [];
for (let t = 0; t < this.contexts.length - 1; t++) {
let n = this.contexts.slice(0, this.contexts.length - t);
e.push(this.contextIdforContexts(n));
}
e.push(""), this._currentContextIds = e;
}
contextIdforContexts(e) {
return e ? e.map((t) => t.id === 0 && t.iterationId === 0 ? "" : `${t.frameName}-${t.iterationId}`).join("/") : "";
}
enterFrame(e) {
this.contexts && (this.lastId++, this.contexts = this.contexts.slice(), this.contexts.push(this.newFrame(this.lastId, e)), this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)));
}
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");
}
nextIteration() {
if (this.contexts && this.contexts.length > 0) {
this.contexts = this.contexts.slice(), this.lastId++;
let e = Object.assign({}, this.contexts[this.contexts.length - 1]);
e.iterationId += 1, e.id = this.lastId, this.contexts.splice(-1, 1, e), this._currentContextIds.splice(0, 1, this.contextIdforContexts(this.contexts));
} else
throw new Error("Cannot increase frame iteration, the context is empty");
}
getWeight(e) {
return this.weightMap[e];
}
addTensorArray(e) {
this.tensorArrayMap[e.id] = e;
}
getTensorArray(e) {
return this.tensorArrayMap[e];
}
addTensorList(e) {
this.tensorListMap[e.id] = e;
}
getTensorList(e) {
return this.tensorListMap[e];
}
dispose(e) {
for (let t in this.tensorArrayMap)
this.tensorArrayMap[t].clearAndClose(e);
for (let t in this.tensorListMap)
this.tensorListMap[t].clearAndClose(e);
}
};
function uw(e, t, n, s) {
let r = /* @__PURE__ */ new Set(), a = [], o = null, i = null, u = /* @__PURE__ */ new Set(), l = Object.keys(e).map((d) => _n(d)[0]), c = [];
s != null && (c = s.map((d) => _n(d.name)[0]));
let p = [...t];
for (; p.length > 0; ) {
let d = p.pop();
if ((O0(d) || eU(d) || tU(d)) && o == null && (o = d, i = o.children.map((h) => h.name).filter((h) => r.has(h))), r.add(d.name), n[d.name] == null && l.indexOf(d.name) === -1 && c.indexOf(d.name) === -1) {
if (d.inputs.length === 0) {
a.push(d.name);
continue;
}
d.inputs.forEach((h) => {
u.has(h.name) || (u.add(h.name), p.push(h));
});
}
}
return { inputs: e, outputs: t, usedNodes: r, missingInputs: a, dynamicNode: o, syncInputs: i };
}
function Y4(e, t, n) {
let { usedNodes: s, inputs: r } = n, a = [], o = Object.keys(r).map((c) => _n(c)[0]).map((c) => e.nodes[c]), i = e.initNodes;
o.forEach((c) => {
s.has(c.name) && a.push(c);
}), e.weights.forEach((c) => {
s.has(c.name) && a.push(c);
}), i != null && i.forEach((c) => {
s.has(c.name) && a.push(c);
});
let u = /* @__PURE__ */ new Set(), l = [];
for (; a.length > 0; ) {
let c = a.pop();
u.add(c.name), t[c.name] || l.push(c), c.children.forEach((p) => {
!u.has(p.name) && s.has(p.name) && p.inputs.every((d) => u.has(d.name)) && a.push(p);
});
}
return l;
}
var Q4 = ["Switch", "Merge", "Enter", "Exit", "NextIteration", "StatelessIf", "StatelessWhile", "if", "While"];
var Z4 = ["NonMaxSuppressionV2", "NonMaxSuppressionV3", "NonMaxSuppressionV5", "Where"];
var J4 = ["HashTable", "HashTableV2", "LookupTableImport", "LookupTableImportV2", "LookupTableFind", "LookupTableFindV2", "LookupTableSize", "LookupTableSizeV2"];
function O0(e) {
return Q4.indexOf(e.op) >= 0;
}
function eU(e) {
return Z4.indexOf(e.op) >= 0;
}
function tU(e) {
return J4.indexOf(e.op) >= 0;
}
var Xm = class {
constructor(e, t) {
this.graph = e, this.parent = t, this.compiledMap = /* @__PURE__ */ new Map(), this._weightMap = {}, this.SEPERATOR = ",", this._functions = {}, this._functionExecutorMap = {}, this.intermediateTensors = {}, this.keepTensorForDebug = false, this._outputs = e.outputs, this._inputs = e.inputs, this._initNodes = e.initNodes, this._signature = e.signature, this._functions = e.functions, e.functions != null && Object.keys(e.functions).forEach((n) => {
this._functionExecutorMap[n] = new Xm(e.functions[n], 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(e) {
let t = Object.keys(e).map((n) => e[n].map((s) => s.id));
this._weightIds = [].concat(...t), this._weightMap = e;
}
set resourceManager(e) {
this._resourceManager = e;
}
get inputs() {
return this._inputs.map((e) => ({ name: e.name, shape: e.attrParams.shape ? e.attrParams.shape.value : void 0, dtype: e.attrParams.dtype ? e.attrParams.dtype.value : void 0 }));
}
get outputs() {
return this._outputs.map((e) => ({ name: e.name, shape: e.attrParams.shape ? e.attrParams.shape.value : void 0, dtype: e.attrParams.dtype ? e.attrParams.dtype.value : void 0 }));
}
get inputNodes() {
return this._inputs.map((e) => e.signatureKey || e.name);
}
get outputNodes() {
return this._outputs.map((e) => {
let t = e.signatureKey || e.name;
return e.defaultOutput ? `${t}:${e.defaultOutput}` : t;
});
}
get functions() {
return Object.keys(this._functions).reduce((e, t) => (e[t] = this._functions[t].signature, e), {});
}
getCompilationKey(e, t) {
let n = e.map((r) => r.name).sort(), s = t.map((r) => r.name).sort();
return n.join(this.SEPERATOR) + "--" + s.join(this.SEPERATOR);
}
compile(e, t) {
let n = uw(e, t, this.weightMap, this._initNodes), { missingInputs: s, dynamicNode: r, syncInputs: a } = n;
if (r != null)
throw new Error(`This execution contains the node '${r.name}', which has the dynamic op '${r.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${a}]`);
if (s.length > 0) {
let o = t.map((u) => u.name), i = Object.keys(e);
throw new Error(`Cannot compute the outputs [${o}] from the provided inputs [${i}]. Missing the following inputs: [${s}]`);
}
return Y4(this.graph, this.weightMap, n);
}
execute(e, t) {
e = this.mapInputs(e);
let n = Object.keys(e).sort();
this.checkInputs(e), this.checkInputShapeAndType(e), t = this.mapOutputs(t), this.checkOutputs(t);
let s = n.map((c) => this.graph.nodes[_n(c)[0]]), r = t.map((c) => _n(c)[0]), a = r.map((c) => this.graph.nodes[c]);
this.resetIntermediateTensors(), a.length === 0 && (a = this._outputs);
let o = this.getCompilationKey(s, a), i = this.compiledMap.get(o);
i == null && (i = this.compile(e, a), this.compiledMap.set(o, i));
let u = {}, l = {};
return q(() => {
let c = new iw(this.weightMap, u, l, this.functionExecutorMap), p = { ...this.weightMap };
Object.keys(e).forEach((f) => {
let [m, g] = _n(f), b = [];
b[g] = e[f], p[m] = b;
});
let d = this.getFrozenTensorIds(p), h = {};
for (let f = 0; f < i.length; f++) {
let m = i[f];
if (!p[m.name]) {
let g = ow(m, p, c, this._resourceManager);
if (w.isPromise(g))
throw new Error(`The execution of the op '${m.op}' returned a promise. Please use model.executeAsync() instead.`);
p[m.name] = g, this.checkTensorForDisposal(m.name, m, p, c, d, r, h);
}
}
return this.parent == null && c.dispose(d), t.map((f) => un(f, p, c));
});
}
getFrozenTensorIds(e) {
let t = [].concat.apply([], Object.keys(e).map((n) => e[n]).map((n) => n.map((s) => s.id)));
return new Set(t);
}
checkTensorForDisposal(e, t, n, s, r, a, o) {
t.category === "control" || a.indexOf(e) !== -1 || (n[e].forEach((i) => {
i != null && (o[i.id] = (o[i.id] || 0) + t.children.length);
}), t.inputs.forEach((i) => {
if (i.category !== "control") {
let u = s4(i.name, n, s);
u != null && u.forEach((l) => {
if (l && !l.kept && !r.has(l.id)) {
let c = o[l.id];
if (c === 1) {
if (!this.keepTensorForDebug)
l.dispose();
else {
let [p, d] = Ts(t.name, s);
this.intermediateTensors[p] ? this.intermediateTensors[p][d] = l : (this.intermediateTensors[p] = [], this.intermediateTensors[p][d] = l);
}
delete o[l.id];
} else
c != null && o[l.id]--;
}
});
}
}));
}
async executeAsync(e, t) {
return this._executeAsync(e, t);
}
disposeIntermediateTensors() {
!this.intermediateTensors || (Object.keys(this.intermediateTensors).forEach((e) => this.intermediateTensors[e].forEach((t) => t.dispose())), this.disposeTensorsMap());
}
disposeTensorsMap() {
!this.tensorsMap || Object.keys(this.tensorsMap).forEach((e) => {
this.tensorsMap[e].forEach((n) => {
n && !n.kept && !n.isDisposed && !this.keepIds.has(n.id) && n.dispose();
});
});
}
getIntermediateTensors() {
return this.tensorsMap;
}
resetIntermediateTensors() {
for (let e in this.intermediateTensors)
this.intermediateTensors[e].forEach((t) => t.dispose()), delete this.intermediateTensors[e];
}
async _executeAsync(e, t, n = false, s = {}, r = {}) {
n || (e = this.mapInputs(e), this.checkInputs(e), this.checkInputShapeAndType(e), t = this.mapOutputs(t), this.checkOutputs(t));
try {
this.keepTensorForDebug = K().getBool("KEEP_INTERMEDIATE_TENSORS");
} catch (l) {
console.warn(l.message);
}
this.resetIntermediateTensors();
let a = new iw(this.weightMap, s, r, this.functionExecutorMap);
this.tensorsMap = await this.executeWithControlFlow(e, a, t, n);
let o = t.map((l) => un(l, this.tensorsMap, a)), i = o.map((l) => l.id), u = Object.keys(e).map((l) => e[l].id);
return this.keepIds = /* @__PURE__ */ new Set([...i, ...u, ...this.weightIds]), this.keepTensorForDebug || this.disposeTensorsMap(), this.parent == null && a.dispose(this.keepIds), o;
}
async executeFunctionAsync(e, t, n) {
let s = e.reduce((r, a, o) => (r[this.inputs[o].name] = a, r), {});
return this._executeAsync(s, this.outputNodes, true, t, n);
}
async executeWithControlFlow(e, t, n, s) {
let r = Object.keys(e), a = r.map((y) => this.graph.nodes[_n(y)[0]]), o = n.map((y) => _n(y)[0]), i = o.map((y) => this.graph.nodes[y]);
i.length === 0 && (i = this._outputs);
let { usedNodes: u, missingInputs: l, dynamicNode: c, syncInputs: p } = uw(e, i, this.weightMap, this._initNodes), d = [...a, ...this.graph.weights, ...this._initNodes || []].map((y) => ({ node: y, contexts: t.currentContext })), h = { ...this.weightMap };
Object.keys(e).forEach((y) => {
let [v, x] = _n(y), k = [];
k[x] = e[y], h[v] = k;
});
let f = {}, m = this.getFrozenTensorIds(h), g = {};
for (; d.length > 0; ) {
let y = this.processStack(a, d, t, h, g, m, o, f, u);
await Promise.all(y);
}
c == null && !s && console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");
let b = i.filter((y) => !O0(y) && !un(y.name, h, t)).map((y) => y.name);
if (b.length > 0) {
let y = "";
throw c != null && (y = `Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${p}]`), new Error(`Cannot compute the outputs [${b}] from the provided inputs [${r}]. Consider providing the following inputs: [${l}]. ${y}`);
}
return h;
}
processStack(e, t, n, s, r, a, o, i, u) {
let l = [];
for (; t.length > 0; ) {
let c = t.pop();
n.currentContext = c.contexts;
let p = "";
if (c.node.op === "Enter" && S("isConstant", c.node, s, n) && ([p] = Ts(c.node.name, n)), s[c.node.name] == null) {
let d = ow(c.node, s, n, this._resourceManager);
p || ([p] = Ts(c.node.name, n));
let h = n.currentContext;
w.isPromise(d) ? l.push(d.then((f) => (s[p] = f, n.currentContext = h, this.checkTensorForDisposal(p, c.node, s, n, a, o, i), this.processChildNodes(c.node, t, n, s, r, u), f))) : (s[p] = d, this.checkTensorForDisposal(p, c.node, s, n, a, o, i), this.processChildNodes(c.node, t, n, s, r, u));
} else
this.processChildNodes(c.node, t, n, s, r, u);
}
return l;
}
processChildNodes(e, t, n, s, r, a) {
e.children.forEach((o) => {
let [i] = Ts(o.name, n);
r[i] || !a.has(o.name) || (o.op === "Merge" ? o.inputNames.some((u) => !!un(u, s, n)) && (r[i] = true, t.push({ contexts: n.currentContext, node: o })) : o.inputNames.every((u) => !!un(u, s, n)) && (r[i] = true, t.push({ contexts: n.currentContext, node: o })));
});
}
dispose() {
Object.keys(this.weightMap).forEach((e) => this.weightMap[e].forEach((t) => t.dispose()));
}
checkInputShapeAndType(e) {
Object.keys(e).forEach((t) => {
let n = e[t], [s] = _n(t), r = this.graph.nodes[s];
if (r.attrParams.shape && r.attrParams.shape.value) {
let a = r.attrParams.shape.value, o = a.length === n.shape.length && n.shape.every((i, u) => a[u] === -1 || a[u] === i);
w.assert(o, () => `The shape of dict['${r.name}'] provided in model.execute(dict) must be [${a}], but was [${n.shape}]`);
}
r.attrParams.dtype && r.attrParams.dtype.value && w.assert(n.dtype === r.attrParams.dtype.value, () => `The dtype of dict['${r.name}'] provided in model.execute(dict) must be ${r.attrParams.dtype.value}, but was ${n.dtype}`);
});
}
mapInputs(e) {
let t = {};
for (let n in e)
if (this._signature != null && this._signature.inputs != null && this._signature.inputs[n] != null) {
let s = this._signature.inputs[n];
t[s.name] = e[n];
} else
t[n] = e[n];
return t;
}
checkInputs(e) {
let t = Object.keys(e).filter((n) => {
let [s] = _n(n);
return this.graph.nodes[s] == null;
});
if (t.length > 0)
throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`);
}
mapOutputs(e) {
return e.map((t) => this._signature != null && this._signature.outputs != null && this._signature.outputs[t] != null ? this._signature.outputs[t].name : t, {});
}
checkOutputs(e) {
e.forEach((t) => {
let [n] = _n(t);
if (!this.graph.nodes[n])
throw new Error(`The output '${t}' is not found in the graph`);
});
}
};
var nU = class {
constructor(e = {}, t = {}) {
this.hashTableNameToHandle = e, this.hashTableMap = t;
}
addHashTable(e, t) {
this.hashTableNameToHandle[e] = t.handle, this.hashTableMap[t.id] = t;
}
getHashTableHandleByName(e) {
return this.hashTableNameToHandle[e];
}
getHashTableById(e) {
return this.hashTableMap[e];
}
dispose() {
for (let e in this.hashTableMap)
this.hashTableMap[e].clearAndClose(), delete this.hashTableMap[e];
for (let e in this.hashTableNameToHandle)
this.hashTableNameToHandle[e].dispose(), delete this.hashTableNameToHandle[e];
}
};
var sU = "?tfjs-format=file";
var rU = "model.json";
var P0 = class {
constructor(e, t = {}) {
this.modelUrl = e, this.loadOptions = t, this.version = "n/a", t == null && (this.loadOptions = {}), this.resourceManager = new nU();
}
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() {
let e = this.modelUrl;
if (e.load != null)
this.handler = e;
else if (this.loadOptions.requestInit != null)
this.handler = An.browserHTTPRequest(e, this.loadOptions);
else {
let t = An.getLoadHandlers(e, this.loadOptions);
if (t.length === 0)
t.push(An.browserHTTPRequest(e, this.loadOptions));
else if (t.length > 1)
throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);
this.handler = t[0];
}
}
load() {
if (this.findIOHandler(), this.handler.load == null)
throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");
let e = this.handler.load();
return w.isPromise(e) ? e.then((t) => this.loadSync(t)) : this.loadSync(e);
}
loadSync(e) {
this.artifacts = e;
let t = this.artifacts.modelTopology, n;
this.artifacts.userDefinedMetadata != null && this.artifacts.userDefinedMetadata.signature != null ? n = this.artifacts.userDefinedMetadata.signature : n = this.artifacts.signature, this.signature = n, this.version = `${t.versions.producer}.${t.versions.minConsumer}`;
let s = An.decodeWeights(this.artifacts.weightData, this.artifacts.weightSpecs);
if (this.executor = new Xm(nw.Instance.transformGraph(t, this.signature)), this.executor.weightMap = this.convertTensorMapToTensorsMap(s), this.executor.resourceManager = this.resourceManager, e.modelInitializer != null && e.modelInitializer.node != null) {
let r = nw.Instance.transformGraph(e.modelInitializer);
this.initializer = new Xm(r), this.initializer.weightMap = this.executor.weightMap, this.initializer.resourceManager = this.resourceManager, this.initializer.executeAsync({}, []);
}
return true;
}
async save(e, t) {
if (typeof e == "string") {
let n = An.getSaveHandlers(e);
if (n.length === 0)
throw new Error(`Cannot find any save handlers for URL '${e}'`);
if (n.length > 1)
throw new Error(`Found more than one (${n.length}) save handlers for URL '${e}'`);
e = n[0];
}
if (e.save == null)
throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");
return e.save(this.artifacts);
}
predict(e, t) {
return this.execute(e, this.outputNodes);
}
normalizeInputs(e) {
if (!(e instanceof et) && !Array.isArray(e))
return e;
if (e = Array.isArray(e) ? e : [e], e.length !== this.inputNodes.length)
throw new Error(`Input tensor count mismatch,the graph model has ${this.inputNodes.length} placeholders, while there are ${e.length} input tensors.`);
return this.inputNodes.reduce((t, n, s) => (t[n] = e[s], t), {});
}
normalizeOutputs(e) {
return e = e || this.outputNodes, Array.isArray(e) ? e : [e];
}
execute(e, t) {
e = this.normalizeInputs(e), t = this.normalizeOutputs(t);
let n = this.executor.execute(e, t);
return n.length > 1 ? n : n[0];
}
async executeAsync(e, t) {
e = this.normalizeInputs(e), t = this.normalizeOutputs(t);
let n = await this.executor.executeAsync(e, t);
return n.length > 1 ? n : n[0];
}
getIntermediateTensors() {
return this.executor.getIntermediateTensors();
}
disposeIntermediateTensors() {
this.executor.disposeIntermediateTensors();
}
convertTensorMapToTensorsMap(e) {
return Object.keys(e).reduce((t, n) => (t[n] = [e[n]], t), {});
}
dispose() {
this.executor.dispose(), this.initializer && this.initializer.dispose(), this.resourceManager.dispose();
}
};
async function Rhe(e, t = {}) {
if (e == null)
throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");
t == null && (t = {}), t.fromTFHub && typeof e == "string" && (e = aU(e));
let n = new P0(e, t);
return await n.load(), n;
}
function Dhe(e) {
if (e == null)
throw new Error("modelUrl in loadGraphModelSync() cannot be null. Please provide a url or an IOHandler that loads the model");
if (!e.load)
throw new Error(`modelUrl IO Handler ${e} has no load function`);
let t = new P0(e);
return t.load(), t;
}
function aU(e) {
return e.endsWith("/") || (e = e + "/"), `${e}${rU}${sU}`;
}
var Fhe = "0.0.0";
var oU = {};
Ee(oU, { CSVDataset: () => K0, Dataset: () => su, FileDataSource: () => tC, TextLineDataset: () => j0, URLDataSource: () => nC, array: () => _U, csv: () => BU, func: () => VU, generator: () => WU, microphone: () => GU, version_data: () => HU, webcam: () => UU, zip: () => AU });
var iU = wa(Qd());
var uU = wa(Qd());
function lU(e, t) {
return Md(e, t);
}
function Md(e, t, n = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Set()) {
if (e == null)
return null;
if (typeof Blob == "function" && e instanceof Blob)
return e.slice();
if (s.has(e))
throw new Error("Circular references are not supported.");
if (n.has(e))
return n.get(e);
let r = t(e);
if (r.recurse && r.value !== null)
throw new Error("A deep map function may not return both a value and recurse=true.");
if (r.recurse)
if (ai(e)) {
let a = Array.isArray(e) ? [] : {};
s.add(e);
for (let o in e) {
let i = e[o], u = Md(i, t, n, s);
a[o] = u;
}
return s.delete(e), e.__proto__ && (a.__proto__ = e.__proto__), a;
} else
throw new Error(`Can't recurse into non-iterable type: ${e}`);
else
return n.set(e, r.value), r.value;
}
function cU(e, t = L0) {
return z0(e, t);
}
function z0(e, t, n = /* @__PURE__ */ new Set()) {
let s = e[0];
if (n.has(s))
throw new Error("Circular references are not supported.");
let r = t(e);
if (r.recurse && r.value !== null)
throw new Error("A deep zip function may not return both a value and recurse=true.");
if (r.recurse)
if (ai(s)) {
let a = Array.isArray(s) ? [] : {};
n.add(s);
for (let o in s) {
let i = e.map((l) => l[o]), u = z0(i, t, n);
a[o] = u;
}
return n.delete(s), a;
} else
throw new Error(`Can't recurse into non-iterable type: ${s}`);
else
return r.value;
}
function L0(e) {
return e === null ? null : ai(e[0]) ? { value: null, recurse: true } : { value: e, recurse: false };
}
async function M0(e, t) {
let n = /* @__PURE__ */ new Map();
Md(e, t, n);
for (let r of Array.from(n.keys())) {
let a = n.get(r);
if (w.isPromise(a)) {
let o = await a;
n.set(r, o);
}
}
return Md(e, t, n);
}
function ai(e) {
let t = false;
if (K().get("IS_BROWSER"))
t = e instanceof TextDecoder;
else {
let { StringDecoder: n } = sk();
t = e instanceof n;
}
return e != null && !ArrayBuffer.isView(e) && (Array.isArray(e) || typeof e == "object" && !(e instanceof et) && !(e instanceof Promise) && !t);
}
function dU(e) {
return e == null || pU(e) || Array.isArray(e) || typeof e == "object" && e instanceof et || w.isTypedArray(e);
}
function pU(e) {
return e === null || typeof e != "object" && typeof e != "function";
}
function hU(e) {
return lU(e, fU);
}
function fU(e) {
return e instanceof et ? { value: e.clone(), recurse: false } : ai(e) ? { value: null, recurse: true } : { value: e, recurse: false };
}
var B0 = class {
constructor(e) {
if (this.capacity = e, this.begin = 0, this.end = 0, e == null)
throw new RangeError("Can't create a ring buffer of unknown capacity.");
if (e < 1)
throw new RangeError("Can't create ring buffer of capacity < 1.");
this.data = new Array(e), this.doubledCapacity = 2 * e;
}
wrap(e) {
for (; e < 0; )
e += this.doubledCapacity;
return e % this.doubledCapacity;
}
get(e) {
if (e < 0)
throw new RangeError("Can't get item at a negative index.");
return this.data[e % this.capacity];
}
set(e, t) {
if (e < 0)
throw new RangeError("Can't set item at a negative index.");
this.data[e % this.capacity] = t;
}
length() {
let e = this.end - this.begin;
return e < 0 && (e = this.doubledCapacity + e), e;
}
isFull() {
return this.length() === this.capacity;
}
isEmpty() {
return this.length() === 0;
}
push(e) {
if (this.isFull())
throw new RangeError("Ring buffer is full.");
this.set(this.end, e), this.end = this.wrap(this.end + 1);
}
pushAll(e) {
for (let t of e)
this.push(t);
}
pop() {
if (this.isEmpty())
throw new RangeError("Ring buffer is empty.");
this.end = this.wrap(this.end - 1);
let e = this.get(this.end);
return this.set(this.end, void 0), e;
}
unshift(e) {
if (this.isFull())
throw new RangeError("Ring buffer is full.");
this.begin = this.wrap(this.begin - 1), this.set(this.begin, e);
}
shift() {
if (this.isEmpty())
throw new RangeError("Ring buffer is empty.");
let e = this.get(this.begin);
return this.set(this.begin, void 0), this.begin = this.wrap(this.begin + 1), e;
}
shuffleExcise(e) {
if (this.isEmpty())
throw new RangeError("Ring buffer is empty.");
let t = this.wrap(this.begin + e), n = this.get(t);
return this.set(t, this.pop()), n;
}
};
var V0 = class extends B0 {
constructor() {
super(V0.INITIAL_CAPACITY);
}
isFull() {
return false;
}
push(e) {
super.isFull() && this.expand(), super.push(e);
}
unshift(e) {
super.isFull() && this.expand(), super.unshift(e);
}
expand() {
let e = this.capacity * 2, t = new Array(e), n = this.length();
for (let s = 0; s < n; s++)
t[s] = this.get(this.wrap(this.begin + s));
this.data = t, this.capacity = e, this.doubledCapacity = 2 * this.capacity, this.begin = 0, this.end = n;
}
};
var W0 = V0;
W0.INITIAL_CAPACITY = 32;
function U0(e) {
return new bU(e);
}
function uv(e) {
return new yU(e);
}
function mU(e, t) {
return new G0(e, t);
}
function gU(e, t = H0.FAIL) {
return new TU(e, t);
}
var Ut = class {
async toArray() {
let e = [], t = await this.next();
for (; !t.done; )
e.push(t.value), t = await this.next();
return e;
}
async toArrayForTest() {
let e = this.prefetch(100), t = [], n = await e.next();
for (; !n.done; )
t.push(n.value), n = await e.next();
return t;
}
async resolveFully() {
let e = await this.next();
for (; !e.done; )
e = await this.next();
}
async resolveWhile(e) {
let t = await this.next(), n = e(t.value);
for (; !t.done && n; )
t = await this.next(), n = e(t.value);
}
handleErrors(e) {
return new CU(this, e);
}
filter(e) {
return new SU(this, e);
}
map(e) {
return new IU(this, e);
}
mapAsync(e) {
return new lw(this, e);
}
serialMapAsync(e) {
return new lw(this, e).serial();
}
flatmap(e) {
return new NU(this, e);
}
async forEachAsync(e) {
return this.map(e).resolveFully();
}
async serialForEach(e) {
return this.serialMapAsync(e).resolveWhile((t) => t === true);
}
rowMajorBatch(e, t = true) {
return new kU(this, e, t);
}
columnMajorBatch(e, t = true, n = L0) {
return this.rowMajorBatch(e, t).map((r) => cU(r, n));
}
concatenate(e, t) {
return new G0(U0([this, e]), t);
}
take(e) {
return e < 0 || e == null ? this : new wU(this, e);
}
skip(e) {
return e < 0 || e == null ? this : new xU(this, e);
}
prefetch(e) {
return new q0(this, e);
}
shuffle(e, t) {
return new $U(this, e, t);
}
serial() {
return new vU(this);
}
};
var bU = class extends Ut {
constructor(e) {
super(), this.items = e, this.trav = 0;
}
summary() {
return `Array of ${this.items.length} items`;
}
async next() {
if (this.trav >= this.items.length)
return { value: null, done: true };
let e = this.items[this.trav];
return this.trav++, { value: hU(e), done: false };
}
};
var yU = class extends Ut {
constructor(e) {
super(), this.nextFn = e;
}
summary() {
return "Function call";
}
async next() {
try {
return this.nextFn();
} catch (e) {
throw e.message = `Error thrown while iterating through a dataset: ${e.message}`, e;
}
}
};
var vU = class extends Ut {
constructor(e) {
super(), this.upstream = e, this.lastRead = Promise.resolve({ value: null, done: false });
}
summary() {
return `${this.upstream.summary()} -> Serial`;
}
async next() {
return this.lastRead = this.lastRead.then(() => this.serialNext()), this.lastRead;
}
async serialNext() {
return this.upstream.next();
}
};
var xU = class extends Ut {
constructor(e, t) {
super(), this.upstream = e, this.maxCount = t, this.count = 0, this.lastRead = Promise.resolve({ value: null, done: false });
}
summary() {
return `${this.upstream.summary()} -> Skip`;
}
async next() {
return this.lastRead = this.lastRead.then(() => this.serialNext()), this.lastRead;
}
async serialNext() {
for (; this.count++ < this.maxCount; ) {
let e = await this.upstream.next();
if (e.done)
return e;
De(e.value);
}
return this.upstream.next();
}
};
var wU = class extends Ut {
constructor(e, t) {
super(), this.upstream = e, this.maxCount = t, this.count = 0;
}
summary() {
return `${this.upstream.summary()} -> Take`;
}
async next() {
return this.count++ >= this.maxCount ? { value: null, done: true } : this.upstream.next();
}
};
var kU = class extends Ut {
constructor(e, t, n = true) {
super(), this.upstream = e, this.batchSize = t, this.enableSmallLastBatch = n, this.lastRead = Promise.resolve({ value: null, done: false });
}
summary() {
return `${this.upstream.summary()} -> RowMajorBatch`;
}
async next() {
return this.lastRead = this.lastRead.then(() => this.serialNext()), this.lastRead;
}
async serialNext() {
let e = [];
for (; e.length < this.batchSize; ) {
let t = await this.upstream.next();
if (t.done)
return this.enableSmallLastBatch && e.length > 0 ? { value: e, done: false } : { value: null, done: true };
e.push(t.value);
}
return { value: e, done: false };
}
};
var SU = class extends Ut {
constructor(e, t) {
super(), this.upstream = e, this.predicate = t, this.lastRead = Promise.resolve({ value: null, done: false });
}
summary() {
return `${this.upstream.summary()} -> Filter`;
}
async next() {
return this.lastRead = this.lastRead.then(() => this.serialNext()), this.lastRead;
}
async serialNext() {
for (; ; ) {
let e = await this.upstream.next();
if (e.done || this.predicate(e.value))
return e;
De(e.value);
}
}
};
var IU = class extends Ut {
constructor(e, t) {
super(), this.upstream = e, this.transform = t;
}
summary() {
return `${this.upstream.summary()} -> Map`;
}
async next() {
let e = await this.upstream.next();
if (e.done)
return { value: null, done: true };
let t = _s.getTensorsInContainer(e.value), n = this.transform(e.value), s = _s.getTensorsInContainer(n);
for (let r of t)
_s.isTensorInList(r, s) || r.dispose();
return { value: n, done: false };
}
};
var CU = class extends Ut {
constructor(e, t) {
super(), this.upstream = e, this.handler = t, this.count = 0, this.lastRead = Promise.resolve({ value: null, done: false });
}
summary() {
return `${this.upstream.summary()} -> handleErrors`;
}
async next() {
return this.lastRead = this.lastRead.then(() => this.serialNext()), this.lastRead;
}
async serialNext() {
for (; ; )
try {
return await this.upstream.next();
} catch (e) {
if (!this.handler(e))
return { value: null, done: true };
}
}
};
var lw = class extends Ut {
constructor(e, t) {
super(), this.upstream = e, this.transform = t;
}
summary() {
return `${this.upstream.summary()} -> AsyncMap`;
}
async next() {
let e = await this.upstream.next();
if (e.done)
return { value: null, done: true };
let t = _s.getTensorsInContainer(e.value), n = await this.transform(e.value), s = _s.getTensorsInContainer(n);
for (let r of t)
_s.isTensorInList(r, s) || r.dispose();
return { value: n, done: false };
}
};
var lv = class extends Ut {
constructor() {
super(), this.outputQueue = new W0(), this.lastRead = Promise.resolve({ value: null, done: false });
}
async next() {
return this.lastRead = this.lastRead.then(() => this.serialNext()), this.lastRead;
}
async serialNext() {
for (; this.outputQueue.length() === 0; )
if (!await this.pump())
return { value: null, done: true };
return { value: this.outputQueue.shift(), done: false };
}
};
var NU = class extends lv {
constructor(e, t) {
super(), this.upstream = e, this.transform = t;
}
summary() {
return `${this.upstream.summary()} -> Flatmap`;
}
async pump() {
let e = await this.upstream.next();
if (e.done)
return false;
let t = _s.getTensorsInContainer(e.value), n = this.transform(e.value), s = _s.getTensorsInContainer(n);
this.outputQueue.pushAll(n);
for (let r of t)
_s.isTensorInList(r, s) || r.dispose();
return true;
}
};
var G0 = class extends Ut {
constructor(e, t) {
super(), this.baseErrorHandler = t, this.lastRead = null, this.iterator = null, this.moreIterators = e;
}
summary() {
return "TODO: fill in upstream of chained summaries -> Chained";
}
async next() {
return this.lastRead = this.readFromChain(this.lastRead), this.lastRead;
}
async readFromChain(e) {
if (await e, this.iterator == null) {
let n = await this.moreIterators.next();
if (n.done)
return { value: null, done: true };
this.iterator = n.value, this.baseErrorHandler != null && (this.iterator = this.iterator.handleErrors(this.baseErrorHandler));
}
let t = await this.iterator.next();
return t.done ? (this.iterator = null, this.readFromChain(e)) : t;
}
};
var H0 = ((e) => (e[e.FAIL = 0] = "FAIL", e[e.SHORTEST = 1] = "SHORTEST", e[e.LONGEST = 2] = "LONGEST", e))(H0 || {});
var TU = class extends Ut {
constructor(e, t = 0) {
super(), this.iterators = e, this.mismatchMode = t, this.count = 0, this.currentPromise = null;
}
summary() {
return "{TODO: fill in upstream of zip summaries} -> Zip";
}
async nextState(e) {
await e;
let t = 0, n = 0;
function s(a) {
return a instanceof Ut ? { value: a.next().then((i) => (t++, i.done && n++, i.value)), recurse: false } : { value: null, recurse: true };
}
let r = await M0(this.iterators, s);
if (t === n)
return { value: null, done: true };
if (n > 0)
switch (this.mismatchMode) {
case 0:
throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);
case 1:
return { value: null, done: true };
case 2:
default:
}
return this.count++, { value: r, done: false };
}
async next() {
return this.currentPromise = this.nextState(this.currentPromise), this.currentPromise;
}
};
var q0 = class extends Ut {
constructor(e, t) {
super(), this.upstream = e, this.bufferSize = t, this.buffer = new B0(t);
}
summary() {
return `${this.upstream.summary()} -> Prefetch`;
}
refill() {
for (; !this.buffer.isFull(); ) {
let e = this.upstream.next();
this.buffer.push(e);
}
}
next() {
return this.refill(), this.buffer.shift();
}
};
var $U = class extends q0 {
constructor(e, t, n) {
super(e, t), this.upstream = e, this.windowSize = t, this.upstreamExhausted = false, this.random = uU.alea(n || w.now().toString()), this.lastRead = Promise.resolve({ value: null, done: false });
}
async next() {
return this.lastRead = this.lastRead.then(() => this.serialNext()), this.lastRead;
}
randomInt(e) {
return Math.floor(this.random() * e);
}
chooseIndex() {
return this.randomInt(this.buffer.length());
}
async serialNext() {
for (this.upstreamExhausted || this.refill(); !this.buffer.isEmpty(); ) {
let e = this.chooseIndex(), t = await this.buffer.shuffleExcise(e);
if (t.done)
this.upstreamExhausted = true;
else
return this.refill(), t;
}
return { value: null, done: true };
}
};
var su = class {
constructor() {
this.size = null;
}
batch(e, t = true) {
let n = this;
w.assert(e > 0, () => `batchSize needs to be positive, but it is
${e}`);
let s;
return this.size === 1 / 0 || this.size == null ? s = this.size : t ? s = Math.ceil(this.size / e) : s = Math.floor(this.size / e), $n(async () => (await n.iterator()).columnMajorBatch(e, t, EU), s);
}
concatenate(e) {
let t = this, n;
return this.size === 1 / 0 || e.size === 1 / 0 ? n = 1 / 0 : this.size != null && e.size != null ? n = this.size + e.size : n = null, $n(async () => (await t.iterator()).concatenate(await e.iterator()), n);
}
filter(e) {
let t = this, n;
return this.size === 1 / 0 ? n = 1 / 0 : n = null, $n(async () => (await t.iterator()).filter((s) => q(() => e(s))), n);
}
async forEachAsync(e) {
return (await this.iterator()).forEachAsync(e);
}
map(e) {
let t = this;
return $n(async () => (await t.iterator()).map((n) => q(() => e(n))), this.size);
}
mapAsync(e) {
let t = this;
return $n(async () => (await t.iterator()).mapAsync(e), this.size);
}
prefetch(e) {
if (e == null)
throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");
let t = this;
return $n(async () => (await t.iterator()).prefetch(e), this.size);
}
repeat(e) {
let t = this, n;
return this.size != null && e > 0 ? n = this.size * e : e === 0 ? n = 0 : this.size != null && (e === void 0 || e < 0) ? n = 1 / 0 : n = null, $n(async () => {
let s = uv(async () => ({ value: await t.iterator(), done: false }));
return mU(s.take(e));
}, n);
}
skip(e) {
let t = this, n;
return this.size != null && e >= 0 && this.size >= e ? n = this.size - e : this.size != null && (this.size < e || e === void 0 || e < 0) ? n = 0 : n = null, $n(async () => (await t.iterator()).skip(e), n);
}
shuffle(e, t, n = true) {
if (e == null || e < 0)
throw this.size == null ? new RangeError("`Dataset.shuffle()` requires bufferSize to be specified.") : new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);
let s = this, r = iU.alea(t || w.now().toString());
return $n(async () => {
let a = r.int32();
return n && (a += r.int32()), (await s.iterator()).shuffle(e, a.toString());
}, this.size);
}
take(e) {
let t = this, n;
return this.size != null && this.size > e ? n = e : this.size != null && this.size <= e ? n = this.size : n = null, $n(async () => (await t.iterator()).take(e), n);
}
async toArray() {
if (this.size === 1 / 0)
throw new Error("Can not convert infinite data stream to array.");
return (await this.iterator()).toArray();
}
async toArrayForTest() {
if (this.size === 1 / 0)
throw new Error("Can not convert infinite data stream to array.");
return (await this.iterator()).toArrayForTest();
}
};
su.MAX_BUFFER_SIZE = 1e4;
function $n(e, t = null) {
return new class extends su {
constructor() {
super(...arguments), this.size = t;
}
async iterator() {
return e();
}
}();
}
function _U(e) {
return $n(async () => U0(e), e.length);
}
function AU(e) {
if (!ai(e))
throw new Error("The argument to zip() must be an object or array.");
let t;
if (Array.isArray(e))
for (let n = 0; n < e.length; n++)
t = t == null ? e[n].size : Math.min(t, e[n].size);
else if (e instanceof Object)
for (let n in e)
t = t == null ? e[n].size : Math.min(t, e[n].size);
return $n(async () => {
let n = await M0(e, (s) => {
if (s instanceof su)
return { value: s.iterator(), recurse: false };
if (ai(s))
return { value: null, recurse: true };
throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.");
});
return gU(n, 1);
}, t);
}
function EU(e) {
if (e === null)
return null;
let t = e[0];
return dU(t) ? { value: RU(e), recurse: false } : { value: null, recurse: true };
}
function RU(e) {
if (e.length === 0)
throw new Error("Can't make a batch of zero elements.");
return e[0] instanceof et ? es(e) : ms(e);
}
var j0 = class extends su {
constructor(e) {
super(), this.input = e;
}
async iterator() {
return (await this.input.iterator()).decodeUTF8().split(`
`).map((s) => (s.endsWith("\r") && (s = s.slice(0, -1)), s));
}
};
var Jc = '"';
var Eu = Symbol("out");
var cw = Symbol("field");
var ed = Symbol("quote");
var sm = Symbol("quoteafterquote");
var dw = Symbol("quoteinquote");
var K0 = class extends su {
constructor(e, t) {
super(), this.input = e, this.hasHeader = true, this.fullColumnNames = null, this.columnNamesValidated = false, this.columnConfigs = null, this.configuredColumnsOnly = false, this.delimiter = ",", this.delimWhitespace = false, this.base = new j0(e), t || (t = {}), this.hasHeader = t.hasHeader !== false, this.fullColumnNames = t.columnNames, this.columnConfigs = t.columnConfigs, this.configuredColumnsOnly = t.configuredColumnsOnly, t.delimWhitespace ? (w.assert(t.delimiter == null, () => "Delimiter should not be provided when delimWhitespace is true."), this.delimWhitespace = true, this.delimiter = " ") : this.delimiter = t.delimiter ? t.delimiter : ",";
}
async columnNames() {
return this.columnNamesValidated || await this.setColumnNames(), this.configuredColumnsOnly ? Object.keys(this.columnConfigs) : this.fullColumnNames;
}
async setColumnNames() {
let e = await this.maybeReadHeaderLine();
if (!this.fullColumnNames && !e)
throw new Error("Column names must be provided if there is no header line.");
this.fullColumnNames && e && w.assert(e.length === this.fullColumnNames.length, () => "The length of provided columnNames (" + this.fullColumnNames.length.toString() + ") does not match the length of the header line read from file (" + e.length.toString() + ")."), this.fullColumnNames || (this.fullColumnNames = e);
let t = this.fullColumnNames.reduce((s, r) => (s[r] = s[r] + 1 || 1, s), {}), n = Object.keys(t).filter((s) => t[s] > 1);
if (w.assert(n.length === 0, () => "Duplicate column names found: " + n.toString()), this.columnConfigs) {
for (let s of Object.keys(this.columnConfigs))
if (this.fullColumnNames.indexOf(s) === -1)
throw new Error('The key "' + s + '" provided in columnConfigs does not match any of the column names (' + this.fullColumnNames.toString() + ").");
}
this.columnNamesValidated = true;
}
async maybeReadHeaderLine() {
if (this.hasHeader) {
let t = await (await this.base.iterator()).next();
if (t.done)
throw new Error("No data was found for CSV parsing.");
let n = t.value;
return this.parseRow(n, false);
} else
return null;
}
async iterator() {
this.columnNamesValidated || await this.setColumnNames();
let e = await this.base.iterator();
return this.hasHeader && (e = e.skip(1)), e.map((t) => this.makeDataElement(t));
}
makeDataElement(e) {
let t = this.parseRow(e), n = {}, s = {};
for (let r = 0; r < this.fullColumnNames.length; r++) {
let a = this.fullColumnNames[r], o = this.columnConfigs ? this.columnConfigs[a] : null;
if (!(this.configuredColumnsOnly && !o)) {
let i = t[r], u = null;
if (i === "")
if (o && o.default !== void 0)
u = o.default;
else {
if (o && (o.required || o.isLabel))
throw new Error(`Required column ${a} is empty in this line: ${e}`);
u = void 0;
}
else {
let l = Number(i);
if (isNaN(l))
o && o.dtype === "bool" ? u = this.getBoolean(i) : u = i;
else if (!o || !o.dtype)
u = l;
else
switch (o.dtype) {
case "float32":
u = l;
break;
case "int32":
u = Math.floor(l);
break;
case "bool":
u = this.getBoolean(i);
break;
default:
u = l;
}
}
o && o.isLabel ? s[a] = u : n[a] = u;
}
}
return Object.keys(s).length === 0 ? n : { xs: n, ys: s };
}
getBoolean(e) {
return e === "1" || e.toLowerCase() === "true" ? 1 : 0;
}
parseRow(e, t = true) {
let n = [], s = 0, r = e.length, a = Eu;
for (let o = 0; o < r; o++)
switch (a) {
case Eu:
switch (e.charAt(o)) {
case Jc:
s = o + 1, a = ed;
break;
case this.delimiter:
if (s = o + 1, this.delimiter === " " && this.delimWhitespace)
break;
n.push(""), a = Eu;
break;
default:
a = cw, s = o;
break;
}
break;
case cw:
switch (e.charAt(o)) {
case this.delimiter:
n.push(e.substring(s, o)), a = Eu, s = o + 1;
break;
default:
}
break;
case ed:
switch (e.charAt(o)) {
case Jc:
a = sm;
break;
default:
}
break;
case sm:
switch (e.charAt(o)) {
case this.delimiter:
n.push(e.substring(s, o - 1)), a = Eu, s = o + 1;
break;
case Jc:
a = ed;
break;
default:
a = dw;
break;
}
break;
case dw:
switch (e.charAt(o)) {
case Jc:
a = ed;
break;
default:
}
break;
default:
}
if (a === sm ? n.push(e.substring(s, r - 1)) : n.push(e.substring(s)), t && n.length !== this.fullColumnNames.length)
throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);
return n;
}
};
var X0 = class extends Ut {
constructor(e) {
super(), this.microphoneConfig = e, this.isClosed = false, this.fftSize = e.fftSize || 1024;
let t = Math.log2(this.fftSize);
if (this.fftSize < 0 || t < 4 || t > 14 || !Number.isInteger(t))
throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);
if (this.numFrames = e.numFramesPerSpectrogram || 43, this.sampleRateHz = e.sampleRateHz, this.columnTruncateLength = e.columnTruncateLength || this.fftSize, this.audioTrackConstraints = e.audioTrackConstraints, this.smoothingTimeConstant = e.smoothingTimeConstant || 0, this.includeSpectrogram = e.includeSpectrogram !== false, this.includeWaveform = e.includeWaveform === true, !this.includeSpectrogram && !this.includeWaveform)
throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.");
}
summary() {
return "microphone";
}
static async create(e = {}) {
if (!K().get("IS_BROWSER"))
throw new Error("microphone API is only supported in browser environment.");
let t = new X0(e);
return await t.start(), t;
}
async start() {
try {
this.stream = await navigator.mediaDevices.getUserMedia({ audio: this.audioTrackConstraints == null ? true : this.audioTrackConstraints, video: false });
} catch (n) {
throw new Error(`Error thrown while initializing video stream: ${n.message}`);
}
if (!this.stream)
throw new Error("Could not obtain audio from microphone.");
let e = window.AudioContext || window.webkitAudioContext;
if (this.audioContext = new e(), !this.sampleRateHz)
this.sampleRateHz = this.audioContext.sampleRate;
else if (this.audioContext.sampleRate !== this.sampleRateHz)
throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`);
let t = this.audioContext.createMediaStreamSource(this.stream);
this.analyser = this.audioContext.createAnalyser(), this.analyser.fftSize = this.fftSize * 2, this.analyser.smoothingTimeConstant = this.smoothingTimeConstant, t.connect(this.analyser), this.freqData = new Float32Array(this.fftSize), this.timeData = new Float32Array(this.fftSize);
}
async next() {
if (this.isClosed)
return { value: null, done: true };
let e, t, n = await this.getAudioData();
if (this.includeSpectrogram) {
let s = this.flattenQueue(n.freqDataQueue);
e = this.getTensorFromAudioDataArray(s, [this.numFrames, this.columnTruncateLength, 1]);
}
if (this.includeWaveform) {
let s = this.flattenQueue(n.timeDataQueue);
t = this.getTensorFromAudioDataArray(s, [this.numFrames * this.fftSize, 1]);
}
return { value: { spectrogram: e, waveform: t }, done: false };
}
async capture() {
return (await this.next()).value;
}
async getAudioData() {
let e = [], t = [], n = 0;
return new Promise((s) => {
let r = setInterval(() => {
this.includeSpectrogram && (this.analyser.getFloatFrequencyData(this.freqData), this.freqData[0] === -1 / 0 && s({ freqDataQueue: e, timeDataQueue: t }), e.push(this.freqData.slice(0, this.columnTruncateLength))), this.includeWaveform && (this.analyser.getFloatTimeDomainData(this.timeData), t.push(this.timeData.slice())), ++n === this.numFrames && (clearInterval(r), s({ freqDataQueue: e, timeDataQueue: t }));
}, this.fftSize / this.sampleRateHz * 1e3);
});
}
stop() {
this.isClosed || (this.isClosed = true, this.analyser.disconnect(), this.audioContext.close(), this.stream != null && this.stream.getTracks().length > 0 && this.stream.getTracks()[0].stop());
}
toArray() {
throw new Error("Can not convert infinite audio stream to array.");
}
getSampleRate() {
return this.sampleRateHz;
}
flattenQueue(e) {
let t = e[0].length, n = new Float32Array(e.length * t);
return e.forEach((s, r) => n.set(s, r * t)), n;
}
getTensorFromAudioDataArray(e, t) {
let n = new Float32Array(w.sizeFromShape(t));
return n.set(e, n.length - e.length), ms(n, t);
}
};
var Y0 = class extends Ut {
constructor(e, t) {
if (super(), this.webcamVideoElement = e, this.webcamConfig = t, this.isClosed = true, this.resize = false, this.needToResize())
if (this.resize = true, this.cropSize = [this.webcamConfig.resizeHeight, this.webcamConfig.resizeWidth], this.cropBoxInd = Zt([0], "int32"), this.webcamConfig.centerCrop) {
let n = this.webcamConfig.resizeWidth * 1 / this.webcamVideoElement.width, s = this.webcamConfig.resizeHeight * 1 / this.webcamVideoElement.height, r = (1 - n) / 2, a = (1 - s) / 2, o = r + n, i = s + a;
this.cropBox = Zo([a, r, i, o], [1, 4]);
} else
this.cropBox = Zo([0, 0, 1, 1], [1, 4]);
}
summary() {
return "webcam";
}
static async create(e, t = {}) {
if (!K().get("IS_BROWSER"))
throw new Error("tf.data.webcam is only supported in browser environment.");
if (!e) {
if (e = document.createElement("video"), !t.resizeWidth || !t.resizeHeight)
throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");
e.width = t.resizeWidth, e.height = t.resizeHeight;
}
let n = new Y0(e, t);
return await n.start(), n;
}
async start() {
this.webcamConfig.facingMode && w.assert(this.webcamConfig.facingMode === "user" || this.webcamConfig.facingMode === "environment", () => `Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`);
try {
this.stream = await navigator.mediaDevices.getUserMedia({ video: { deviceId: this.webcamConfig.deviceId, facingMode: this.webcamConfig.facingMode ? this.webcamConfig.facingMode : "user", width: this.webcamVideoElement.width, height: this.webcamVideoElement.height } });
} catch (e) {
throw e.message = `Error thrown while initializing video stream: ${e.message}`, e;
}
if (!this.stream)
throw new Error("Could not obtain video from webcam.");
try {
this.webcamVideoElement.srcObject = this.stream;
} catch (e) {
console.log(e), this.webcamVideoElement.src = window.URL.createObjectURL(this.stream);
}
return this.webcamVideoElement.play(), this.isClosed = false, new Promise((e) => {
this.webcamVideoElement.onloadedmetadata = () => {
e();
};
});
}
async next() {
if (this.isClosed)
return { value: null, done: true };
let e;
try {
e = Gk.fromPixels(this.webcamVideoElement);
} catch (t) {
throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(t)}`);
}
if (this.resize)
try {
return { value: this.cropAndResizeFrame(e), done: false };
} catch (t) {
throw new Error(`Error thrown cropping the video: ${t.message}`);
} finally {
e.dispose();
}
else
return { value: e, done: false };
}
needToResize() {
return !!(this.webcamConfig.resizeWidth && this.webcamConfig.resizeHeight && (this.webcamVideoElement.width !== this.webcamConfig.resizeWidth || this.webcamVideoElement.height !== this.webcamConfig.resizeHeight));
}
cropAndResizeFrame(e) {
return q(() => {
let t = Pn(le(e, "float32"), 0), n;
n = Kn.cropAndResize(t, this.cropBox, this.cropBoxInd, this.cropSize, "bilinear");
let s = n.shape;
return U(n, s.slice(1));
});
}
async capture() {
return (await this.next()).value;
}
stop() {
this.stream.getTracks().forEach((t) => t.stop());
try {
this.webcamVideoElement.srcObject = null;
} catch (t) {
console.log(t), this.webcamVideoElement.src = null;
}
this.isClosed = true;
}
toArray() {
throw new Error("Can not convert infinite video stream to array.");
}
};
var Q0 = class {
};
var Z0 = class extends Ut {
split(e) {
return new DU(this, e);
}
};
var DU = class extends Z0 {
constructor(e, t) {
super(), this.upstream = e, this.impl = new FU(e, t);
}
summary() {
return this.impl.summary();
}
async next() {
return this.impl.next();
}
};
var FU = class extends lv {
constructor(e, t) {
super(), this.upstream = e, this.separator = t, this.carryover = "";
}
summary() {
return `${this.upstream.summary()} -> Split('${this.separator}')`;
}
async pump() {
let e = await this.upstream.next();
if (e.done)
return this.carryover === "" ? false : (this.outputQueue.push(this.carryover), this.carryover = "", true);
let t = e.value.split(this.separator);
t[0] = this.carryover + t[0];
for (let n of t.slice(0, -1))
this.outputQueue.push(n);
return this.carryover = t[t.length - 1], true;
}
};
var OU = class extends Ut {
decodeUTF8() {
return new PU(this);
}
};
var PU = class extends Z0 {
constructor(e) {
super(), this.upstream = e, this.impl = new zU(e);
}
summary() {
return this.impl.summary();
}
async next() {
return this.impl.next();
}
};
var zU = class extends lv {
constructor(e) {
if (super(), this.upstream = e, K().get("IS_BROWSER"))
this.decoder = new TextDecoder("utf-8");
else {
let { StringDecoder: t } = sk();
this.decoder = new t("utf8");
}
}
summary() {
return `${this.upstream.summary()} -> Utf8`;
}
async pump() {
let e = await this.upstream.next(), t;
if (e.done)
return false;
t = e.value;
let n;
return K().get("IS_BROWSER") ? n = this.decoder.decode(t, { stream: true }) : n = this.decoder.write(Buffer.from(t.buffer)), this.outputQueue.push(n), true;
}
};
var J0 = class extends OU {
constructor(e, t = {}) {
super(), this.file = e, this.options = t, w.assert(e instanceof Uint8Array || (K().get("IS_BROWSER") ? e instanceof File || e instanceof Blob : false), () => "FileChunkIterator only supports File, Blob and Uint8Array right now."), this.offset = t.offset || 0, this.chunkSize = t.chunkSize || 1024 * 1024;
}
summary() {
return `FileChunks ${this.file}`;
}
async next() {
return this.offset >= (this.file instanceof Uint8Array ? this.file.byteLength : this.file.size) ? { value: null, done: true } : { value: await new Promise((t, n) => {
let s = this.offset + this.chunkSize;
if (this.file instanceof Uint8Array)
t(new Uint8Array(this.file.slice(this.offset, s)));
else {
let r = new FileReader();
r.onload = (o) => {
let i = r.result;
if (i instanceof ArrayBuffer && (i = new Uint8Array(i)), !(i instanceof Uint8Array))
return n(new TypeError("FileReader returned unknown type."));
t(i);
}, r.onabort = (o) => n(new Error("Aborted")), r.onerror = (o) => n(new Error(o.type));
let a = this.file.slice(this.offset, s);
r.readAsArrayBuffer(a);
}
this.offset = s;
}), done: false };
}
};
async function LU(e, t = {}, n) {
let s, r;
typeof e == "string" ? s = e : (s = e.url, r = MU(e));
let a = await (n || w.fetch)(s, r);
if (a.ok) {
let o = new Uint8Array(await a.arrayBuffer());
return new J0(o, t);
} else
throw new Error(a.statusText);
}
var MU = (e) => ({ method: e.method, headers: e.headers, body: e.body, mode: e.mode, credentials: e.credentials, cache: e.cache, redirect: e.redirect, referrer: e.referrer, integrity: e.integrity });
function eC(e) {
return typeof e == "string" && e.slice(0, 7) === "file://";
}
var tC = class extends Q0 {
constructor(e, t = {}) {
super(), this.input = e, this.options = t;
}
async iterator() {
if (eC(this.input) && K().get("IS_NODE")) {
let e = pg();
this.input = e.readFileSync(this.input.slice(7));
}
return new J0(this.input, this.options);
}
};
var nC = class extends Q0 {
constructor(e, t = {}) {
super(), this.url = e, this.fileOptions = t;
}
async iterator() {
return eC(this.url) ? new tC(this.url, this.fileOptions).iterator() : LU(this.url, this.fileOptions);
}
};
function BU(e, t = {}) {
return new K0(new nC(e), t);
}
function VU(e) {
let t = uv(e);
return $n(async () => t);
}
function WU(e) {
return $n(async () => {
let t = await e();
return uv(() => t.next());
});
}
async function UU(e, t) {
return Y0.create(e, t);
}
async function GU(e) {
return X0.create(e);
}
var HU = "0.0.0";
function be(e, t) {
Array.isArray(e) || (e = [e]), e.forEach((n) => {
n != null && w.assert(n.dtype !== "complex64", () => `${t} does not support complex64 tensors in the CPU backend.`);
});
}
var qU = ws.whereImpl;
var sC = class extends il {
constructor() {
super(), this.blockSize = 48, this.firstUse = true, this.data = new Zd(this, ds());
}
nextDataId() {
return sC.nextDataId++;
}
write(e, t, n) {
this.firstUse && (this.firstUse = false, K().get("IS_NODE") && C.warn(`
============================
Hi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details.
============================`));
let s = { id: this.nextDataId() };
return this.data.set(s, { values: e, dtype: n, refCount: 1 }), s;
}
makeTensorInfo(e, t, n) {
let s;
if (t === "string" && n != null && n.length > 0 && w.isString(n[0])) {
let r = n.map((a) => w.encodeString(a));
s = this.write(r, e, t);
} else
s = this.write(n, e, t);
return { dataId: s, shape: e, dtype: t };
}
refCount(e) {
return this.data.has(e) ? this.data.get(e).refCount : 0;
}
incRef(e) {
let t = this.data.get(e);
t.refCount++;
}
decRef(e) {
if (this.data.has(e)) {
let t = this.data.get(e);
t.refCount--;
}
}
move(e, t, n, s, r) {
this.data.set(e, { values: t, dtype: s, refCount: r });
}
numDataIds() {
return this.data.numDataIds();
}
async read(e) {
return this.readSync(e);
}
readSync(e) {
let { dtype: t, complexTensorInfos: n } = this.data.get(e);
if (t === "complex64") {
let s = this.readSync(n.real.dataId), r = this.readSync(n.imag.dataId);
return C.mergeRealAndImagArrays(s, r);
}
return this.data.get(e).values;
}
bufferSync(e) {
let t = this.readSync(e.dataId);
if (e.dtype === "string")
try {
let n = t.map((s) => w.decodeString(s));
return Ae(e.shape, e.dtype, n);
} catch (n) {
throw new Error("Failed to decode encoded string bytes into utf-8");
}
return Ae(e.shape, e.dtype, t);
}
makeOutput(e, t, n) {
return ds().makeTensorFromTensorInfo(this.makeTensorInfo(t, n, e), this);
}
disposeData(e, t = false) {
if (this.data.has(e)) {
if (this.data.get(e).refCount--, !t && this.data.get(e).refCount > 0)
return false;
let { complexTensorInfos: n } = this.data.get(e);
n != null && (this.disposeData(n.real.dataId, true), this.disposeData(n.imag.dataId, true)), this.data.delete(e);
}
return true;
}
disposeIntermediateTensorInfo(e) {
this.disposeData(e.dataId);
}
async time(e) {
let t = w.now();
return e(), { kernelMs: w.now() - t };
}
memory() {
return { unreliable: true, reasons: ["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."] };
}
where(e) {
be([e], "where");
let t = this.readSync(e.dataId);
return qU(e.shape, t);
}
dispose() {
}
floatPrecision() {
return 32;
}
epsilon() {
return super.epsilon();
}
};
var rC = sC;
rC.nextDataId = 0;
var cv = {};
Ee(cv, { addImpl: () => oC, bincountImpl: () => pv, bincountReduceImpl: () => iC, ceilImpl: () => uC, concatImpl: () => hv, equalImpl: () => lC, expImpl: () => dC, expm1Impl: () => hC, floorImpl: () => fC, gatherNdImpl: () => mC, gatherV2Impl: () => gC, greaterEqualImpl: () => yC, greaterImpl: () => bC, lessEqualImpl: () => xC, lessImpl: () => vC, linSpaceImpl: () => wC, logImpl: () => kC, maxImpl: () => SC, maximumImpl: () => IC, minimumImpl: () => CC, multiplyImpl: () => fv, negImpl: () => NC, notEqualImpl: () => TC, prodImpl: () => $C, rangeImpl: () => gv, rsqrtImpl: () => _C, scatterImpl: () => Ko, sigmoidImpl: () => FG, simpleAbsImpl: () => aC, sliceImpl: () => Vd, sparseFillEmptyRowsImpl: () => EC, sparseReshapeImpl: () => RC, sparseSegmentReductionImpl: () => bv, sqrtImpl: () => zG, squaredDifferenceImpl: () => DC, stridedSliceImpl: () => FC, stringNGramsImpl: () => OC, stringSplitImpl: () => PC, stringToHashBucketFastImpl: () => zC, subImpl: () => LC, tileImpl: () => MC, topKImpl: () => VC, transposeImpl: () => mv, uniqueImpl: () => WC });
function aC(e) {
let t = new Float32Array(e.length);
for (let n = 0; n < e.length; ++n)
t[n] = Math.abs(e[n]);
return t;
}
var jU = (e) => {
let { x: t } = e.inputs, n = e.backend;
be(t, "abs");
let s = new Float32Array(w.sizeFromShape(t.shape)), r = n.data.get(t.dataId).values;
return s = aC(r), n.makeOutput(s, t.shape, t.dtype);
};
var KU = { kernelName: di, backendName: "cpu", kernelFunc: jU };
function At(e) {
return (t, n, s, r, a) => {
let o = C.assertAndGetBroadcastShape(t, n), i = o.length, u = w.computeStrides(o), l = w.sizeFromShape(o), c = w.getTypedArrayFromDType(a, l), p = t.length, d = n.length, h = w.computeStrides(t), f = w.computeStrides(n), m = C.getBroadcastDims(t, o), g = C.getBroadcastDims(n, o);
if (m.length + g.length === 0)
for (let b = 0; b < c.length; ++b)
c[b] = e(s[b % s.length], r[b % r.length]);
else
for (let b = 0; b < c.length; ++b) {
let y = w.indexToLoc(b, i, u), v = y.slice(-p);
m.forEach(($) => v[$] = 0);
let x = w.locToIndex(v, p, h), k = y.slice(-d);
g.forEach(($) => k[$] = 0);
let I = w.locToIndex(k, d, f);
c[b] = e(s[x], r[I]);
}
return [c, o];
};
}
function En(e) {
let { inputs: t, backend: n } = e, { real: s, imag: r } = t, a = n.data.get(s.dataId).values, o = n.data.get(r.dataId).values, i = n.makeTensorInfo(s.shape, "complex64"), u = n.data.get(i.dataId);
return u.complexTensorInfos = { real: n.makeTensorInfo(s.shape, "float32", a), imag: n.makeTensorInfo(r.shape, "float32", o) }, i;
}
var XU = { kernelName: np, backendName: "cpu", kernelFunc: En };
function Bd(e, t, n = "float32") {
if (n === "complex64") {
let r = Bd(e, t, "float32"), a = Bd(e, t, "float32");
return En({ inputs: { real: r, imag: a }, backend: e });
}
let s = w.makeZerosTypedArray(w.sizeFromShape(t), n);
return e.makeTensorInfo(t, n, s);
}
function Os(e) {
let { inputs: t, backend: n } = e, { x: s } = t;
return n.incRef(s.dataId), { dataId: s.dataId, shape: s.shape, dtype: s.dtype };
}
var YU = { kernelName: Wa, backendName: "cpu", kernelFunc: Os };
function ga(e) {
let { inputs: t, backend: n } = e, { input: s } = t, r = n.data.get(s.dataId).complexTensorInfos.real, a = n.data.get(r.dataId).values;
return n.makeTensorInfo(r.shape, r.dtype, a);
}
var QU = { kernelName: cp, backendName: "cpu", kernelFunc: ga };
function kr(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { dtype: a } = s;
if (a === "complex64") {
if (r.dtype === "complex64")
return Os({ inputs: { x: r }, backend: n });
let o = Bd(n, r.shape, r.dtype), i = kr({ inputs: { x: r }, backend: n, attrs: { dtype: "float32" } }), u = En({ inputs: { real: i, imag: o }, backend: n });
return n.disposeIntermediateTensorInfo(o), n.disposeIntermediateTensorInfo(i), u;
}
if (r.dtype === "complex64") {
let o = ga({ inputs: { input: r }, backend: n }), i = kr({ inputs: { x: o }, backend: n, attrs: { dtype: a } });
return n.disposeIntermediateTensorInfo(o), i;
}
if (!w.hasEncodingLoss(r.dtype, a)) {
let o = Os({ inputs: { x: r }, backend: n });
return { dataId: o.dataId, shape: o.shape, dtype: a };
}
if (a === "int32") {
let o = n.data.get(r.dataId).values, i = Int32Array.from(o);
return n.makeTensorInfo(r.shape, "int32", i);
}
if (a === "bool") {
let o = n.data.get(r.dataId).values, i = w.toTypedArray([0], r.dtype), [u, l] = At((c, p) => c !== p ? 1 : 0)(r.shape, [], o, i, "bool");
return n.makeTensorInfo(l, "bool", u);
}
throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${a}`);
}
var ZU = { kernelName: Ta, backendName: "cpu", kernelFunc: kr };
function Gt(e, t, n, s) {
return n == null ? ({ inputs: r, backend: a }) => {
let { a: o, b: i } = r, u = a;
be([o, i], e);
let l = u.data.get(o.dataId).values, c = u.data.get(i.dataId).values, p = o.dtype === "string" ? C.fromUint8ToStringArray(l) : l, d = o.dtype === "string" ? C.fromUint8ToStringArray(c) : c, h = s || o.dtype, [f, m] = t(o.shape, i.shape, p, d, h);
return u.makeTensorInfo(m, h, f);
} : ({ inputs: r, backend: a }) => {
let { a: o, b: i } = r, u = a;
if (o.dtype === "complex64" || i.dtype === "complex64") {
let l = kr({ inputs: { x: o }, backend: u, attrs: { dtype: "complex64" } }), c = u.data.get(l.dataId), p = c.complexTensorInfos.real, d = c.complexTensorInfos.imag, h = u.data.get(p.dataId).values, f = u.data.get(d.dataId).values, m = kr({ inputs: { x: i }, backend: u, attrs: { dtype: "complex64" } }), g = u.data.get(m.dataId), b = g.complexTensorInfos.real, y = g.complexTensorInfos.imag, v = u.data.get(b.dataId).values, x = u.data.get(y.dataId).values, [k, I, $] = n(o.shape, i.shape, h, f, v, x), R = u.makeTensorInfo($, "float32", k), E = u.makeTensorInfo($, "float32", I), P = En({ inputs: { real: R, imag: E }, backend: u });
return u.disposeIntermediateTensorInfo(l), u.disposeIntermediateTensorInfo(m), u.disposeIntermediateTensorInfo(R), u.disposeIntermediateTensorInfo(E), P;
} else {
let l = u.data.get(o.dataId).values, c = u.data.get(i.dataId).values, p = s || o.dtype, [d, h] = t(o.shape, i.shape, l, c, p);
return u.makeTensorInfo(h, p, d);
}
};
}
function dv(e) {
return (t, n, s, r, a, o) => {
let i = C.assertAndGetBroadcastShape(t, n), u = w.sizeFromShape(i), l = i.length, c = w.computeStrides(i), p = w.getTypedArrayFromDType("float32", u), d = w.getTypedArrayFromDType("float32", u), h = C.getBroadcastDims(t, i), f = C.getBroadcastDims(n, i), m = C.mergeRealAndImagArrays(s, r), g = C.mergeRealAndImagArrays(a, o), b = t.length, y = w.computeStrides(t), v = n.length, x = w.computeStrides(n);
if (h.length + f.length === 0)
for (let k = 0; k < p.length; k++) {
let I = k % m.length, $ = k % g.length, R = e(m[I * 2], m[I * 2 + 1], g[$ * 2], g[$ * 2 + 1]);
p[k] = R.real, d[k] = R.imag;
}
else
for (let k = 0; k < p.length; k++) {
let I = w.indexToLoc(k, l, c), $ = I.slice(-b);
h.forEach((D) => $[D] = 0);
let R = w.locToIndex($, b, y), E = I.slice(-v);
f.forEach((D) => E[D] = 0);
let P = w.locToIndex(E, v, x), A = e(m[R * 2], m[R * 2 + 1], g[P * 2], g[P * 2 + 1]);
p[k] = A.real, d[k] = A.imag;
}
return [p, d, i];
};
}
var oC = At((e, t) => e + t);
var JU = dv((e, t, n, s) => ({ real: e + n, imag: t + s }));
var oi = Gt(Cr, oC, JU);
var eG = { kernelName: Cr, backendName: "cpu", kernelFunc: oi };
function pv(e, t, n, s, r) {
let a = w.sizeFromShape(s), o = w.makeZerosTypedArray(r, n);
for (let i = 0; i < e.length; i++) {
let u = e[i];
if (u < 0)
throw new Error("Input x must be non-negative!");
u >= r || (a > 0 ? o[u] += t[i] : o[u] += 1);
}
return o;
}
function iC(e, t, n, s = false) {
let r = e.shape[0], a = e.shape[1], o = Ae([r, n], t.dtype);
for (let i = 0; i < r; i++)
for (let u = 0; u < a; u++) {
let l = e.get(i, u);
if (l < 0)
throw new Error("Input x must be non-negative!");
l >= n || (s ? o.set(1, i, l) : t.size > 0 ? o.set(o.get(i, l) + t.get(i, u), i, l) : o.set(o.get(i, l) + 1, i, l));
}
return o;
}
function Dr(e) {
return (t, n, s) => {
let r = w.getTypedArrayFromDType(n, t.length);
for (let a = 0; a < t.length; ++a)
r[a] = e(t[a], s);
return r;
};
}
function st(e, t, n) {
return ({ inputs: s, attrs: r, backend: a }) => {
let { x: o } = s;
if (be(o, e), o.dtype === "string" || n === "string")
throw new Error("unaryKernelFunc does not support string input/output");
let i = a, u = i.data.get(o.dataId).values, l = w.sizeFromShape(o.shape), c = n || o.dtype, p = w.getArrayFromDType(c, l);
for (let d = 0; d < l; ++d)
p[d] = t(u[d], r);
return i.makeTensorInfo(o.shape, c, p);
};
}
function ru(e, t, n) {
return ({ inputs: s, attrs: r, backend: a }) => {
let { x: o } = s;
if (be(o, e), o.dtype === "string" || n === "string")
throw new Error("unaryKernelFunc does not support string input/output");
let i = a, u = i.data.get(o.dataId).values, l = n || o.dtype, c = t(u, l, r);
return i.makeTensorInfo(o.shape, l, c);
};
}
var uC = Dr((e) => Math.ceil(e));
var tG = ru($a, uC);
var nG = { kernelName: $a, backendName: "cpu", kernelFunc: tG };
function hv(e, t, n, s) {
let r = w.getArrayFromDType(n, w.sizeFromShape(t));
if (s && n !== "string") {
let a = 0;
e.forEach((o) => {
let i = w.sizeFromShape(o.shape);
r.set(o.vals, a), a += i;
});
} else {
let a = 0;
e.forEach((o) => {
let i = n === "string" ? C.fromUint8ToStringArray(o.vals) : o.vals, u = 0;
for (let l = 0; l < o.shape[0]; ++l) {
let c = l * t[1] + a;
for (let p = 0; p < o.shape[1]; ++p)
r[c + p] = i[u++];
}
a += o.shape[1];
});
}
return r;
}
var lC = At((e, t) => e === t ? 1 : 0);
var cC = Gt(bi, lC, null, "bool");
var sG = { kernelName: bi, backendName: "cpu", kernelFunc: cC };
var dC = Dr((e) => Math.exp(e));
var pC = ru(za, dC, "float32");
var rG = { kernelName: za, backendName: "cpu", kernelFunc: pC };
var hC = Dr((e) => Math.expm1(e));
var aG = ru(vi, hC);
var oG = { kernelName: vi, backendName: "cpu", kernelFunc: aG };
var fC = Dr((e) => Math.floor(e));
var iG = ru(La, fC);
var uG = { kernelName: La, backendName: "cpu", kernelFunc: iG };
function mC(e, t, n, s, r, a, o, i, u) {
let l = Ae([s, a], n);
for (let c = 0; c < s; c++) {
let p = [], d = 0;
for (let h = 0; h < r; h++) {
let f = e[c * r + h];
d += f * o[h], p.push(f);
}
if (d < 0 || d >= u / a)
throw new Error(`Invalid indices: ${p} does not index into ${i}`);
for (let h = 0; h < a; h++)
l.values[c * a + h] = t.get(...t.indexToLoc(d * a + h));
}
return l;
}
function gC(e, t, n) {
let s = Ae(n, e.dtype);
for (let r = 0; r < s.size; ++r) {
let o = s.indexToLoc(r).slice(), i = o[0], u = o[2], l = t.locToIndex([i, u]);
o[2] = t.values[l];
let c = e.locToIndex(o);
0 <= c && c < e.values.length && (s.values[r] = e.values[c]);
}
return s;
}
var bC = At((e, t) => e > t ? 1 : 0);
var lG = Gt(Si, bC, null, "bool");
var cG = { kernelName: Si, backendName: "cpu", kernelFunc: lG };
var yC = At((e, t) => e >= t ? 1 : 0);
var dG = Gt(Va, yC, null, "bool");
var pG = { kernelName: Va, backendName: "cpu", kernelFunc: dG };
var vC = At((e, t) => e < t ? 1 : 0);
var hG = Gt(Ii, vC, null, "bool");
var fG = { kernelName: Ii, backendName: "cpu", kernelFunc: hG };
var xC = At((e, t) => e <= t ? 1 : 0);
var mG = Gt(Ci, xC, null, "bool");
var gG = { kernelName: Ci, backendName: "cpu", kernelFunc: mG };
function wC(e, t, n) {
let s = (t - e) / (n - 1), r = w.makeZerosTypedArray(n, "float32");
r[0] = e;
for (let a = 1; a < r.length; a++)
r[a] = r[a - 1] + s;
return r;
}
var kC = Dr((e) => Math.log(e));
var bG = ru(Ga, kC);
var yG = { kernelName: Ga, backendName: "cpu", kernelFunc: bG };
function SC(e, t, n, s) {
let r = w.getTypedArrayFromDType(s, w.sizeFromShape(n));
for (let a = 0; a < r.length; ++a) {
let o = a * t, i = e[o];
for (let u = 0; u < t; ++u) {
let l = e[o + u];
(Number.isNaN(l) || l > i) && (i = l);
}
r[a] = i;
}
return r;
}
var IC = At((e, t) => Math.max(e, t));
var vG = Gt(qa, IC);
var xG = { kernelName: qa, backendName: "cpu", kernelFunc: vG };
var CC = At((e, t) => Math.min(e, t));
var wG = Gt(Ya, CC);
var kG = { kernelName: Ya, backendName: "cpu", kernelFunc: wG };
var fv = At((e, t) => e * t);
var SG = dv((e, t, n, s) => ({ real: e * n - t * s, imag: e * s + t * n }));
var eh = Gt(Za, fv, SG);
var IG = { kernelName: Za, backendName: "cpu", kernelFunc: eh };
function NC(e, t, n) {
let s = w.createScalarValue(-1, n);
return fv([], t, s, e, n);
}
function CG(e) {
let { inputs: t, backend: n } = e, { x: s } = t;
be(s, "neg");
let r = n.data.get(s.dataId).values, [a, o] = NC(r, s.shape, s.dtype);
return n.makeTensorInfo(o, s.dtype, a);
}
var NG = { kernelName: $i, backendName: "cpu", kernelFunc: CG };
var TC = At((e, t) => e !== t ? 1 : 0);
var TG = Gt(_i, TC, null, "bool");
var $G = { kernelName: _i, backendName: "cpu", kernelFunc: TG };
function mv(e, t, n, s, r) {
let a = t.length, o = w.sizeFromShape(t), i = w.computeStrides(t), u = w.computeStrides(r), l = w.getTypedArrayFromDType(n, w.sizeFromShape(r));
for (let c = 0; c < o; ++c) {
let p = w.indexToLoc(c, a, i), d = new Array(p.length);
for (let f = 0; f < d.length; f++)
d[f] = p[s[f]];
let h = w.locToIndex(d, a, u);
l[h] = e[c];
}
return l;
}
function wn(e) {
let { inputs: t, attrs: n, backend: s } = e, { x: r } = t, { perm: a } = n;
be(r, "transpose");
let o = r.shape.length, i = new Array(o);
for (let p = 0; p < i.length; p++)
i[p] = r.shape[a[p]];
let u = s.data.get(r.dataId).values, l = mv(u, r.shape, r.dtype, a, i);
return { dataId: s.write(l, i, r.dtype), shape: i, dtype: r.dtype };
}
var _G = { kernelName: Hs, backendName: "cpu", kernelFunc: wn };
function $C(e, t, n, s) {
let [r, a] = C.computeOutAndReduceShapes(e, s), o = cn(t, "int32"), i = w.makeZerosTypedArray(w.sizeFromShape(r), o), u = w.sizeFromShape(a);
for (let l = 0; l < i.length; ++l) {
let c = l * u, p = 1;
for (let d = 0; d < u; ++d)
p *= n[c + d];
i[l] = p;
}
return { outVals: i, outShape: r, outDtype: o };
}
function AG(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, keepDims: o } = s;
be(r, "prod");
let i = r.shape.length, u = w.parseAxisParam(a, r.shape), l = C.getAxesPermutation(u, i), c = u, p = r, d = [];
l != null && (p = wn({ inputs: { x: r }, backend: n, attrs: { perm: l } }), d.push(p), c = C.getInnerMostAxes(c.length, i));
let h = n.data.get(p.dataId).values, { outVals: f, outShape: m, outDtype: g } = $C(p.shape, p.dtype, h, c), b = m;
return o && (b = C.expandShapeToKeepDim(m, u)), d.forEach((y) => n.disposeIntermediateTensorInfo(y)), n.makeTensorInfo(b, g, f);
}
var EG = { kernelName: no, backendName: "cpu", kernelFunc: AG };
function gv(e, t, n, s) {
let r = e === t, a = e < t && n < 0, o = t < e && n > 1;
if (r || a || o)
return w.makeZerosTypedArray(0, s);
let i = Math.abs(Math.ceil((t - e) / n)), u = w.makeZerosTypedArray(i, s);
t < e && n === 1 && (n = -1), u[0] = e;
for (let l = 1; l < u.length; l++)
u[l] = u[l - 1] + n;
return u;
}
var _C = Dr((e) => 1 / Math.sqrt(e));
var RG = ru(oo, _C);
var DG = { kernelName: oo, backendName: "cpu", kernelFunc: RG };
function Ko(e, t, n, s, r, a, o, i, u, l) {
let c = [s / r, r], p = e.values, d = t.values;
if (s === 0)
return Ae(n, t.dtype);
let h = Ae(c, t.dtype);
typeof u == "string" || typeof u == "number" ? h.values.fill(u) : typeof u == "boolean" && h.values.fill(+u);
for (let f = 0; f < a; f++) {
let m = [], g = 0;
for (let b = 0; b < o; b++) {
let y = p[f * o + b];
m.push(y), g += y * i[b];
}
if (g < 0 || g >= s / r)
throw new Error(`Invalid indices: ${m} does not index into ${n}`);
for (let b = 0; b < r; b++)
l ? h.values[g * r + b] += d[f * r + b] : h.values[g * r + b] = t.rank === 0 ? d[0] : d[f * r + b];
}
return h;
}
var FG = Dr((e) => 1 / (1 + Math.exp(-e)));
var AC = st(uo, (e) => 1 / (1 + Math.exp(-e)));
var OG = { kernelName: uo, backendName: "cpu", kernelFunc: AC };
function Vd(e, t, n, s, r) {
let a = kt.isSliceContinous(s, t, n), o = w.sizeFromShape(n), i = w.computeStrides(s);
if (a) {
let p = kt.computeFlatOffset(t, i);
return r === "string" ? e.slice(p, p + o) : e.subarray(p, p + o);
}
let u = r === "string" ? C.fromUint8ToStringArray(e) : e, l = Ae(s, r, u), c = Ae(n, r);
for (let p = 0; p < c.size; ++p) {
let d = c.indexToLoc(p), h = d.map((f, m) => f + t[m]);
c.set(l.get(...h), ...d);
}
return r === "string" ? C.fromStringArrayToUint8(c.values) : c.values;
}
function ba(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { begin: a, size: o } = s;
be(r, "slice");
let [i, u] = kt.parseSliceParams(r, a, o);
kt.assertParamsValid(r, i, u);
let l = n.data.get(r.dataId).values, c = Vd(l, i, u, r.shape, r.dtype);
return n.makeTensorInfo(u, r.dtype, c);
}
var PG = { kernelName: Bi, backendName: "cpu", kernelFunc: ba };
function EC(e, t, n, s, r, a, o) {
let i = t[0], u = a[0], l = new Array(u), c = new Array(i), p = t[1];
if (u === 0) {
if (i !== 0)
throw new Error(C.getSparseFillEmptyRowsIndicesDenseShapeMismatch(i));
let g = w.getArrayFromDType(n, 0), b = w.getArrayFromDType(r, 0);
return [g, [0, p], b, l, c];
}
let d = true, h = 0, f = new Array(u).fill(0);
for (let g = 0; g < i; ++g) {
let b = e[g * p];
if (b < 0)
throw new Error(C.getSparseFillEmptyRowsNegativeIndexErrorMessage(g, b));
if (b >= u)
throw new Error(C.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(g, b, u));
++f[b], d = d && b >= h, h = b;
}
let m = true;
for (let g = 0; g < u; ++g) {
let b = f[g] === 0;
l[g] = b, m = m && !b, f[g] = Math.max(f[g], 1), g > 0 && (f[g] += f[g - 1]);
}
if (m && d) {
let g = e, b = s;
for (let y = 0; y < i; ++y)
c[y] = y;
return [g, [i, p], b, l, c];
} else {
let g = f[u - 1], b = w.getArrayFromDType(n, g * p), y = w.getArrayFromDType(r, g), v = new Array(u).fill(0);
for (let x = 0; x < i; ++x) {
let k = e[x * p], I = v[k], $ = (k === 0 ? 0 : f[k - 1]) + I;
v[k]++;
for (let R = 0; R < p; ++R)
b[$ * p + R] = e[x * p + R];
y[$] = s[x], c[x] = $;
}
for (let x = 0; x < u; ++x)
if (v[x] === 0) {
let I = x === 0 ? 0 : f[x - 1];
b[I * p + 0] = x;
for (let $ = 1; $ < p; ++$)
b[I * p + $] = 0;
y[I] = o;
}
return [b, [g, p], y, l, c];
}
}
function RC(e, t, n, s, r) {
let a = w.sizeFromShape(s), o = t[0], i = r.length, u = [], l = 1, c = -1;
for (let g = 0; g < i; ++g) {
let b = r[g];
if (b === -1) {
if (c !== -1)
throw new Error(C.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(c, g));
c = g, u.push(1);
} else {
if (b < 0)
throw new Error(C.getSparseReshapeNegativeOutputDimErrorMessage(g, b));
l *= b, u.push(b);
}
}
if (c !== -1) {
if (l <= 0)
throw new Error(C.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());
let g = Math.trunc(a / l);
if (l * g !== a)
throw new Error(C.getSparseReshapeInputOutputMultipleErrorMessage(s, u));
u[c] = g;
}
if (w.sizeFromShape(u) !== a)
throw new Error(C.getSparseReshapeInputOutputMismatchErrorMessage(s, u));
let d = s.length, h = [];
if (d > 0) {
h[d - 1] = 1;
for (let g = d - 2; g >= 0; --g)
h[g] = h[g + 1] * s[g + 1];
}
let f = [];
if (i > 0) {
f[i - 1] = 1;
for (let g = i - 2; g >= 0; --g)
f[g] = f[g + 1] * u[g + 1];
}
let m = w.getArrayFromDType(n, o * i);
for (let g = 0; g < o; ++g) {
let b = 0;
for (let y = 0; y < d; ++y)
b += e[g * d + y] * h[y];
for (let y = 0; y < i; ++y)
m[g * i + y] = Math.trunc(b / f[y]), b %= f[y];
}
return [m, [o, i], u];
}
function bv(e, t, n, s, r, a = false, o = 0) {
let i = s.length, u = [t[0], e.length / t[0]], l = u[1], p = i > 0 ? r[i - 1] + 1 : 0;
if (p < 0)
throw new Error(C.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());
let d = t.slice();
d[0] = p;
let h = d.reduce((v, x) => v * x, 1), f = w.getArrayFromDType(n, h);
if (i === 0)
return p > 0 && f.fill(o), [f, d];
if (p <= 0)
throw new Error(C.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());
let m = 0, g = 1, b = 0, y = r[m];
for (; ; ) {
let v = 0;
if (g < i) {
if (v = r[g], y === v) {
++g;
continue;
}
if (y >= v)
throw new Error(C.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage());
}
if (y < 0 || y >= p)
throw new Error(C.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(y, p));
y > b && f.fill(o, b * l, y * l);
for (let x = m; x < g; ++x) {
let k = s[x];
if (k < 0 || k >= u[0])
throw new Error(C.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(x, s[x], u[0]));
for (let I = 0; I < l; I++)
f[y * l + I] += e[k * l + I];
}
if (a)
for (let x = 0; x < l; x++)
f[y * l + x] /= g - m;
if (m = g, ++g, b = y + 1, y = v, g > i)
break;
}
return b < p && f.fill(o, b * l, p * l), [f, d];
}
var zG = Dr((e) => Math.sqrt(e));
var LG = st(lo, (e) => Math.sqrt(e));
var MG = { kernelName: lo, backendName: "cpu", kernelFunc: LG };
var DC = At((e, t) => {
let n = e - t;
return n * n;
});
var BG = Gt(ho, DC);
var VG = { kernelName: ho, backendName: "cpu", kernelFunc: BG };
function FC(e, t, n, s) {
let r = Ae(e, t.dtype);
for (let a = 0; a < r.size; a++) {
let o = r.indexToLoc(a), i = new Array(o.length);
for (let u = 0; u < i.length; u++)
i[u] = o[u] * n[u] + s[u];
r.set(t.get(...i), ...o);
}
return r;
}
var WG = class {
constructor(e, t, n, s, r, a) {
this.separator = w.encodeString(e), this.nGramWidths = t, this.leftPad = w.encodeString(n), this.rightPad = w.encodeString(s), this.padWidth = r, this.preserveShort = a;
}
getPadWidth(e) {
return Math.min(this.padWidth < 0 ? e - 1 : this.padWidth, e - 1);
}
getNumNGrams(e, t) {
let n = this.getPadWidth(t);
return Math.max(0, e + 2 * n - t + 1);
}
createNGrams(e, t, n, s, r, a) {
for (let o = 0; o < r; ++o) {
let i = this.getPadWidth(a), u = Math.max(0, i - o), l = Math.max(0, i - (r - (o + 1))), c = a - (u + l), p = t + (u > 0 ? 0 : o - i), d = 0;
d += u * this.leftPad.length;
for (let b = 0; b < c; ++b)
d += e[p + b].length;
d += l * this.rightPad.length, d += (u + l + c - 1) * this.separator.length, n[s + o] = new Uint8Array(d);
let f = n[s + o], m = 0, g = (b) => b.forEach((y) => f[m++] = y);
for (let b = 0; b < u; ++b)
g(this.leftPad), g(this.separator);
for (let b = 0; b < c - 1; ++b)
g(e[p + b]), g(this.separator);
if (c > 0) {
g(e[p + c - 1]);
for (let b = 0; b < l; ++b)
g(this.separator), g(this.rightPad);
} else {
for (let b = 0; b < l - 1; ++b)
g(this.rightPad), g(this.separator);
g(this.rightPad);
}
}
}
compute(e, t) {
let n = e.length, s = t.length;
if (s > 0) {
let i = t[0];
if (i !== 0)
throw new Error(`First split value must be 0, got ${i}`);
for (let u = 1; u < s; ++u) {
let l = t[u] >= i;
if (l = l && t[u] <= n, !l)
throw new Error(`Invalid split value ${t[u]}, must be in [${i}, ${n}]`);
i = t[u];
}
if (i !== n)
throw new Error(`Last split value must be data size. Expected ${n}, got ${i}`);
}
let r = s - 1, a = w.getArrayFromDType("int32", s);
if (n === 0 || s === 0) {
let i = new Array(n);
for (let u = 0; u <= r; ++u)
a[u] = 0;
return [i, a];
}
a[0] = 0;
for (let i = 1; i <= r; ++i) {
let u = t[i] - t[i - 1], l = 0;
this.nGramWidths.forEach((c) => {
l += this.getNumNGrams(u, c);
}), this.preserveShort && u > 0 && l === 0 && (l = 1), a[i] = a[i - 1] + l;
}
let o = new Array(a[r]);
for (let i = 0; i < r; ++i) {
let u = t[i], l = a[i];
if (this.nGramWidths.forEach((c) => {
let p = t[i + 1] - t[i], d = this.getNumNGrams(p, c);
this.createNGrams(e, u, o, l, d, c), l += d;
}), this.preserveShort && l === a[i]) {
let c = t[i + 1] - t[i];
if (c === 0)
continue;
let p = c + 2 * this.padWidth, d = 1;
this.createNGrams(e, u, o, l, d, p);
}
}
return [o, a];
}
};
function OC(e, t, n, s, r, a, o, i) {
return new WG(n, s, r, a, o, i).compute(e, t);
}
function UG(e, t, n, s) {
if (!e.length)
return;
if (t.length === 0) {
for (let a = 0; a < e.length; ++a)
s.push(e.subarray(a, a + 1));
return;
}
if (t.length === 1) {
let a = t[0], o = e.indexOf(a);
for (; o !== -1; ) {
let i = e.subarray(0, o);
(!n || i.length !== 0) && s.push(i), e = e.subarray(o + 1), o = e.indexOf(a);
}
(!n || e.length !== 0) && s.push(e);
return;
}
let r = 0;
for (let a = 0; a < e.length + 1; a++)
if (a === e.length || t.indexOf(e[a]) !== -1) {
let o = e.subarray(r, a);
(!n || o.length !== 0) && s.push(o), r = a + 1;
}
}
function PC(e, t, n) {
let s = e.length, r = [], a = 0, o = 0, i = new Array(s);
for (let d = 0; d < s; ++d) {
let h = r.length;
UG(e[d], t, n, r);
let f = r.length - h;
i[d] = f, a += f, o = Math.max(o, f);
}
let u = w.getArrayFromDType("int32", a * 2), l = new Array(a), c = [s, o], p = 0;
for (let d = 0; d < s; ++d)
for (let h = 0; h < i[d]; ++h)
u[p * 2] = d, u[p * 2 + 1] = h, l[p] = r[p], ++p;
return [u, l, c];
}
function zC(e, t) {
let n = w.getArrayFromDType("int32", e.length);
for (let s = 0; s < e.length; ++s)
n[s] = w.fingerPrint64(e[s]).modulo(t).getLowBitsUnsigned();
return n;
}
var LC = At((e, t) => e - t);
var GG = dv((e, t, n, s) => ({ real: e - n, imag: t - s }));
var yv = Gt(fo, LC, GG);
var HG = { kernelName: fo, backendName: "cpu", kernelFunc: yv };
function MC(e, t) {
let n = new Array(e.rank);
for (let r = 0; r < n.length; r++)
n[r] = e.shape[r] * t[r];
let s = Ae(n, e.dtype);
for (let r = 0; r < s.values.length; ++r) {
let a = s.indexToLoc(r), o = new Array(e.rank);
for (let u = 0; u < o.length; u++)
o[u] = a[u] % e.shape[u];
let i = e.locToIndex(o);
s.values[r] = e.values[i];
}
return s;
}
var Pu = (e, t) => {
let n = t.value - e.value;
return n === 0 ? e.index - t.index : n;
};
function BC(e, t, n = 0, s = e.length - 1) {
for (; s > n; ) {
if (s - n > 600) {
let i = s - n + 1, u = t - n + 1, l = Math.log(i), c = 0.5 * Math.exp(2 * l / 3), p = 0.5 * Math.sqrt(l * c * (i - c) / i) * Math.sign(u - i / 2), d = Math.max(n, Math.floor(t - u * c / i + p)), h = Math.min(s, Math.floor(t + (i - u) * c / i + p));
BC(e, t, d, h);
}
let r = e[t], a = n, o = s;
for (w.swap(e, n, t), Pu(e[s], r) > 0 && w.swap(e, n, s); a < o; ) {
for (w.swap(e, a, o), a++, o--; Pu(e[a], r) < 0; )
a = a + 1;
for (; Pu(e[o], r) > 0; )
o = o - 1;
}
Pu(e[n], r) === 0 ? w.swap(e, n, o) : (o = o + 1, w.swap(e, o, s)), o <= t && (n = o + 1), t <= o && (s = o - 1);
}
}
function VC(e, t, n, s, r) {
let a = t[t.length - 1], [o, i] = [e.length / a, a], u = w.getTypedArrayFromDType(n, o * s), l = w.getTypedArrayFromDType("int32", o * s);
for (let p = 0; p < o; p++) {
let d = p * i, h = e.subarray(d, d + i), f = new Array(h.length);
h.forEach((y, v) => f[v] = { value: y, index: v }), s < f.length && (BC(f, s), f = f.slice(0, s)), r && f.sort(Pu);
let m = p * s, g = u.subarray(m, m + s), b = l.subarray(m, m + s);
for (let y = 0; y < s; y++)
g[y] = f[y].value, b[y] = f[y].index;
}
let c = t.slice();
return c[c.length - 1] = s, [Ae(c, n, u), Ae(c, "int32", l)];
}
function WC(e, t, n, s) {
let r = w.parseAxisParam(t, n)[0], a = [1, n[0], 1];
for (let f = 0; f < r; f++)
a[0] *= n[f];
a[1] = n[r];
for (let f = r + 1; f < n.length; f++)
a[2] *= n[f];
let o = {}, i = new Int32Array(n[r]), u = new Vt(a, s, e), l = [], c = a[0] === 1 && a[2] === 1;
for (let f = 0; f < n[r]; f++) {
let m;
if (c)
m = e[f].toString();
else {
let g = [];
for (let b = 0; b < a[0]; b++)
for (let y = 0; y < a[2]; y++)
g.push(u.get(b, f, y));
m = g.join(",");
}
if (o[m] !== void 0)
i[f] = o[m];
else {
let g = Object.keys(o).length;
o[m] = g, i[f] = g, l.push(f);
}
}
let p = a.slice();
p[1] = Object.keys(o).length;
let d = new Vt(p, s);
l.forEach((f, m) => {
for (let g = 0; g < a[0]; g++)
for (let b = 0; b < a[2]; b++)
d.set(u.get(g, f, b), g, m, b);
});
let h = n.slice();
return h[r] = p[1], { outputValues: d.values, outputShape: h, indices: i };
}
var Ohe = "0.0.0";
xp("cpu", () => new rC(), 1);
var UC = st(Pa, (e) => e >= 0 ? e : Math.exp(e) - 1);
var qG = { kernelName: Pa, backendName: "cpu", kernelFunc: UC };
function GC(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { alpha: a } = s;
be([r], "leakyRelu");
let o = w.sizeFromShape(r.shape), i = n.data.get(r.dataId).values, u = w.getTypedArrayFromDType("float32", o);
for (let l = 0; l < i.length; l++)
u[l] = i[l] < 0 ? a * i[l] : i[l];
return n.makeTensorInfo(r.shape, "float32", u);
}
var jG = { kernelName: Ua, backendName: "cpu", kernelFunc: GC };
var KG = At((e, t) => e < 0 ? t * e : e);
function HC(e) {
let { inputs: t, backend: n } = e, { x: s, alpha: r } = t;
be([s, r], "prelu");
let a = n.data.get(s.dataId).values, o = n.data.get(r.dataId).values, [i, u] = KG(s.shape, r.shape, a, o, "float32");
return n.makeTensorInfo(u, "float32", i);
}
var XG = { kernelName: to, backendName: "cpu", kernelFunc: HC };
var qC = st(so, (e) => Math.max(0, e));
var YG = { kernelName: so, backendName: "cpu", kernelFunc: qC };
var jC = st(ao, (e) => Math.min(Math.max(0, e), 6));
var QG = { kernelName: ao, backendName: "cpu", kernelFunc: jC };
function Wd(e, t, n, s, r) {
if (n === "linear")
return Os({ inputs: { x: t }, backend: e });
if (n === "relu")
return qC({ inputs: { x: t }, backend: e });
if (n === "elu")
return UC({ inputs: { x: t }, backend: e });
if (n === "relu6")
return jC({ inputs: { x: t }, backend: e });
if (n === "prelu")
return HC({ inputs: { x: t, alpha: s }, backend: e });
if (n === "leakyrelu")
return GC({ inputs: { x: t }, backend: e, attrs: { alpha: r } });
if (n === "sigmoid")
return AC({ inputs: { x: t }, backend: e });
throw new Error(`Activation ${n} has not been implemented for the CPU backend.`);
}
function pt(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { shape: a } = s, o = w.sizeFromShape(r.shape), i = w.inferFromImplicitShape(a, o), u = w.sizeFromShape(i);
w.assert(o === u, () => `The new shape (${i}) has ${u} elements and the old shape (${r.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`), n.incRef(r.dataId);
let l = n.data.get(r.dataId);
if (l.complexTensorInfos != null) {
let c = l.complexTensorInfos.real, p = l.complexTensorInfos.imag;
c.shape = i, p.shape = i;
}
return { dataId: r.dataId, shape: i, dtype: r.dtype };
}
var ZG = { kernelName: Oi, backendName: "cpu", kernelFunc: pt };
function KC(e) {
let { inputs: t, backend: n, attrs: s } = e, { a: r, b: a } = t, { transposeA: o, transposeB: i } = s;
be([r, a], "matMul");
let u = r.shape.length, l = a.shape.length, c = o ? r.shape[u - 2] : r.shape[u - 1], p = i ? a.shape[l - 1] : a.shape[l - 2], d = o ? r.shape[u - 1] : r.shape[u - 2], h = i ? a.shape[l - 2] : a.shape[l - 1], f = r.shape.slice(0, -2), m = a.shape.slice(0, -2), g = w.sizeFromShape(f), b = w.sizeFromShape(m), v = Qi.assertAndGetBroadcastShape(r.shape.slice(0, -2), a.shape.slice(0, -2)).concat([d, h]);
w.assert(c === p, () => `Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${r.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);
let x = o ? [g, c, d] : [g, d, c], k = i ? [b, h, p] : [b, p, h], I = pt({ inputs: { x: r }, backend: n, attrs: { shape: x } }), $ = pt({ inputs: { x: a }, backend: n, attrs: { shape: k } }), R = o ? I.shape[1] : I.shape[2], E = o ? I.shape[2] : I.shape[1], P = i ? $.shape[1] : $.shape[2], A = Math.max(g, b), D = n.data.get(I.dataId).values, T = n.data.get($.dataId).values, L = w.computeStrides(I.shape), W = w.computeStrides($.shape), [j, Y, X] = o ? [L[0], 1, L[1]] : [L[0], L[1], 1], [Z, ne, ee] = i ? [1, W[1], W[0]] : [W[1], 1, W[0]], se = E * P, te = Ae([A, E, P], I.dtype), ie = te.values, ae = n.blockSize;
for (let de = 0; de < A; de++)
for (let me = 0; me < E; me += ae)
for (let ke = 0; ke < P; ke += ae)
for (let Ie = 0; Ie < R; Ie += ae) {
let Re = Math.min(me + ae, E), Pe = Math.min(ke + ae, P), Xe = Math.min(Ie + ae, R);
for (let Je = me; Je < Re; Je++)
for (let Ye = ke; Ye < Pe; Ye++) {
let tt = 0;
for (let Ce = Ie; Ce < Xe; Ce++) {
let ut = Math.min(de, g - 1) * j, ot = Math.min(de, b - 1) * ee, Jt = D[ut + Je * Y + Ce * X], Nt = T[Ce * Z + Ye * ne + ot];
tt += Jt * Nt;
}
ie[de * se + (Je * P + Ye)] += tt;
}
}
return n.disposeIntermediateTensorInfo(I), n.disposeIntermediateTensorInfo($), n.makeTensorInfo(v, te.dtype, te.values);
}
var JG = { kernelName: Na, backendName: "cpu", kernelFunc: KC };
function eH(e) {
let { inputs: t, backend: n, attrs: s } = e, { a: r, b: a, bias: o, preluActivationWeights: i } = t, { transposeA: u, transposeB: l, activation: c, leakyreluAlpha: p } = s, d, h, f, m = [];
d = KC({ inputs: { a: r, b: a }, attrs: { transposeA: u, transposeB: l }, backend: n }), o && (h = oi({ inputs: { a: d, b: o }, backend: n }), m.push(d), d = h), c && (f = Wd(n, d, c, i, p), m.push(d), d = f);
for (let b of m)
n.disposeIntermediateTensorInfo(b);
return d;
}
var tH = { kernelName: oa, backendName: "cpu", kernelFunc: eH };
var nH = st(ul, (e) => Math.acos(e));
var sH = { kernelName: ul, backendName: "cpu", kernelFunc: nH };
var rH = st(ll, (e) => Math.acosh(e));
var aH = { kernelName: ll, backendName: "cpu", kernelFunc: rH };
function oH(e) {
let { inputs: t, backend: n } = e, s = t;
be(t, "addN");
let r = s.map((i) => n.data.get(i.dataId).values), a = Ae(s[0].shape, s[0].dtype), o = a.values;
for (let i = 0; i < s.length; i++) {
let u = r[i];
for (let l = 0; l < o.length; l++)
o[l] += u[l];
}
return n.makeTensorInfo(a.shape, a.dtype, a.values);
}
var iH = { kernelName: Sa, backendName: "cpu", kernelFunc: oH };
function uH(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, keepDims: o } = s;
be(r, "all");
let i = w.parseAxisParam(a, r.shape), u = i, l = C.getAxesPermutation(u, r.shape.length), c = r;
l != null && (c = wn({ inputs: { x: r }, backend: n, attrs: { perm: l } }), u = C.getInnerMostAxes(u.length, r.shape.length)), C.assertAxesAreInnerMostDims("all", u, c.shape.length);
let [p, d] = C.computeOutAndReduceShapes(c.shape, u), h = w.sizeFromShape(d), f = w.makeZerosTypedArray(w.sizeFromShape(p), c.dtype), m = n.data.get(c.dataId).values;
for (let b = 0; b < f.length; ++b) {
let y = b * h, v = m[y];
for (let x = 0; x < h; ++x) {
let k = m[y + x];
v = v && k;
}
f[b] = v;
}
l != null && n.disposeIntermediateTensorInfo(c);
let g = n.makeTensorInfo(p, c.dtype, f);
if (o) {
let b = C.expandShapeToKeepDim(p, i), y = pt({ inputs: { x: g }, backend: n, attrs: { shape: b } });
return n.disposeIntermediateTensorInfo(g), y;
}
return g;
}
var lH = { kernelName: cl, backendName: "cpu", kernelFunc: uH };
function cH(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, keepDims: o } = s;
be(r, "any");
let i = w.parseAxisParam(a, r.shape), u = i, l = C.getAxesPermutation(u, r.shape.length), c = r;
l != null && (c = wn({ inputs: { x: r }, backend: n, attrs: { perm: l } }), u = C.getInnerMostAxes(u.length, r.shape.length)), C.assertAxesAreInnerMostDims("any", u, c.shape.length);
let [p, d] = C.computeOutAndReduceShapes(c.shape, u), h = w.sizeFromShape(d), f = w.makeZerosTypedArray(w.sizeFromShape(p), c.dtype), m = n.data.get(c.dataId).values;
for (let b = 0; b < f.length; ++b) {
let y = b * h, v = m[y];
for (let x = 0; x < h; ++x) {
let k = m[y + x];
v = v || k;
}
f[b] = v;
}
l != null && n.disposeIntermediateTensorInfo(c);
let g = n.makeTensorInfo(p, c.dtype, f);
if (o) {
let b = C.expandShapeToKeepDim(p, i), y = pt({ inputs: { x: g }, backend: n, attrs: { shape: b } });
return n.disposeIntermediateTensorInfo(g), y;
}
return g;
}
var dH = { kernelName: dl, backendName: "cpu", kernelFunc: cH };
function pH(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a } = s;
be(r, "argMax");
let o = w.parseAxisParam(a, r.shape), i = C.getAxesPermutation(o, r.shape.length), u = r, l = [];
i != null && (u = wn({ inputs: { x: r }, backend: n, attrs: { perm: i } }), l.push(u), o = C.getInnerMostAxes(o.length, u.shape.length)), o = [o[0]], C.assertAxesAreInnerMostDims("argMax", o, u.shape.length);
let [c, p] = C.computeOutAndReduceShapes(u.shape, o), d = w.sizeFromShape(c), h = w.makeZerosTypedArray(d, "int32"), f = w.sizeFromShape(p), m = n.data.get(u.dataId).values;
for (let g = 0; g < h.length; ++g) {
let b = g * f, y = m[b], v = 0;
for (let x = 0; x < f; ++x) {
let k = m[b + x];
k > y && (y = k, v = x);
}
h[g] = v;
}
return l.forEach((g) => n.disposeIntermediateTensorInfo(g)), n.makeTensorInfo(c, "int32", h);
}
var hH = { kernelName: Ia, backendName: "cpu", kernelFunc: pH };
function fH(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a } = s;
be(r, "argMin");
let o = w.parseAxisParam(a, r.shape), i = C.getAxesPermutation(o, r.shape.length), u = r, l = [];
i != null && (u = wn({ inputs: { x: r }, backend: n, attrs: { perm: i } }), l.push(u), o = C.getInnerMostAxes(o.length, u.shape.length)), o = [o[0]], C.assertAxesAreInnerMostDims("argMin", o, u.shape.length);
let [c, p] = C.computeOutAndReduceShapes(u.shape, o), d = w.sizeFromShape(c), h = w.makeZerosTypedArray(d, "int32"), f = w.sizeFromShape(p), m = n.data.get(u.dataId).values;
for (let g = 0; g < h.length; ++g) {
let b = g * f, y = m[b], v = 0;
for (let x = 0; x < f; ++x) {
let k = m[b + x];
k < y && (y = k, v = x);
}
h[g] = v;
}
return l.forEach((g) => n.disposeIntermediateTensorInfo(g)), n.makeTensorInfo(c, "int32", h);
}
var mH = { kernelName: pl, backendName: "cpu", kernelFunc: fH };
var gH = st(hl, (e) => Math.asin(e));
var bH = { kernelName: hl, backendName: "cpu", kernelFunc: gH };
var yH = st(fl, (e) => Math.asinh(e));
var vH = { kernelName: fl, backendName: "cpu", kernelFunc: yH };
var xH = st(ml, (e) => Math.atan(e));
var wH = { kernelName: ml, backendName: "cpu", kernelFunc: xH };
var kH = At((e, t) => Math.atan2(e, t));
var SH = Gt(bl, kH);
var IH = { kernelName: bl, backendName: "cpu", kernelFunc: SH };
var CH = st(gl, (e) => Math.atanh(e));
var NH = { kernelName: gl, backendName: "cpu", kernelFunc: CH };
function vv(e, t, n, s, r, a) {
let o = r.strideHeight, i = r.strideWidth, u = r.dilationHeight, l = r.dilationWidth, c = r.effectiveFilterHeight, p = r.effectiveFilterWidth, d = r.padInfo.top, h = r.padInfo.left, f = a === "max" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, m = Ae(r.outShape, n), g = m.values, b = r.outShape[1] * r.outShape[2] * r.outShape[3], y = r.outShape[2] * r.outShape[3], v = r.outShape[3];
for (let x = 0; x < r.batchSize; ++x) {
let k = x * b, I = x * s[0];
for (let $ = 0; $ < r.inChannels; ++$)
for (let R = 0; R < r.outHeight; ++R) {
let E = R * o - d, P = Math.max(0, E), A = Math.min(r.inHeight, c + E), D = k + R * y;
for (let T = 0; T < r.outWidth; ++T) {
let L = T * i - h, W = Math.max(0, L), j = Math.min(r.inWidth, p + L), Y = f, X = 0, Z = 0;
for (let ee = P; ee < A; ee += u) {
let se = I + ee * s[1];
for (let te = W; te < j; te += l) {
let ie = se + te * s[2], ae = e[ie + $];
a === "max" && ae > Y ? Y = ae : a === "avg" && (X += ae, Z++);
}
if (isNaN(Y))
break;
}
let ne = D + T * v + $;
g[ne] = a === "avg" ? X / Z : Y;
}
}
}
return m;
}
function XC(e, t, n, s, r = false, a = false) {
let o = Ae(s.outShape, "int32"), i = s.strideHeight, u = s.strideWidth, l = s.dilationHeight, c = s.dilationWidth, p = s.effectiveFilterHeight, d = s.effectiveFilterWidth, h = s.padInfo.top, f = s.padInfo.left, m = Ae(t, n, e);
for (let g = 0; g < s.batchSize; ++g)
for (let b = 0; b < s.inChannels; ++b)
for (let y = 0; y < s.outHeight; ++y) {
let v = y * i - h, x = v;
for (; x < 0; )
x += l;
let k = Math.min(s.inHeight, p + v);
for (let I = 0; I < s.outWidth; ++I) {
let $ = I * u - f, R = $;
for (; R < 0; )
R += c;
let E = Math.min(s.inWidth, d + $), P = Number.NEGATIVE_INFINITY, A = -1;
for (let D = x; D < k; D += l) {
let T = D - v;
for (let L = R; L < E; L += c) {
let W = L - $, j = m.get(g, D, L, b);
j > P && (P = j, r ? A = a ? ((g * s.inHeight + D) * s.inWidth + L) * s.inChannels + b : (D * s.inWidth + L) * s.inChannels + b : A = T * d + W);
}
}
o.set(A, g, y, I, b);
}
}
return o;
}
function YC(e, t, n, s, r, a) {
let o = r.strideDepth, i = r.strideHeight, u = r.strideWidth, l = r.dilationDepth, c = r.dilationHeight, p = r.dilationWidth, d = r.effectiveFilterDepth, h = r.effectiveFilterHeight, f = r.effectiveFilterWidth, m = r.padInfo.front, g = r.padInfo.top, b = r.padInfo.left, y = a === "max" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, v = Ae(r.outShape, n), x = v.values, k = r.outShape[1] * r.outShape[2] * r.outShape[3] * r.outShape[4], I = r.outShape[2] * r.outShape[3] * r.outShape[4], $ = r.outShape[3] * r.outShape[4], R = r.outShape[4];
for (let E = 0; E < r.batchSize; ++E) {
let P = E * k, A = E * s[0];
for (let D = 0; D < r.inChannels; ++D)
for (let T = 0; T < r.outDepth; ++T) {
let L = T * o - m, W = L;
for (; W < 0; )
W += l;
let j = Math.min(r.inDepth, d + L), Y = P + T * I;
for (let X = 0; X < r.outHeight; ++X) {
let Z = X * i - g, ne = Z;
for (; ne < 0; )
ne += c;
let ee = Math.min(r.inHeight, h + Z), se = Y + X * $;
for (let te = 0; te < r.outWidth; ++te) {
let ie = te * u - b, ae = ie;
for (; ae < 0; )
ae += p;
let de = Math.min(r.inWidth, f + ie), me = se + te * R, ke = y, Ie = 0, Re = 0;
for (let Xe = W; Xe < j; Xe += l) {
let Je = A + Xe * s[1];
for (let Ye = ne; Ye < ee; Ye += c) {
let tt = Je + Ye * s[2];
for (let Ce = ae; Ce < de; Ce += p) {
let ut = tt + Ce * s[3], ot = e[ut + D];
if (a === "max" && ot > ke ? ke = ot : a === "avg" && (Ie += ot, Re++), isNaN(ke))
break;
}
if (isNaN(ke))
break;
}
if (isNaN(ke))
break;
}
let Pe = me + D;
x[Pe] = a === "avg" ? Ie / Re : ke;
}
}
}
}
return v;
}
function TH(e, t) {
let n = Ae(t.outShape, "int32"), s = t.strideDepth, r = t.strideHeight, a = t.strideWidth, o = t.dilationDepth, i = t.dilationHeight, u = t.dilationWidth, l = t.effectiveFilterDepth, c = t.effectiveFilterHeight, p = t.effectiveFilterWidth, d = t.padInfo.front, h = t.padInfo.top, f = t.padInfo.left;
for (let m = 0; m < t.batchSize; ++m)
for (let g = 0; g < t.inChannels; ++g)
for (let b = 0; b < t.outDepth; ++b) {
let y = b * s - d, v = y;
for (; v < 0; )
v += o;
let x = Math.min(t.inDepth, l + y);
for (let k = 0; k < t.outHeight; ++k) {
let I = k * r - h, $ = I;
for (; $ < 0; )
$ += i;
let R = Math.min(t.inHeight, c + I);
for (let E = 0; E < t.outWidth; ++E) {
let P = E * a - f, A = P;
for (; A < 0; )
A += u;
let D = Math.min(t.inWidth, p + P), T = Number.NEGATIVE_INFINITY, L = -1;
for (let W = v; W < x; W += o) {
let j = W - y;
for (let Y = $; Y < R; Y += i) {
let X = Y - I;
for (let Z = A; Z < D; Z += u) {
let ne = Z - P, ee = e.get(m, W, Y, Z, g);
ee >= T && (T = ee, L = j * c * p + X * c + ne);
}
}
}
n.set(L, m, b, k, E, g);
}
}
}
return n;
}
function $H(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t;
be(r, "avgPool");
let { filterSize: a, strides: o, pad: i, dimRoundingMode: u } = s, l = 1;
w.assert(C.eitherStridesOrDilationsAreOne(o, l), () => `Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${l}'`);
let c = C.computePool2DInfo(r.shape, a, o, l, i, u), p;
if (c.filterWidth === 1 && c.filterHeight === 1 && w.arraysEqual(c.inShape, c.outShape))
p = Os({ inputs: { x: r }, backend: n });
else {
let d = n.data.get(r.dataId).values, h = w.computeStrides(r.shape), f = vv(d, r.shape, r.dtype, h, c, "avg");
p = n.makeTensorInfo(c.outShape, r.dtype, f.values);
}
return p;
}
var _H = { kernelName: Ca, backendName: "cpu", kernelFunc: $H };
function AH(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { filterSize: a, strides: o, pad: i, dimRoundingMode: u, dataFormat: l } = s;
be(r, "avgPool3d");
let c = C.computePool3DInfo(r.shape, a, o, 1, i, u, l), p = n.data.get(r.dataId).values, d = YC(p, r.shape, r.dtype, w.computeStrides(r.shape), c, "avg");
return n.makeTensorInfo(d.shape, "float32", d.values);
}
var EH = { kernelName: tp, backendName: "cpu", kernelFunc: AH };
function RH(e) {
let { inputs: t, backend: n, attrs: s } = e, { dy: r, input: a } = t, { filterSize: o, strides: i, pad: u, dimRoundingMode: l } = s;
be([r, a], "avgPool3DGrad");
let c = C.computePool3DInfo(a.shape, o, i, 1, u, l), p = c.strideDepth, d = c.strideHeight, h = c.strideWidth, f = c.filterDepth, m = c.filterHeight, g = c.filterWidth, b = c.dilationDepth, y = c.dilationHeight, v = c.dilationWidth, x = c.effectiveFilterDepth, k = c.effectiveFilterHeight, I = c.effectiveFilterWidth, $ = x - 1 - c.padInfo.front, R = I - 1 - c.padInfo.left, E = k - 1 - c.padInfo.top, P = Ae(a.shape, "float32"), A = 1 / (f * m * g), D = n.bufferSync(r);
for (let T = 0; T < c.batchSize; ++T)
for (let L = 0; L < c.inChannels; ++L)
for (let W = 0; W < c.inDepth; ++W)
for (let j = 0; j < c.inHeight; ++j)
for (let Y = 0; Y < c.inWidth; ++Y) {
let X = W - $, Z = j - E, ne = Y - R, ee = 0;
for (let se = 0; se < x; se += b) {
let te = (X + se) / p;
if (!(te < 0 || te >= c.outDepth || Math.floor(te) !== te))
for (let ie = 0; ie < k; ie += y) {
let ae = (Z + ie) / d;
if (!(ae < 0 || ae >= c.outHeight || Math.floor(ae) !== ae))
for (let de = 0; de < I; de += v) {
let me = (ne + de) / h;
if (me < 0 || me >= c.outWidth || Math.floor(me) !== me)
continue;
ee += D.get(T, te, ae, me, L);
}
}
}
P.set(ee * A, T, W, j, Y, L);
}
return n.makeTensorInfo(P.shape, P.dtype, P.values);
}
var DH = { kernelName: yg, backendName: "cpu", kernelFunc: RH };
function FH(e) {
let { inputs: t, backend: n, attrs: s } = e, { dy: r, input: a } = t, o = a;
be([r, a], "avgPoolGrad");
let { filterSize: i, strides: u, pad: l } = s, c = C.computePool2DInfo(o.shape, i, u, 1, l), p = c.strideHeight, d = c.strideWidth, h = c.filterHeight, f = c.filterWidth, m = c.dilationHeight, g = c.dilationWidth, b = c.effectiveFilterHeight, y = c.effectiveFilterWidth, v = y - 1 - c.padInfo.left, x = b - 1 - c.padInfo.top, k = Ae(o.shape, "float32"), I = 1 / (h * f), $ = n.data.get(r.dataId).values, R = Ae(r.shape, "float32", $);
for (let E = 0; E < c.batchSize; ++E)
for (let P = 0; P < c.inChannels; ++P)
for (let A = 0; A < c.inHeight; ++A)
for (let D = 0; D < c.inWidth; ++D) {
let T = A - x, L = D - v, W = 0;
for (let j = 0; j < b; j += m) {
let Y = (T + j) / p;
if (!(Y < 0 || Y >= c.outHeight || Math.floor(Y) !== Y))
for (let X = 0; X < y; X += g) {
let Z = (L + X) / d;
if (Z < 0 || Z >= c.outWidth || Math.floor(Z) !== Z)
continue;
W += R.get(E, Y, Z, P);
}
}
k.set(W * I, E, A, D, P);
}
return n.makeTensorInfo(k.shape, k.dtype, k.values);
}
var OH = { kernelName: bg, backendName: "cpu", kernelFunc: FH };
function PH(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, scale: a, offset: o, mean: i, variance: u } = t;
w.assert(i.shape.length === u.shape.length, () => "Batch normalization gradient requires mean and variance to have equal ranks."), w.assert(o == null || i.shape.length === o.shape.length, () => "Batch normalization gradient requires mean and offset to have equal ranks."), w.assert(a == null || i.shape.length === a.shape.length, () => "Batch normalization gradient requires mean and scale to have equal ranks."), be([r, i, u, a, o], "batchNorm");
let { varianceEpsilon: l } = s;
l == null && (l = 1e-3);
let c = n.data.get(r.dataId).values, p = n.data.get(i.dataId).values, d = n.data.get(u.dataId).values, h = a ? n.data.get(a.dataId).values : new Float32Array([1]), f = o ? n.data.get(o.dataId).values : new Float32Array([0]), m = new Float32Array(c.length), g = f.length, b = h.length, y = d.length, v = p.length, x = 0, k = 0, I = 0, $ = 0;
for (let R = 0; R < c.length; ++R)
m[R] = f[x++] + (c[R] - p[k++]) * h[I++] / Math.sqrt(d[$++] + l), x >= g && (x = 0), k >= v && (k = 0), I >= b && (I = 0), $ >= y && ($ = 0);
return n.makeTensorInfo(r.shape, r.dtype, m);
}
var zH = { kernelName: Ba, backendName: "cpu", kernelFunc: PH };
function LH(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { blockShape: a, crops: o } = s;
be([r], "batchToSpaceND");
let i = a.reduce((b, y) => b * y), u = C.getReshaped(r.shape, a, i), l = C.getPermuted(u.length, a.length), c = C.getReshapedPermuted(r.shape, a, i), p = C.getSliceBeginCoords(o, a.length), d = C.getSliceSize(c, o, a.length), h = pt({ inputs: { x: r }, backend: n, attrs: { shape: u } }), f = wn({ inputs: { x: h }, backend: n, attrs: { perm: l } }), m = pt({ inputs: { x: f }, backend: n, attrs: { shape: c } }), g = ba({ inputs: { x: m }, backend: n, attrs: { begin: p, size: d } });
return n.disposeIntermediateTensorInfo(h), n.disposeIntermediateTensorInfo(f), n.disposeIntermediateTensorInfo(m), g;
}
var MH = { kernelName: pi, backendName: "cpu", kernelFunc: LH };
function BH(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, weights: a } = t, { size: o } = s, i = n.data.get(r.dataId).values, u = n.data.get(a.dataId).values, l = pv(i, u, a.dtype, a.shape, o);
return n.makeTensorInfo([o], a.dtype, l);
}
var VH = { kernelName: vg, backendName: "cpu", kernelFunc: BH };
function WH(e) {
let { inputs: t, backend: n } = e, { s0: s, s1: r } = t, a = n.data.get(s.dataId).values, o = n.data.get(r.dataId).values, i = C.assertAndGetBroadcastShape(Array.from(a), Array.from(o));
return n.makeTensorInfo([i.length], "int32", Int32Array.from(i));
}
var UH = { kernelName: xg, backendName: "cpu", kernelFunc: WH };
var GH = st(Nr, (e, t) => {
let n = t;
return e > n.clipValueMax ? n.clipValueMax : e < n.clipValueMin ? n.clipValueMin : e;
});
var HH = { kernelName: Nr, backendName: "cpu", kernelFunc: GH };
var qH = (e) => {
let { x: t } = e.inputs, n = e.backend, s = new Float32Array(w.sizeFromShape(t.shape)), r = n.data.get(t.dataId), a = r.complexTensorInfos.real, o = r.complexTensorInfos.imag, i = n.data.get(a.dataId).values, u = n.data.get(o.dataId).values;
for (let l = 0; l < i.length; l++) {
let c = i[l], p = u[l];
s[l] = Math.hypot(c, p);
}
return n.makeOutput(s, t.shape, "float32");
};
var jH = { kernelName: sp, backendName: "cpu", kernelFunc: qH };
function ii(e) {
let { inputs: t, backend: n } = e, { input: s } = t, r = n.data.get(s.dataId).complexTensorInfos.imag, a = n.data.get(r.dataId).values;
return n.makeTensorInfo(r.shape, r.dtype, a);
}
var KH = { kernelName: ip, backendName: "cpu", kernelFunc: ii };
function ui(e) {
let { inputs: t, backend: n, attrs: s } = e, { axis: r } = s, a = w.parseAxisParam(r, t[0].shape)[0], o = C.computeOutShape(t.map((m) => m.shape), a);
if (w.sizeFromShape(o) === 0)
return n.makeTensorInfo(o, t[0].dtype, []);
let i = t.filter((m) => w.sizeFromShape(m.shape) > 0);
if (i.length === 1)
return Os({ inputs: { x: i[0] }, backend: n });
let u = i.map((m) => m.shape);
if (C.assertParamsConsistent(u, a), i[0].dtype === "complex64") {
let m = i.map((x) => ga({ inputs: { input: x }, backend: n })), g = i.map((x) => ii({ inputs: { input: x }, backend: n })), b = ui({ inputs: m, backend: n, attrs: { axis: a } }), y = ui({ inputs: g, backend: n, attrs: { axis: a } }), v = En({ inputs: { real: b, imag: y }, backend: n });
return m.forEach((x) => n.disposeIntermediateTensorInfo(x)), g.forEach((x) => n.disposeIntermediateTensorInfo(x)), n.disposeIntermediateTensorInfo(b), n.disposeIntermediateTensorInfo(y), v;
}
let l = i.map((m) => {
let g = w.sizeFromShape(m.shape.slice(a));
return pt({ inputs: { x: m }, backend: n, attrs: { shape: [-1, g] } });
}), c = l.map((m) => ({ vals: n.data.get(m.dataId).values, shape: m.shape }));
o = C.computeOutShape(l.map((m) => m.shape), 1);
let p = l[0].shape[0] === 1, d = hv(c, o, t[0].dtype, p), h = C.computeOutShape(i.map((m) => m.shape), a), f = n.makeTensorInfo(h, t[0].dtype, d);
return l.forEach((m) => n.disposeIntermediateTensorInfo(m)), f;
}
var XH = { kernelName: hi, backendName: "cpu", kernelFunc: ui };
function QC(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, filter: a } = t, { strides: o, pad: i, dataFormat: u, dilations: l, dimRoundingMode: c } = s;
be([r, a], "conv2d");
let p = C.convertConv2DDataFormat(u), d = C.computeConv2DInfo(r.shape, a.shape, o, l, i, c, false, p), h = d.filterHeight, f = d.filterWidth, m = d.dilationHeight, g = d.dilationWidth, b = d.padInfo.left, y = d.padInfo.top, v = d.dataFormat === "channelsLast", x = new Vt(d.outShape, r.dtype), k = w.computeStrides(r.shape), I = w.computeStrides(a.shape), $ = k[0], R = v ? k[1] : k[2], E = v ? k[2] : 1, P = v ? 1 : k[1], A = x.strides[0], D = v ? x.strides[1] : x.strides[2], T = v ? x.strides[2] : 1, L = v ? 1 : x.strides[1], W = n.data.get(r.dataId).values, j = n.data.get(a.dataId).values, Y = x.values;
for (let X = 0; X < d.batchSize; ++X) {
let Z = X * $, ne = X * A;
for (let ee = 0; ee < d.outHeight; ++ee) {
let se = ne + ee * D, te = ee * d.strideHeight - y;
for (let ie = 0; ie < h; ++ie) {
let ae = te + ie * m;
if (ae < 0 || ae >= d.inHeight)
continue;
let de = ie * I[0], me = Z + ae * R;
for (let ke = 0; ke < d.outWidth; ++ke) {
let Ie = se + ke * T, Re = ke * d.strideWidth - b;
for (let Pe = 0; Pe < f; ++Pe) {
let Xe = Re + Pe * g;
if (Xe < 0 || Xe >= d.inWidth)
continue;
let Je = de + Pe * I[1], Ye = me + Xe * E, tt = Je;
for (let Ce = 0; Ce < d.inChannels; ++Ce) {
let ut = W[Ye + Ce * P];
for (let ot = 0; ot < d.outChannels; ++ot)
Y[Ie + ot * L] += ut * j[tt + ot];
tt += d.outChannels;
}
}
}
}
}
}
return n.makeTensorInfo(x.shape, x.dtype, Y);
}
var YH = { kernelName: _a, backendName: "cpu", kernelFunc: QC };
function QH(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, dy: a } = t, { strides: o, pad: i, dataFormat: u, dimRoundingMode: l, filterShape: c } = s;
be([r, a], "conv2dBackpropFilter");
let p = C.convertConv2DDataFormat(u), d = C.computeConv2DInfo(r.shape, c, o, 1, i, l, false, p), { strideHeight: h, strideWidth: f, filterHeight: m, filterWidth: g } = d, b = d.dataFormat === "channelsLast", y = new Vt(d.filterShape, "float32"), v = d.padInfo.left, x = d.padInfo.top, k = n.data.get(r.dataId).values, I = n.data.get(a.dataId).values, $ = new Vt(r.shape, r.dtype, k), R = new Vt(a.shape, a.dtype, I);
for (let E = 0; E < m; ++E) {
let P = Math.max(0, Math.ceil((x - E) / h)), A = Math.min(d.outHeight, (d.inHeight + x - E) / h);
for (let D = 0; D < g; ++D) {
let T = Math.max(0, Math.ceil((v - D) / f)), L = Math.min(d.outWidth, (d.inWidth + v - D) / f);
for (let W = 0; W < d.inChannels; ++W)
for (let j = 0; j < d.outChannels; ++j) {
let Y = 0;
for (let X = 0; X < d.batchSize; ++X)
for (let Z = P; Z < A; ++Z) {
let ne = E + Z * h - x;
for (let ee = T; ee < L; ++ee) {
let se = D + ee * f - v;
b ? Y += $.get(X, ne, se, W) * R.get(X, Z, ee, j) : Y += $.get(X, W, ne, se) * R.get(X, j, Z, ee);
}
}
y.set(Y, E, D, W, j);
}
}
}
return n.makeTensorInfo(y.shape, y.dtype, y.values);
}
var ZH = { kernelName: wg, backendName: "cpu", kernelFunc: QH };
function JH(e) {
let { inputs: t, backend: n, attrs: s } = e, { dy: r, filter: a } = t, { inputShape: o, strides: i, pad: u, dataFormat: l, dimRoundingMode: c } = s;
be([r, a], "conv2dBackpropInput");
let p = w.computeStrides(a.shape), d = w.computeStrides(r.shape), h = C.convertConv2DDataFormat(l), f = C.computeConv2DInfo(o, a.shape, i, 1, u, c, false, h), m = new Vt(f.inShape, "float32"), g = m.values, b = n.data.get(r.dataId).values, y = n.data.get(a.dataId).values, [v, x, k] = p, { batchSize: I, filterHeight: $, filterWidth: R, inChannels: E, inHeight: P, inWidth: A, outChannels: D, outHeight: T, outWidth: L, strideHeight: W, strideWidth: j } = f;
h = f.dataFormat;
let Y = $ - 1 - f.padInfo.top, X = R - 1 - f.padInfo.left, Z = h === "channelsLast", ne = m.strides[0], ee = Z ? m.strides[1] : m.strides[2], se = Z ? m.strides[2] : 1, te = Z ? 1 : m.strides[1], ie = d[0], ae = Z ? d[1] : d[2], de = Z ? d[2] : 1, me = Z ? 1 : d[1];
for (let ke = 0; ke < I; ++ke)
for (let Ie = 0; Ie < E; ++Ie)
for (let Re = 0; Re < P; ++Re) {
let Pe = Re - Y, Xe = Math.max(0, Math.ceil(Pe / W)), Je = Math.min(T, ($ + Pe) / W);
for (let Ye = 0; Ye < A; ++Ye) {
let tt = Ye - X, Ce = Math.max(0, Math.ceil(tt / j)), ut = Math.min(L, (R + tt) / j), ot = 0;
for (let Nt = Xe; Nt < Je; ++Nt) {
let In = Nt * W - Pe;
for (let Et = Ce; Et < ut; ++Et) {
let en = Et * j - tt, Cn = ie * ke + ae * Nt + de * Et, Nn = v * ($ - 1 - In) + x * (R - 1 - en) + k * Ie;
for (let Yt = 0; Yt < D; ++Yt) {
let Dn = b[Cn + me * Yt], tn = y[Nn + Yt];
ot += Dn * tn;
}
}
}
let Jt = ne * ke + ee * Re + se * Ye + te * Ie;
g[Jt] = ot;
}
}
return n.makeTensorInfo(m.shape, m.dtype, m.values);
}
var eq = { kernelName: Aa, backendName: "cpu", kernelFunc: JH };
function tq(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, filter: a } = t, { strides: o, pad: i, dilations: u } = s;
be([r, a], "conv3d");
let l = C.computeConv3DInfo(r.shape, a.shape, o, u, i), { filterDepth: c, filterHeight: p, filterWidth: d, dilationDepth: h, dilationHeight: f, dilationWidth: m, padInfo: g } = l, b = g.front, y = g.left, v = g.top, x = new Vt(l.outShape, r.dtype), k = n.data.get(r.dataId).values, I = n.data.get(a.dataId).values, $ = x.values, R = w.computeStrides(r.shape), E = w.computeStrides(a.shape);
for (let P = 0; P < l.batchSize; ++P) {
let A = P * R[0], D = P * x.strides[0];
for (let T = 0; T < l.outDepth; ++T) {
let L = D + T * x.strides[1], W = T * l.strideDepth - b;
for (let j = 0; j < c; ++j) {
let Y = W + j * h;
if (Y < 0 || Y >= l.inDepth)
continue;
let X = j * E[0], Z = A + Y * R[1];
for (let ne = 0; ne < l.outHeight; ++ne) {
let ee = L + ne * x.strides[2], se = ne * l.strideHeight - v;
for (let te = 0; te < p; ++te) {
let ie = se + te * f;
if (ie < 0 || ie >= l.inHeight)
continue;
let ae = X + te * E[1], de = Z + ie * R[2];
for (let me = 0; me < l.outWidth; ++me) {
let ke = ee + me * l.outChannels, Ie = me * l.strideWidth - y;
for (let Re = 0; Re < d; ++Re) {
let Pe = Ie + Re * m;
if (Pe < 0 || Pe >= l.inWidth)
continue;
let Xe = ae + Re * E[2], Je = de + Pe * l.inChannels, Ye = Xe;
for (let tt = 0; tt < l.inChannels; ++tt) {
let Ce = k[Je + tt];
for (let ut = 0; ut < l.outChannels; ++ut)
$[ke + ut] += Ce * I[Ye + ut];
Ye += l.outChannels;
}
}
}
}
}
}
}
}
return n.makeTensorInfo(x.shape, x.dtype, x.values);
}
var nq = { kernelName: rp, backendName: "cpu", kernelFunc: tq };
function sq(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, dy: a } = t, { strides: o, pad: i, filterShape: u } = s;
be([r, a], "conv3dBackpropFilterV2");
let l = w.computeStrides(r.shape), c = w.computeStrides(a.shape), p = C.computeConv3DInfo(r.shape, u, o, 1, i), d = p.strideDepth, h = p.strideHeight, f = p.strideWidth, m = p.filterDepth, g = p.filterHeight, b = p.filterWidth, y = new Vt(p.filterShape, "float32"), v = y.values, [x, k, I, $] = y.strides, R = n.data.get(a.dataId).values, [E, P, A, D] = c, T = n.data.get(r.dataId).values, [L, W, j, Y] = l, X = p.padInfo.front, Z = p.padInfo.left, ne = p.padInfo.top;
for (let ee = 0; ee < m; ++ee) {
let se = Math.max(0, Math.ceil((X - ee) / d)), te = Math.min(p.outDepth, (p.inDepth + X - ee) / d), ie = ee * x;
for (let ae = 0; ae < g; ++ae) {
let de = Math.max(0, Math.ceil((ne - ae) / h)), me = Math.min(p.outHeight, (p.inHeight + ne - ae) / h), ke = ae * k + ie;
for (let Ie = 0; Ie < b; ++Ie) {
let Re = Math.max(0, Math.ceil((Z - Ie) / f)), Pe = Math.min(p.outWidth, (p.inWidth + Z - Ie) / f), Xe = Ie * I + ke;
for (let Je = 0; Je < p.inChannels; ++Je) {
let Ye = Je * $ + Xe;
for (let tt = 0; tt < p.outChannels; ++tt) {
let Ce = 0;
for (let ut = 0; ut < p.batchSize; ++ut) {
let ot = ut * L, Jt = ut * E;
for (let Nt = se; Nt < te; ++Nt) {
let Et = (ee + Nt * d - X) * W + ot, en = Nt * P + Jt;
for (let Cn = de; Cn < me; ++Cn) {
let Yt = (ae + Cn * h - ne) * j + Et, Dn = Cn * A + en;
for (let tn = Re; tn < Pe; ++tn) {
let Ls = (Ie + tn * f - Z) * Y + Yt, Co = tn * D + Dn;
Ce += T[Ls + Je] * R[Co + tt];
}
}
}
}
v[Ye + tt] = Ce;
}
}
}
}
}
return n.makeTensorInfo(y.shape, y.dtype, y.values);
}
var rq = { kernelName: kg, backendName: "cpu", kernelFunc: sq };
function aq(e) {
let { inputs: t, backend: n, attrs: s } = e, { dy: r, filter: a } = t, { pad: o, strides: i, inputShape: u } = s;
be([r], "conv3dBackpropInputV2");
let l = w.computeStrides(r.shape), c = w.computeStrides(a.shape), p = C.computeConv3DInfo(u, a.shape, i, 1, o), d = new Vt(p.inShape, "float32"), h = d.values, [f, m, g, b] = d.strides, y = n.data.get(r.dataId).values, [v, x, k, I] = l, $ = n.data.get(a.dataId).values, [R, E, P, A] = c, { batchSize: D, filterDepth: T, filterHeight: L, filterWidth: W, inChannels: j, inDepth: Y, inHeight: X, inWidth: Z, outChannels: ne, outDepth: ee, outHeight: se, outWidth: te, strideDepth: ie, strideHeight: ae, strideWidth: de } = p, me = T - 1 - p.padInfo.front, ke = L - 1 - p.padInfo.top, Ie = W - 1 - p.padInfo.left;
for (let Re = 0; Re < D; ++Re)
for (let Pe = 0; Pe < j; ++Pe)
for (let Xe = 0; Xe < Y; ++Xe) {
let Je = Xe - me, Ye = Math.max(0, Math.ceil(Je / ie)), tt = Math.min(ee, (T + Je) / ie);
for (let Ce = 0; Ce < X; ++Ce) {
let ut = Ce - ke, ot = Math.max(0, Math.ceil(ut / ae)), Jt = Math.min(se, (L + ut) / ae);
for (let Nt = 0; Nt < Z; ++Nt) {
let In = Nt - Ie, Et = Math.max(0, Math.ceil(In / de)), en = Math.min(te, (W + In) / de), Cn = 0;
for (let Nn = Ye; Nn < tt; ++Nn) {
let Yt = Nn * ie - Je;
for (let Dn = ot; Dn < Jt; ++Dn) {
let tn = Dn * ae - ut;
for (let zs = Et; zs < en; ++zs) {
let Ls = zs * de - In, Co = v * Re + x * Nn + k * Dn + I * zs, Zs = R * (T - 1 - Yt) + E * (L - 1 - tn) + P * (W - 1 - Ls) + A * Pe;
for (let Ms = 0; Ms < ne; ++Ms) {
let gu = y[Co + Ms], No = $[Zs + Ms];
Cn += gu * No;
}
}
}
}
h[f * Re + m * Xe + g * Ce + b * Nt + Pe] = Cn;
}
}
}
return n.makeTensorInfo(d.shape, d.dtype, d.values);
}
var oq = { kernelName: Sg, backendName: "cpu", kernelFunc: aq };
var iq = st(Ea, (e) => Math.cos(e));
var uq = { kernelName: Ea, backendName: "cpu", kernelFunc: iq };
var lq = st(Ra, (e) => Math.cosh(e));
var cq = { kernelName: Ra, backendName: "cpu", kernelFunc: lq };
function dq(e) {
let { inputs: t, backend: n, attrs: s } = e, { image: r, boxes: a, boxInd: o } = t, { cropSize: i, method: u, extrapolationValue: l } = s, [c, p, d, h] = r.shape, f = a.shape[0], [m, g] = i, b = Ae([f, m, g, h], "float32"), y = n.data.get(a.dataId).values, v = n.data.get(o.dataId).values, x = n.data.get(r.dataId).values, k = w.computeStrides(r.shape), I = w.computeStrides(b.shape);
for (let $ = 0; $ < f; $++) {
let R = $ * 4, E = y[R], P = y[R + 1], A = y[R + 2], D = y[R + 3], T = v[$];
if (T >= c)
continue;
let L = m > 1 ? (A - E) * (p - 1) / (m - 1) : 0, W = g > 1 ? (D - P) * (d - 1) / (g - 1) : 0;
for (let j = 0; j < m; j++) {
let Y = m > 1 ? E * (p - 1) + j * L : 0.5 * (E + A) * (p - 1);
if (Y < 0 || Y > p - 1) {
for (let X = 0; X < g; X++)
for (let Z = 0; Z < h; Z++) {
let ne = Z + X * I[2] + j * I[1] + $ * I[0];
b.values[ne] = l;
}
continue;
}
if (u === "bilinear") {
let X = Math.floor(Y), Z = Math.ceil(Y), ne = Y - X;
for (let ee = 0; ee < g; ee++) {
let se = g > 1 ? P * (d - 1) + ee * W : 0.5 * (P + D) * (d - 1);
if (se < 0 || se > d - 1) {
for (let de = 0; de < h; de++) {
let me = de + ee * I[2] + j * I[1] + $ * I[0];
b.values[me] = l;
}
continue;
}
let te = Math.floor(se), ie = Math.ceil(se), ae = se - te;
for (let de = 0; de < h; de++) {
let me = de + te * k[2] + X * k[1] + T * k[0], ke = x[me];
me = de + ie * k[2] + X * k[1] + T * k[0];
let Ie = x[me];
me = de + te * k[2] + Z * k[1] + T * k[0];
let Re = x[me];
me = de + ie * k[2] + Z * k[1] + T * k[0];
let Pe = x[me], Xe = ke + (Ie - ke) * ae, Je = Re + (Pe - Re) * ae;
me = de + ee * I[2] + j * I[1] + $ * I[0], b.values[me] = Xe + (Je - Xe) * ne;
}
}
} else
for (let X = 0; X < g; ++X) {
let Z = g > 1 ? P * (d - 1) + X * W : 0.5 * (P + D) * (d - 1);
if (Z < 0 || Z > d - 1) {
for (let se = 0; se < h; se++) {
let te = se + X * I[2] + j * I[1] + $ * I[0];
b.values[te] = l;
}
continue;
}
let ne = Math.round(Z), ee = Math.round(Y);
for (let se = 0; se < h; se++) {
let te = se + ne * k[2] + ee * k[1] + T * k[0], ie = se + X * I[2] + j * I[1] + $ * I[0];
b.values[ie] = x[te];
}
}
}
}
return n.makeTensorInfo(b.shape, b.dtype, b.values);
}
var pq = { kernelName: mi, backendName: "cpu", kernelFunc: dq };
function hq(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, exclusive: o, reverse: i } = s;
be(r, "cumprod");
let u = C.getAxesPermutation([a], r.shape.length), l = r;
u != null && (l = wn({ inputs: { x: r }, backend: n, attrs: { perm: u } }));
let c = C.getInnerMostAxes(1, r.shape.length)[0];
if (c !== l.shape.length - 1)
throw new Error(`backend.cumprod in CPU expects an inner-most axis=${l.shape.length - 1} but got axis=${c}`);
let p = cn(l.dtype, "int32"), d = w.makeOnesTypedArray(w.sizeFromShape(l.shape), p), h = n.data.get(l.dataId).values, f = l.shape[l.shape.length - 1], m = i ? (b, y) => b + f - y - 1 : (b, y) => b + y;
for (let b = 0; b < h.length; b += f)
for (let y = 0; y < f; y++) {
let v = m(b, y);
if (y === 0)
d[v] = o ? 1 : h[v];
else {
let x = m(b, y - 1);
d[v] = o ? h[x] * d[x] : h[v] * d[x];
}
}
let g = n.makeTensorInfo(l.shape, p, d);
if (u != null) {
let b = C.getUndoAxesPermutation(u), y = wn({ inputs: { x: g }, backend: n, attrs: { perm: b } });
return n.disposeIntermediateTensorInfo(g), n.disposeIntermediateTensorInfo(l), y;
}
return g;
}
var fq = { kernelName: fi, backendName: "cpu", kernelFunc: hq };
function mq(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, exclusive: o, reverse: i } = s;
be(r, "cumsum");
let u = C.getAxesPermutation([a], r.shape.length), l = r;
u != null && (l = wn({ inputs: { x: r }, backend: n, attrs: { perm: u } }));
let c = C.getInnerMostAxes(1, r.shape.length)[0];
if (c !== l.shape.length - 1)
throw new Error(`backend.cumsum in CPU expects an inner-most axis=${l.shape.length - 1} but got axis=${c}`);
let p = cn(l.dtype, "int32"), d = w.makeZerosTypedArray(w.sizeFromShape(l.shape), p), h = n.data.get(l.dataId).values, f = l.shape[l.shape.length - 1], m = i ? (b, y) => b + f - y - 1 : (b, y) => b + y;
for (let b = 0; b < h.length; b += f)
for (let y = 0; y < f; y++) {
let v = m(b, y);
if (y === 0)
d[v] = o ? 0 : h[v];
else {
let x = m(b, y - 1);
d[v] = o ? h[x] + d[x] : h[v] + d[x];
}
}
let g = n.makeTensorInfo(l.shape, p, d);
if (u != null) {
let b = C.getUndoAxesPermutation(u), y = wn({ inputs: { x: g }, backend: n, attrs: { perm: b } });
return n.disposeIntermediateTensorInfo(g), n.disposeIntermediateTensorInfo(l), y;
}
return g;
}
var gq = { kernelName: Da, backendName: "cpu", kernelFunc: mq };
function bq(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, weights: a } = t, { size: o, binaryOutput: i } = s;
if (r.shape.length === 1) {
let u = n.data.get(r.dataId).values, l = n.data.get(a.dataId).values, c = pv(u, l, a.dtype, a.shape, o);
return n.makeTensorInfo([o], a.dtype, c);
} else if (r.shape.length === 2) {
let u = n.bufferSync(r), l = n.bufferSync(a), c = iC(u, l, o, i);
return n.makeTensorInfo(c.shape, a.dtype, c.values);
}
throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`);
}
var yq = { kernelName: Ig, backendName: "cpu", kernelFunc: bq };
function vq(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { blockSize: a, dataFormat: o } = s;
w.assert(o === "NHWC", () => `Only NHWC dataFormat supported on CPU for depthToSpace. Got ${o}`);
let i = r.shape[0], u = r.shape[1], l = r.shape[2], c = r.shape[3], p = u * a, d = l * a, h = c / (a * a), f = n.data.get(r.dataId).values, m = new Float32Array(i * p * d * h), g = 0;
for (let b = 0; b < i; ++b)
for (let y = 0; y < p; ++y) {
let v = Math.floor(y / a), x = y % a;
for (let k = 0; k < d; ++k) {
let I = Math.floor(k / a), $ = k % a, R = (x * a + $) * h;
for (let E = 0; E < h; ++E) {
let A = E + R + c * (I + l * (v + u * b));
m[g++] = f[A];
}
}
}
return n.makeTensorInfo([i, p, d, h], r.dtype, m);
}
var xq = { kernelName: gi, backendName: "cpu", kernelFunc: vq };
function ZC(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, filter: a } = t, { strides: o, pad: i, dilations: u, dimRoundingMode: l } = s;
be([r, a], "depthwiseConv2DNative");
let c = w.computeStrides(r.shape), p = w.computeStrides(a.shape), d = u;
d == null && (d = [1, 1]), w.assert(C.eitherStridesOrDilationsAreOne(o, d), () => `Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${d}'`);
let h = C.computeConv2DInfo(r.shape, a.shape, o, d, i, l, true), { filterHeight: f, filterWidth: m, dilationHeight: g, dilationWidth: b, padInfo: y } = h, v = y.left, x = y.top, k = h.outChannels / h.inChannels, I = new Vt(h.outShape, r.dtype), $ = n.data.get(r.dataId).values, R = n.data.get(a.dataId).values, E = I.values;
for (let P = 0; P < h.batchSize; ++P) {
let A = P * c[0], D = P * I.strides[0];
for (let T = 0; T < h.outHeight; ++T) {
let L = D + T * I.strides[1], W = T * h.strideHeight - x;
for (let j = 0; j < f; ++j) {
let Y = W + j * g;
if (Y < 0 || Y >= h.inHeight)
continue;
let X = j * p[0], Z = A + Y * c[1];
for (let ne = 0; ne < h.outWidth; ++ne) {
let ee = L + ne * I.strides[2], se = ne * h.strideWidth - v;
for (let te = 0; te < m; ++te) {
let ie = se + te * b;
if (ie < 0 || ie >= h.inWidth)
continue;
let ae = X + te * p[1], de = Z + ie * h.inChannels, me = ee, ke = ae;
for (let Ie = 0; Ie < h.inChannels; ++Ie) {
let Re = $[de + Ie];
for (let Pe = 0; Pe < k; ++Pe)
E[me + Pe] += Re * R[ke + Pe];
me += k, ke += k;
}
}
}
}
}
}
return n.makeTensorInfo(I.shape, I.dtype, I.values);
}
var wq = { kernelName: Fa, backendName: "cpu", kernelFunc: ZC };
function kq(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, dy: a } = t, { strides: o, dilations: i, pad: u, dimRoundingMode: l, filterShape: c } = s;
be([r, a], "depthwiseConv2dNativeBackpropFilter");
let p = C.computeConv2DInfo(r.shape, c, o, i, u, l, true), { strideHeight: d, strideWidth: h, filterHeight: f, filterWidth: m } = p, g = new Vt(p.filterShape, "float32"), b = p.padInfo.left, y = p.padInfo.top, v = p.outChannels / p.inChannels, x = n.data.get(r.dataId).values, k = new Vt(r.shape, r.dtype, x), I = n.data.get(a.dataId).values, $ = new Vt(a.shape, a.dtype, I);
for (let R = 0; R < f; ++R) {
let E = Math.max(0, Math.ceil((y - R) / d)), P = Math.min(p.outHeight, (p.inHeight + y - R) / d);
for (let A = 0; A < m; ++A) {
let D = Math.max(0, Math.ceil((b - A) / h)), T = Math.min(p.outWidth, (p.inWidth + b - A) / h);
for (let L = 0; L < p.outChannels; ++L) {
let W = Math.trunc(L / v), j = L % v, Y = 0;
for (let X = 0; X < p.batchSize; ++X)
for (let Z = E; Z < P; ++Z) {
let ne = R + Z * d - y;
for (let ee = D; ee < T; ++ee) {
let se = A + ee * h - b;
Y += k.get(X, ne, se, W) * $.get(X, Z, ee, L);
}
}
g.set(Y, R, A, W, j);
}
}
}
return n.makeTensorInfo(g.shape, g.dtype, g.values);
}
var Sq = { kernelName: Cg, backendName: "cpu", kernelFunc: kq };
function Iq(e) {
let { inputs: t, backend: n, attrs: s } = e, { dy: r, filter: a } = t, { strides: o, dilations: i, pad: u, dimRoundingMode: l, inputShape: c } = s;
be([r, a], "depthwiseConv2DNativeBackpropInput");
let p = w.computeStrides(r.shape), d = w.computeStrides(a.shape), h = C.computeConv2DInfo(c, a.shape, o, i, u, l, true), f = new Vt(h.inShape, "float32"), m = f.values, [g, b, y] = f.strides, v = n.data.get(r.dataId).values, [x, k, I] = p, $ = n.data.get(a.dataId).values, [R, E, P] = d, { batchSize: A, filterHeight: D, filterWidth: T, inChannels: L, inHeight: W, inWidth: j, outChannels: Y, outHeight: X, outWidth: Z, strideHeight: ne, strideWidth: ee } = h, se = D - 1 - h.padInfo.top, te = T - 1 - h.padInfo.left, ie = Y / L;
for (let ae = 0; ae < A; ++ae)
for (let de = 0; de < L; ++de)
for (let me = 0; me < W; ++me) {
let ke = me - se, Ie = Math.max(0, Math.ceil(ke / ne)), Re = Math.min(X, (D + ke) / ne);
for (let Pe = 0; Pe < j; ++Pe) {
let Xe = Pe - te, Je = Math.max(0, Math.ceil(Xe / ee)), Ye = Math.min(Z, (T + Xe) / ee), tt = 0;
for (let Ce = Ie; Ce < Re; ++Ce) {
let ut = Ce * ne - ke;
for (let ot = Je; ot < Ye; ++ot) {
let Jt = ot * ee - Xe, Nt = x * ae + k * Ce + I * ot, In = R * (D - 1 - ut) + E * (T - 1 - Jt) + P * de;
for (let Et = 0; Et < ie; ++Et) {
let en = de * ie + Et, Cn = v[Nt + en], Nn = $[In + Et];
tt += Cn * Nn;
}
}
}
m[g * ae + b * me + y * Pe + de] = tt;
}
}
return n.makeTensorInfo(f.shape, f.dtype, f.values);
}
var Cq = { kernelName: Ng, backendName: "cpu", kernelFunc: Iq };
function Nq(e) {
let { inputs: t, backend: n } = e, { x: s } = t, r = w.sizeFromShape(s.shape), a = n.data.get(s.dataId).values, o = Ae([r, r], s.dtype), i = o.values;
for (let l = 0; l < a.length; l++)
i[l * r + l] = a[l];
let u = [...s.shape, ...s.shape];
return n.makeTensorInfo(u, o.dtype, o.values);
}
var Tq = { kernelName: Tg, backendName: "cpu", kernelFunc: Nq };
var $q = { kernelName: ap, backendName: "cpu", kernelFunc: ({ inputs: e, backend: t, attrs: n }) => {
let { x: s, filter: r } = e, { strides: a, pad: o, dilations: i } = n, u = t, l = u.data.get(s.dataId).values, c = s.shape.length, p = u.data.get(r.dataId).values, d = r.shape.length, { batchSize: h, inHeight: f, inWidth: m, inChannels: g, outHeight: b, outWidth: y, padInfo: v, strideHeight: x, strideWidth: k, filterHeight: I, filterWidth: $, dilationHeight: R, dilationWidth: E, outShape: P } = C.computeDilation2DInfo(s.shape, r.shape, a, o, "NHWC", i), A = w.sizeFromShape(P), D = P.length, T = w.getArrayFromDType(s.dtype, A);
for (let W = 0; W < h; ++W)
for (let j = 0; j < b; ++j) {
let Y = j * x - v.top;
for (let X = 0; X < y; ++X) {
let Z = X * k - v.left;
for (let ne = 0; ne < g; ++ne) {
let ee = Number.MIN_SAFE_INTEGER;
for (let te = 0; te < I; ++te) {
let ie = Y + te * R;
if (ie >= 0 && ie < f)
for (let ae = 0; ae < $; ++ae) {
let de = Z + ae * E;
if (de >= 0 && de < m) {
let me = w.locToIndex([W, ie, de, ne], c, w.computeStrides(s.shape)), ke = w.locToIndex([te, ae, ne], d, w.computeStrides(r.shape)), Ie = l[me] + p[ke];
Ie > ee && (ee = Ie);
}
}
}
let se = w.locToIndex([W, j, X, ne], D, w.computeStrides(P));
T[se] = ee;
}
}
}
return { dataId: u.write(w.toTypedArray(T, s.dtype), P, s.dtype), shape: P, dtype: s.dtype };
} };
var _q = { kernelName: um, backendName: "cpu", kernelFunc: ({ inputs: e, backend: t, attrs: n }) => {
let { x: s, filter: r, dy: a } = e, { strides: o, pad: i, dilations: u } = n, l = t, c = w.toNestedArray(s.shape, l.data.get(s.dataId).values), p = w.toNestedArray(r.shape, l.data.get(r.dataId).values), { batchSize: d, inHeight: h, inWidth: f, inChannels: m, outHeight: g, outWidth: b, padInfo: y, strideHeight: v, strideWidth: x, filterHeight: k, filterWidth: I, dilationHeight: $, dilationWidth: R, outShape: E } = C.computeDilation2DInfo(s.shape, r.shape, o, i, "NHWC", u);
w.assert(a.rank === E.length, () => `Error in ${um}, dy must have the same rank as output ${E.length}, but got ${a.rank}`);
let P = w.toNestedArray(E, l.data.get(a.dataId).values), A = w.makeZerosNestedTypedArray(r.shape, r.dtype);
for (let T = 0; T < d; ++T)
for (let L = 0; L < g; ++L) {
let W = L * v - y.top;
for (let j = 0; j < b; ++j) {
let Y = j * x - y.left;
for (let X = 0; X < m; ++X) {
let Z = Number.MIN_SAFE_INTEGER, ne = 0, ee = 0;
for (let se = 0; se < k; ++se) {
let te = W + se * $;
if (te >= 0 && te < h)
for (let ie = 0; ie < I; ++ie) {
let ae = Y + ie * R;
if (ae >= 0 && ae < f) {
let de = c[T][te][ae][X] + p[se][ie][X];
de > Z && (Z = de, ne = se, ee = ie);
}
}
}
A[ne][ee][X] += P[T][L][j][X];
}
}
}
return { dataId: l.write(w.toTypedArray(A, s.dtype), r.shape, r.dtype), shape: r.shape, dtype: r.dtype };
} };
var Aq = { kernelName: im, backendName: "cpu", kernelFunc: ({ inputs: e, backend: t, attrs: n }) => {
let { x: s, filter: r, dy: a } = e, { strides: o, pad: i, dilations: u } = n, l = t, c = w.toNestedArray(s.shape, l.data.get(s.dataId).values), p = w.toNestedArray(r.shape, l.data.get(r.dataId).values), { batchSize: d, inHeight: h, inWidth: f, inChannels: m, outHeight: g, outWidth: b, padInfo: y, strideHeight: v, strideWidth: x, filterHeight: k, filterWidth: I, dilationHeight: $, dilationWidth: R, outShape: E } = C.computeDilation2DInfo(s.shape, r.shape, o, i, "NHWC", u);
w.assert(a.rank === E.length, () => `Error in ${im}, dy must have the same rank as output ${E.length}, but got ${a.rank}`);
let P = w.toNestedArray(E, l.data.get(a.dataId).values), A = w.makeZerosNestedTypedArray(s.shape, s.dtype);
for (let T = 0; T < d; ++T)
for (let L = 0; L < g; ++L) {
let W = L * v - y.top;
for (let j = 0; j < b; ++j) {
let Y = j * x - y.left;
for (let X = 0; X < m; ++X) {
let Z = Number.MIN_SAFE_INTEGER, ne = W < 0 ? 0 : W, ee = Y < 0 ? 0 : Y;
for (let se = 0; se < k; ++se) {
let te = W + se * $;
if (te >= 0 && te < h)
for (let ie = 0; ie < I; ++ie) {
let ae = Y + ie * R;
if (ae >= 0 && ae < f) {
let de = c[T][te][ae][X] + p[se][ie][X];
de > Z && (Z = de, ne = te, ee = ae);
}
}
}
A[T][ne][ee][X] += P[T][L][j][X];
}
}
}
return { dataId: l.write(w.toTypedArray(A, s.dtype), s.shape, s.dtype), shape: s.shape, dtype: s.dtype };
} };
function Zl(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, keepDims: o } = s;
be(r, "sum");
let i;
r.dtype === "bool" ? i = kr({ inputs: { x: r }, backend: n, attrs: { dtype: "int32" } }) : i = Os({ inputs: { x: r }, backend: n });
let u = i.shape.length, l = w.parseAxisParam(a, i.shape), c = C.getAxesPermutation(l, u), p = l, d = i;
c != null && (d = wn({ inputs: { x: i }, backend: n, attrs: { perm: c } }), p = C.getInnerMostAxes(p.length, u)), C.assertAxesAreInnerMostDims("sum", p, d.shape.length);
let [h, f] = C.computeOutAndReduceShapes(d.shape, p), m = C.upcastType(d.dtype, "int32"), g = Bd(n, h, m), b = w.sizeFromShape(f), y = n.data.get(g.dataId).values, v = n.data.get(d.dataId).values;
for (let x = 0; x < y.length; ++x) {
let k = x * b, I = 0;
for (let $ = 0; $ < b; ++$)
I += v[k + $];
y[x] = I;
}
if (o) {
let x = C.expandShapeToKeepDim(g.shape, l), k = g;
g = pt({ inputs: { x: g }, backend: n, attrs: { shape: x } }), n.disposeIntermediateTensorInfo(k);
}
return n.disposeIntermediateTensorInfo(i), c != null && n.disposeIntermediateTensorInfo(d), g;
}
var Eq = { kernelName: co, backendName: "cpu", kernelFunc: Zl };
function Rq(e) {
let { inputs: t, backend: n, attrs: s } = e, { equation: r } = s, a = t, { allDims: o, summedDims: i, idDims: u } = C.decodeEinsumEquation(r, a.length);
C.checkEinsumDimSizes(o.length, u, a);
let { path: l, steps: c } = C.getEinsumComputePath(i, u), p = c.length, d = null, h = o.length, f = [];
for (let m = 0; m < p; ++m) {
for (let g of c[m]) {
let { permutationIndices: b, expandDims: y } = C.getEinsumPermutation(h, u[g]), v;
C.isIdentityPermutation(b) ? v = a[g] : (v = wn({ inputs: { x: a[g] }, backend: n, attrs: { perm: b } }), f.push(v));
let x = v.shape.slice();
for (let k = 0; k < y.length; ++k)
x.splice(y[k], 0, 1);
w.arraysEqual(v.shape, x) || (v = pt({ inputs: { x: v }, backend: n, attrs: { shape: x } }), f.push(v)), d === null ? d = v : (d = eh({ inputs: { a: v, b: d }, backend: n }), f.push(d));
}
m < p - 1 && (l[m] >= 0 && (d = Zl({ inputs: { x: d }, backend: n, attrs: { axis: l[m] - (o.length - h), keepDims: false } }), f.push(d)), h--);
}
for (let m of f)
m !== d && n.disposeIntermediateTensorInfo(m);
return d;
}
var Dq = { kernelName: op, backendName: "cpu", kernelFunc: Rq };
function Fq(e) {
let { inputs: t, backend: n } = e, { dy: s, y: r } = t;
be([s, r], "eluGrad");
let a = new Float32Array(w.sizeFromShape(r.shape)), o = n.data.get(r.dataId).values, i = n.data.get(s.dataId).values;
for (let u = 0; u < o.length; ++u) {
let l = o[u];
l >= 1 ? a[u] = i[u] : a[u] = i[u] * (l + 1);
}
return n.makeTensorInfo(r.shape, "float32", a);
}
var Oq = { kernelName: $g, backendName: "cpu", kernelFunc: Fq };
var Pq = C.ERF_P;
var zq = C.ERF_A1;
var Lq = C.ERF_A2;
var Mq = C.ERF_A3;
var Bq = C.ERF_A4;
var Vq = C.ERF_A5;
var Wq = st(yl, (e) => {
let t = Math.sign(e), n = Math.abs(e), s = 1 / (1 + Pq * n);
return t * (1 - ((((Vq * s + Bq) * s + Mq) * s + Lq) * s + zq) * s * Math.exp(-n * n));
});
var Uq = { kernelName: yl, backendName: "cpu", kernelFunc: Wq };
function Ud(e) {
let { inputs: t, backend: n, attrs: s } = e, { input: r } = t, { dim: a } = s, o = r.shape.length, i = r.shape.slice(), u = a;
return a < 0 && (w.assert(-(o + 1) <= a, () => `Axis must be in the interval [${-(o + 1)}, ${o}]`), u = o + a + 1), i.splice(u, 0, 1), pt({ inputs: { x: r }, backend: n, attrs: { shape: i } });
}
var Gq = { kernelName: yi, backendName: "cpu", kernelFunc: Ud };
var Hq = At((e, t) => e / t);
var xv = Gt(Oa, Hq);
var Ym = { kernelName: Oa, backendName: "cpu", kernelFunc: xv };
function JC(e, t, n) {
let s = e.shape, r = s[0], a = s[1], o = n.data.get(e.dataId), i = o.complexTensorInfos.real, u = o.complexTensorInfos.imag, l = [r, a], c = w.sizeFromShape(l), p = w.getTypedArrayFromDType("float32", c), d = w.getTypedArrayFromDType("float32", c);
for (let g = 0; g < r; g++) {
let b = ba({ inputs: { x: i }, backend: n, attrs: { begin: [g, 0], size: [1, a] } }), y = ba({ inputs: { x: u }, backend: n, attrs: { begin: [g, 0], size: [1, a] } }), v = En({ inputs: { real: b, imag: y }, backend: n }), { real: x, imag: k } = qq(v, t, n), I = C.mergeRealAndImagArrays(x, k);
for (let $ = 0; $ < a; $++) {
let R = C.getComplexWithIndex(I, $);
p[g * a + $] = R.real, d[g * a + $] = R.imag;
}
n.disposeIntermediateTensorInfo(b), n.disposeIntermediateTensorInfo(y), n.disposeIntermediateTensorInfo(v);
}
let h = n.makeTensorInfo(l, "float32", p), f = n.makeTensorInfo(l, "float32", d), m = En({ inputs: { real: h, imag: f }, backend: n });
return n.disposeIntermediateTensorInfo(h), n.disposeIntermediateTensorInfo(f), m;
}
function qq(e, t, n) {
let s = w.sizeFromShape(e.shape), r = n.data.get(e.dataId), a = n.data.get(r.complexTensorInfos.real.dataId).values, o = n.data.get(r.complexTensorInfos.imag.dataId).values;
if (jq(s)) {
let i = Qm(a, o, s, t, n), u = [e.shape[0], e.shape[1]];
if (t) {
let l = n.makeTensorInfo(u, "float32", i.real), c = n.makeTensorInfo(u, "float32", i.imag), p = n.makeTensorInfo([], "float32", w.createScalarValue(s, "float32")), d = Os({ inputs: { x: p }, backend: n }), h = Ym.kernelFunc({ inputs: { a: l, b: p }, backend: n }), f = Ym.kernelFunc({ inputs: { a: c, b: d }, backend: n }), m = n.data.get(h.dataId).values, g = n.data.get(f.dataId).values;
return n.disposeIntermediateTensorInfo(l), n.disposeIntermediateTensorInfo(c), n.disposeIntermediateTensorInfo(p), n.disposeIntermediateTensorInfo(d), n.disposeIntermediateTensorInfo(h), n.disposeIntermediateTensorInfo(f), { real: m, imag: g };
}
return i;
} else {
let i = C.mergeRealAndImagArrays(a, o), u = Kq(i, s, t);
return C.splitRealAndImagArrays(u);
}
}
function jq(e) {
return (e & e - 1) === 0;
}
function Qm(e, t, n, s, r) {
if (n === 1)
return { real: e, imag: t };
let a = C.mergeRealAndImagArrays(e, t), o = n / 2, i = C.complexWithEvenIndex(a), u = i.real, l = i.imag, c = [u.length], p = r.makeTensorInfo(c, "float32", u), d = r.makeTensorInfo(c, "float32", l), h = En({ inputs: { real: p, imag: d }, backend: r }), f = C.complexWithOddIndex(a), m = f.real, g = f.imag, b = [m.length], y = r.makeTensorInfo(b, "float32", m), v = r.makeTensorInfo(b, "float32", g), x = En({ inputs: { real: y, imag: v }, backend: r }), k = Qm(u, l, o, s, r), I = k.real, $ = k.imag, R = [I.length], E = r.makeTensorInfo(R, "float32", I), P = r.makeTensorInfo(R, "float32", $), A = En({ inputs: { real: E, imag: P }, backend: r }), D = Qm(m, g, o, s, r), T = D.real, L = D.imag, W = [T.length], j = r.makeTensorInfo(W, "float32", T), Y = r.makeTensorInfo(W, "float32", L), X = En({ inputs: { real: j, imag: Y }, backend: r }), Z = C.exponents(n, s), ne = [Z.real.length], ee = r.makeTensorInfo(ne, "float32", Z.real), se = r.makeTensorInfo(ne, "float32", Z.imag), te = En({ inputs: { real: ee, imag: se }, backend: r }), ie = eh({ inputs: { a: te, b: X }, backend: r }), ae = oi({ inputs: { a: A, b: ie }, backend: r }), de = yv({ inputs: { a: A, b: ie }, backend: r }), me = ga({ inputs: { input: ae }, backend: r }), ke = ga({ inputs: { input: de }, backend: r }), Ie = ii({ inputs: { input: ae }, backend: r }), Re = ii({ inputs: { input: de }, backend: r }), Pe = ui({ inputs: [me, ke], backend: r, attrs: { axis: 0 } }), Xe = ui({ inputs: [Ie, Re], backend: r, attrs: { axis: 0 } }), Je = r.data.get(Pe.dataId).values, Ye = r.data.get(Xe.dataId).values;
return r.disposeIntermediateTensorInfo(p), r.disposeIntermediateTensorInfo(d), r.disposeIntermediateTensorInfo(h), r.disposeIntermediateTensorInfo(y), r.disposeIntermediateTensorInfo(v), r.disposeIntermediateTensorInfo(x), r.disposeIntermediateTensorInfo(E), r.disposeIntermediateTensorInfo(P), r.disposeIntermediateTensorInfo(A), r.disposeIntermediateTensorInfo(j), r.disposeIntermediateTensorInfo(Y), r.disposeIntermediateTensorInfo(X), r.disposeIntermediateTensorInfo(ee), r.disposeIntermediateTensorInfo(se), r.disposeIntermediateTensorInfo(te), r.disposeIntermediateTensorInfo(ie), r.disposeIntermediateTensorInfo(ae), r.disposeIntermediateTensorInfo(de), r.disposeIntermediateTensorInfo(me), r.disposeIntermediateTensorInfo(Ie), r.disposeIntermediateTensorInfo(ke), r.disposeIntermediateTensorInfo(Re), r.disposeIntermediateTensorInfo(Pe), r.disposeIntermediateTensorInfo(Xe), { real: Je, imag: Ye };
}
function Kq(e, t, n) {
let s = new Float32Array(t * 2);
for (let r = 0; r < t; r++) {
let a = 0, o = 0;
for (let i = 0; i < t; i++) {
let u = C.exponent(r * i, t, n), l = C.getComplexWithIndex(e, i);
a += l.real * u.real - l.imag * u.imag, o += l.real * u.imag + l.imag * u.real;
}
n && (a /= t, o /= t), C.assignToTypedArray(s, a, o, r);
}
return s;
}
function Xq(e) {
let { inputs: t, backend: n } = e, { input: s } = t, r = w.sizeFromShape(s.shape), a = s.shape[s.shape.length - 1], o = r / a, i = pt({ inputs: { x: s }, backend: n, attrs: { shape: [o, a] } }), u = JC(i, false, n), l = pt({ inputs: { x: u }, backend: n, attrs: { shape: s.shape } });
return n.disposeIntermediateTensorInfo(i), n.disposeIntermediateTensorInfo(u), l;
}
var Yq = { kernelName: _g, backendName: "cpu", kernelFunc: Xq };
function wv(e) {
let { backend: t, attrs: n } = e, { shape: s, value: r, dtype: a } = n, o = a || w.inferDtype(r), i = w.getArrayFromDType(o, w.sizeFromShape(s));
return Zq(i, r, o), t.makeTensorInfo(s, o, i);
}
var Qq = { kernelName: vl, backendName: "cpu", kernelFunc: wv };
function Zq(e, t, n) {
e.fill(t);
}
var Jq = { kernelName: xi, backendName: "cpu", kernelFunc: ({ inputs: e, attrs: t, backend: n }) => {
let { image: s } = e, r = n, a = w.getTypedArrayFromDType(s.dtype, w.sizeFromShape(s.shape)), [o, i, u, l] = s.shape, c = r.data.get(s.dataId).values;
for (let d = 0; d < o; d++) {
let h = d * u * i * l;
for (let f = 0; f < i; f++) {
let m = f * (u * l);
for (let g = 0; g < u; g++) {
let b = g * l;
for (let y = 0; y < l; y++) {
let v = Math.round(u - g - 1), x = h + m + b + y, k = c[x];
if (v >= 0 && v < u) {
let I = v * l, $ = h + m + I + y;
k = c[$];
}
a[x] = k;
}
}
}
}
return { dataId: r.write(a, s.shape, s.dtype), shape: s.shape, dtype: s.dtype };
} };
var e6 = At((e, t) => Math.floor(e / t));
var t6 = Gt(Ma, e6, null, "int32");
var n6 = { kernelName: Ma, backendName: "cpu", kernelFunc: t6 };
function s6(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, filter: a, bias: o, preluActivationWeights: i } = t, { strides: u, pad: l, dataFormat: c, dilations: p, dimRoundingMode: d, activation: h, leakyreluAlpha: f } = s, m = QC({ inputs: { x: r, filter: a }, backend: n, attrs: { strides: u, pad: l, dataFormat: c, dilations: p, dimRoundingMode: d } });
if (o) {
let g = m;
if (c === "NCHW" && o.shape.length === 1 && o.shape[0] !== 1) {
let b = pt({ inputs: { x: o }, backend: n, attrs: { shape: [o.shape[0], 1, 1] } });
m = oi({ inputs: { a: m, b }, backend: n }), n.disposeIntermediateTensorInfo(b);
} else
m = oi({ inputs: { a: m, b: o }, backend: n });
n.disposeIntermediateTensorInfo(g);
}
if (h) {
let g = m;
if (c === "NCHW" && h === "prelu" && i.shape.length === 1 && i.shape[0] !== 1) {
let b = pt({ inputs: { x: i }, backend: n, attrs: { shape: [i.shape[0], 1, 1] } });
m = Wd(n, m, h, b, f), n.disposeIntermediateTensorInfo(b);
} else
m = Wd(n, m, h, i, f);
n.disposeIntermediateTensorInfo(g);
}
return m;
}
var r6 = { kernelName: ia, backendName: "cpu", kernelFunc: s6 };
function a6(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, filter: a, bias: o, preluActivationWeights: i } = t, { strides: u, pad: l, dataFormat: c, dilations: p, dimRoundingMode: d, activation: h, leakyreluAlpha: f } = s, m = ZC({ inputs: { x: r, filter: a }, backend: n, attrs: { strides: u, pad: l, dataFormat: c, dilations: p, dimRoundingMode: d } });
if (o) {
let g = m;
m = oi({ inputs: { a: m, b: o }, backend: n }), n.disposeIntermediateTensorInfo(g);
}
if (h) {
let g = m;
m = Wd(n, m, h, i, f), n.disposeIntermediateTensorInfo(g);
}
return m;
}
var o6 = { kernelName: ua, backendName: "cpu", kernelFunc: a6 };
function i6(e) {
let { inputs: t, backend: n } = e, { params: s, indices: r } = t, a = w.sizeFromShape(s.shape), o = r.shape, i = o[o.length - 1], [u, l, c, p] = C.prepareAndValidate(s, r);
if (l === 0)
return n.makeTensorInfo(u, s.dtype, []);
let d = n.data.get(r.dataId).values, h = n.bufferSync(s), f = mC(d, h, s.dtype, l, i, c, p, s.shape, a);
return n.makeTensorInfo(u, s.dtype, f.values);
}
var u6 = { kernelName: ki, backendName: "cpu", kernelFunc: i6 };
function l6(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, indices: a } = t, { axis: o, batchDims: i } = s;
be([r, a], "gatherV2");
let u = w.parseAxisParam(o, r.shape)[0], l = n.data.get(a.dataId).values, c = r.shape[u];
for (let x = 0; x < l.length; ++x) {
let k = l[x];
w.assert(k <= c - 1 && k >= 0, () => `GatherV2: the index value ${k} is not in [0, ${c - 1}]`);
}
let p = i;
i == null && (p = 0);
let d = w.sizeFromShape(a.shape), h = C.segment_util.collectGatherOpShapeInfo(r, a, u, p), f = pt({ inputs: { x: r }, backend: n, attrs: { shape: [h.batchSize, h.outerSize, h.dimSize, h.sliceSize] } }), m = pt({ inputs: { x: a }, backend: n, attrs: { shape: [h.batchSize, d / h.batchSize] } }), g = [h.batchSize, h.outerSize, d / h.batchSize, h.sliceSize], b = n.bufferSync(m), y = n.bufferSync(f), v = gC(y, b, g);
return n.disposeIntermediateTensorInfo(f), n.disposeIntermediateTensorInfo(m), n.makeTensorInfo(h.outputShape, v.dtype, v.values);
}
var c6 = { kernelName: wi, backendName: "cpu", kernelFunc: l6 };
function d6(e) {
let { inputs: t, backend: n } = e, { input: s } = t, r = w.sizeFromShape(s.shape), a = s.shape[s.shape.length - 1], o = r / a, i = pt({ inputs: { x: s }, backend: n, attrs: { shape: [o, a] } }), u = JC(i, true, n), l = pt({ inputs: { x: u }, backend: n, attrs: { shape: s.shape } });
return n.disposeIntermediateTensorInfo(i), n.disposeIntermediateTensorInfo(u), l;
}
var p6 = { kernelName: Ag, backendName: "cpu", kernelFunc: d6 };
var h6 = st(xl, (e) => Number.isFinite(e) ? 1 : 0, "bool");
var f6 = { kernelName: xl, backendName: "cpu", kernelFunc: h6 };
var m6 = st(wl, (e) => Math.abs(e) === 1 / 0 ? 1 : 0, "bool");
var g6 = { kernelName: wl, backendName: "cpu", kernelFunc: m6 };
var b6 = st(kl, (e) => Number.isNaN(e) ? 1 : 0, "bool");
var y6 = { kernelName: kl, backendName: "cpu", kernelFunc: b6 };
function v6(e) {
let { backend: t, attrs: n } = e, { start: s, stop: r, num: a } = n, o = wC(s, r, a);
return t.makeTensorInfo([o.length], "float32", o);
}
var x6 = { kernelName: Eg, backendName: "cpu", kernelFunc: v6 };
var w6 = st(Sl, (e) => Math.log1p(e));
var k6 = { kernelName: Sl, backendName: "cpu", kernelFunc: w6 };
var S6 = At((e, t) => e && t);
var I6 = Gt(Ni, S6, null, "bool");
var C6 = { kernelName: Ni, backendName: "cpu", kernelFunc: I6 };
var N6 = st(Ti, (e) => e ? 0 : 1, "bool");
var T6 = { kernelName: Ti, backendName: "cpu", kernelFunc: N6 };
var $6 = At((e, t) => e || t);
var _6 = Gt(Il, $6, null, "bool");
var A6 = { kernelName: Il, backendName: "cpu", kernelFunc: _6 };
function E6(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { depthRadius: a, bias: o, alpha: i, beta: u } = s;
be(r, "LRN");
let l = r.shape[3], c = l - 1, p = n.data.get(r.dataId).values, d = w.sizeFromShape(r.shape), h = new Float32Array(d);
function f(m) {
let g = m % l, b = m - g + Math.max(0, g - a), y = m - g + Math.min(g + a, c), v = 0;
for (; b <= y; b++) {
let x = p[b];
v += x * x;
}
return v;
}
for (let m = 0; m < d; m++) {
let g = f(m), b = p[m] * Math.pow(o + i * g, -u);
h[m] = b;
}
return n.makeTensorInfo(r.shape, r.dtype, h);
}
var R6 = { kernelName: up, backendName: "cpu", kernelFunc: E6 };
function D6(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, y: a, dy: o } = t, { depthRadius: i, bias: u, alpha: l, beta: c } = s;
be(o, "LRNGrad");
let p = w.sizeFromShape(o.shape), d = o.shape[3], h = n.data.get(o.dataId).values, f = n.data.get(r.dataId).values, m = n.data.get(a.dataId).values, g = new Float32Array(p), b = p;
for (let y = 0; y < b; y++) {
let v = y % d, x = y - v + Math.max(0, v - i), k = y - v + Math.min(d, v + i + 1), I = 0;
for (let $ = x; $ < k; $++)
I += Math.pow(f[$], 2);
I = l * I + u;
for (let $ = x; $ < k; $++) {
let R = -2 * l * c * f[$] * m[y] / I;
y === $ && (R += Math.pow(I, -c)), R *= h[y], g[$] += R;
}
}
return n.makeTensorInfo(o.shape, r.dtype, g);
}
var F6 = { kernelName: Rg, backendName: "cpu", kernelFunc: D6 };
function e1(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { reductionIndices: a, keepDims: o } = s, i = n, u = r.shape, l = u.length, c = w.parseAxisParam(a, u), p = c, d = C.getAxesPermutation(p, l), h = i.data.get(r.dataId).values;
if (d != null) {
let x = new Array(l);
for (let k = 0; k < x.length; k++)
x[k] = u[d[k]];
h = mv(h, u, r.dtype, d, x), p = C.getInnerMostAxes(p.length, l), u = x;
}
be(r, "max"), C.assertAxesAreInnerMostDims("max", p, l);
let [f, m] = C.computeOutAndReduceShapes(u, p), g = w.sizeFromShape(m), b = SC(h, g, f, r.dtype), y = i.write(b, f, r.dtype), v = f;
return o && (v = C.expandShapeToKeepDim(f, c)), { dataId: y, shape: v, dtype: r.dtype };
}
var O6 = { kernelName: Ha, backendName: "cpu", kernelFunc: e1 };
function P6(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t;
be(r, "maxPool");
let { filterSize: a, strides: o, pad: i, dimRoundingMode: u } = s, l = 1;
w.assert(C.eitherStridesOrDilationsAreOne(o, l), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${l}'`);
let c = C.computePool2DInfo(r.shape, a, o, l, i, u), p;
if (c.filterWidth === 1 && c.filterHeight === 1 && w.arraysEqual(c.inShape, c.outShape))
p = Os({ inputs: { x: r }, backend: n });
else {
let d = n.data.get(r.dataId).values, h = w.computeStrides(r.shape), f = vv(d, r.shape, r.dtype, h, c, "max");
p = n.makeTensorInfo(c.outShape, r.dtype, f.values);
}
return p;
}
var z6 = { kernelName: ja, backendName: "cpu", kernelFunc: P6 };
function L6(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { filterSize: a, strides: o, pad: i, dimRoundingMode: u, dataFormat: l } = s;
be(r, "maxPool3d");
let c = C.computePool3DInfo(r.shape, a, o, 1, i, u, l), p = n.data.get(r.dataId).values, d = YC(p, r.shape, r.dtype, w.computeStrides(r.shape), c, "max");
return n.makeTensorInfo(d.shape, "float32", d.values);
}
var M6 = { kernelName: lp, backendName: "cpu", kernelFunc: L6 };
function B6(e) {
let { inputs: t, backend: n, attrs: s } = e, { dy: r, input: a } = t, { filterSize: o, strides: i, pad: u, dimRoundingMode: l } = s;
be([r, a], "maxPool3DGrad");
let c = C.computePool3DInfo(a.shape, o, i, 1, u, l), p = n.bufferSync(a), d = TH(p, c), h = c.strideDepth, f = c.strideHeight, m = c.strideWidth, g = c.dilationDepth, b = c.dilationHeight, y = c.dilationWidth, v = c.effectiveFilterDepth, x = c.effectiveFilterHeight, k = c.effectiveFilterWidth, I = v - 1 - c.padInfo.front, $ = k - 1 - c.padInfo.left, R = x - 1 - c.padInfo.top, E = Ae(a.shape, "float32"), P = n.bufferSync(r);
for (let A = 0; A < c.batchSize; ++A)
for (let D = 0; D < c.inChannels; ++D)
for (let T = 0; T < c.inDepth; ++T)
for (let L = 0; L < c.inHeight; ++L)
for (let W = 0; W < c.inWidth; ++W) {
let j = T - I, Y = L - R, X = W - $, Z = 0;
for (let ne = 0; ne < v; ne += g) {
let ee = (j + ne) / h;
if (!(ee < 0 || ee >= c.outDepth || Math.floor(ee) !== ee))
for (let se = 0; se < x; se += b) {
let te = (Y + se) / f;
if (!(te < 0 || te >= c.outHeight || Math.floor(te) !== te))
for (let ie = 0; ie < k; ie += y) {
let ae = (X + ie) / m;
if (ae < 0 || ae >= c.outWidth || Math.floor(ae) !== ae)
continue;
let de = v * x * k - 1 - d.get(A, ee, te, ae, D), me = ne * x * k + se * k + ie, ke = de === me ? 1 : 0;
if (ke === 0)
continue;
Z += P.get(A, ee, te, ae, D) * ke;
}
}
}
E.set(Z, A, T, L, W, D);
}
return n.makeTensorInfo(E.shape, E.dtype, E.values);
}
var V6 = { kernelName: Fg, backendName: "cpu", kernelFunc: B6 };
function W6(e) {
let { inputs: t, backend: n, attrs: s } = e, { dy: r, input: a, output: o } = t, i = a;
be([a, o], "maxPoolGrad");
let { filterSize: u, strides: l, pad: c, dimRoundingMode: p } = s, d = C.computePool2DInfo(i.shape, u, l, 1, c, p), h = n.data.get(i.dataId).values, f = Ae(d.outShape, i.dtype, XC(h, i.shape, i.dtype, d).values), m = d.strideHeight, g = d.strideWidth, b = d.dilationHeight, y = d.dilationWidth, v = d.effectiveFilterHeight, x = d.effectiveFilterWidth, k = x - 1 - d.padInfo.left, I = v - 1 - d.padInfo.top, $ = Ae(i.shape, "float32"), R = n.data.get(r.dataId).values, E = Ae(r.shape, "float32", R);
for (let P = 0; P < d.batchSize; ++P)
for (let A = 0; A < d.inChannels; ++A)
for (let D = 0; D < d.inHeight; ++D)
for (let T = 0; T < d.inWidth; ++T) {
let L = D - I, W = T - k, j = 0;
for (let Y = 0; Y < v; Y += b) {
let X = (L + Y) / m;
if (!(X < 0 || X >= d.outHeight || Math.floor(X) !== X))
for (let Z = 0; Z < x; Z += y) {
let ne = (W + Z) / g;
if (ne < 0 || ne >= d.outWidth || Math.floor(ne) !== ne)
continue;
let ee = v * x - 1 - f.get(P, X, ne, A), se = Y * x + Z, te = ee === se ? 1 : 0;
if (te === 0)
continue;
j += E.get(P, X, ne, A) * te;
}
}
$.set(j, P, D, T, A);
}
return n.makeTensorInfo($.shape, $.dtype, $.values);
}
var U6 = { kernelName: Dg, backendName: "cpu", kernelFunc: W6 };
function G6(e, t, n, s, r) {
let a = w.computeStrides(t), o = vv(e, t, n, a, r, "max"), i = XC(e, t, n, r, true, s);
return [o.values, i.values];
}
var H6 = { kernelName: Og, backendName: "cpu", kernelFunc: ({ inputs: e, attrs: t, backend: n }) => {
let { x: s } = e, { filterSize: r, strides: a, pad: o, includeBatchInIndex: i } = t, u = n;
be(s, "MaxPoolWithArgmax");
let l = u.data.get(s.dataId).values, c = C.computePool2DInfo(s.shape, r, a, [1, 1], o), [p, d] = G6(l, s.shape, s.dtype, i, c), h = u.write(p, c.outShape, s.dtype), f = u.write(d, c.outShape, s.dtype);
return [{ dataId: h, shape: c.outShape, dtype: s.dtype }, { dataId: f, shape: c.outShape, dtype: "int32" }];
} };
function q6(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, keepDims: o } = s, i = w.parseAxisParam(a, r.shape), l = C.computeOutAndReduceShapes(r.shape, i)[1], c = w.sizeFromShape(l), p = [], d = n.makeTensorInfo([], "float32", new Float32Array([c]));
p.push(d);
let h = kr({ inputs: { x: r }, backend: n, attrs: { dtype: "float32" } });
p.push(h);
let f = xv({ inputs: { a: h, b: d }, backend: n });
p.push(f);
let m = Zl({ inputs: { x: f }, backend: n, attrs: { axis: a, keepDims: o } });
return p.forEach((g) => n.disposeIntermediateTensorInfo(g)), m;
}
var j6 = { kernelName: Ka, backendName: "cpu", kernelFunc: q6 };
function K6(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, keepDims: o } = s;
be(r, "min");
let i = w.parseAxisParam(a, r.shape), u = i, l = C.getAxesPermutation(u, r.shape.length), c = r;
l != null && (c = wn({ inputs: { x: r }, backend: n, attrs: { perm: l } }), u = C.getInnerMostAxes(u.length, r.shape.length)), C.assertAxesAreInnerMostDims("min", u, c.shape.length);
let [p, d] = C.computeOutAndReduceShapes(c.shape, u), h = w.sizeFromShape(d), f = w.makeZerosTypedArray(w.sizeFromShape(p), c.dtype), m = n.data.get(c.dataId).values;
for (let b = 0; b < f.length; ++b) {
let y = b * h, v = m[y];
for (let x = 0; x < h; ++x) {
let k = m[y + x];
(Number.isNaN(k) || k < v) && (v = k);
}
f[b] = v;
}
l != null && n.disposeIntermediateTensorInfo(c);
let g = n.makeTensorInfo(p, c.dtype, f);
if (o) {
let b = C.expandShapeToKeepDim(p, i), y = pt({ inputs: { x: g }, backend: n, attrs: { shape: b } });
return n.disposeIntermediateTensorInfo(g), y;
}
return g;
}
var X6 = { kernelName: Xa, backendName: "cpu", kernelFunc: K6 };
function Y6(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { paddings: a, mode: o } = s;
be(r, "mirrorPad");
let i = a.map((v, x) => v[0] + r.shape[x] + v[1]), u = a.map((v) => v[0]), l = a.map((v, x) => v[0] + r.shape[x]), c = o === "reflect" ? 0 : 1, p = n.data.get(r.dataId).values, d = r.shape.length, h = w.computeStrides(r.shape), f = w.sizeFromShape(i), m = i.length, g = w.computeStrides(i), b = w.getTypedArrayFromDType(r.dtype, f);
for (let v = 0; v < f; v++) {
let x = w.indexToLoc(v, m, g);
for (let I = 0; I < m; I++)
x[I] < u[I] ? x[I] = u[I] * 2 - x[I] - c : x[I] >= l[I] && (x[I] = (l[I] - 1) * 2 - x[I] + c);
x = x.map((I, $) => I - u[$]);
let k = w.locToIndex(x, d, h);
b[v] = p[k];
}
return { dataId: n.write(b, i, r.dtype), shape: i, dtype: r.dtype };
}
var Q6 = { kernelName: Qa, backendName: "cpu", kernelFunc: Y6 };
var Z6 = At((e, t) => {
let n = e % t;
return e < 0 && t < 0 || e >= 0 && t >= 0 ? n : (n + t) % t;
});
var J6 = Gt(Cl, Z6);
var ej = { kernelName: Cl, backendName: "cpu", kernelFunc: J6 };
var tj = wa(Qd());
function t1(e) {
let { inputs: t, backend: n, attrs: s } = e, { logits: r } = t, { dim: a } = s, o = r.shape.length, i = a;
if (i === -1 && (i = o - 1), i !== o - 1)
throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${o} and dim was ${i}`);
let u = w.parseAxisParam([i], r.shape), l = e1({ inputs: { x: r }, backend: n, attrs: { reductionIndices: u, keepDims: false } }), c = C.expandShapeToKeepDim(l.shape, u), p = pt({ inputs: { x: l }, backend: n, attrs: { shape: c } }), d = yv({ inputs: { a: r, b: p }, backend: n }), h = pC({ inputs: { x: d }, backend: n }), f = Zl({ inputs: { x: h }, backend: n, attrs: { axis: u, keepDims: false } }), m = pt({ inputs: { x: f }, backend: n, attrs: { shape: c } }), g = xv({ inputs: { a: h, b: m }, backend: n });
return n.disposeIntermediateTensorInfo(l), n.disposeIntermediateTensorInfo(p), n.disposeIntermediateTensorInfo(d), n.disposeIntermediateTensorInfo(h), n.disposeIntermediateTensorInfo(f), n.disposeIntermediateTensorInfo(m), g;
}
var nj = { kernelName: po, backendName: "cpu", kernelFunc: t1 };
function sj(e) {
let { inputs: t, backend: n, attrs: s } = e, { logits: r } = t, { numSamples: a, seed: o, normalized: i } = s;
be(r, "multinomial");
let u = i ? r : t1({ inputs: { logits: r }, backend: n, attrs: { dim: -1 } }), l = u.shape[0], c = u.shape[1], p = n.data.get(u.dataId).values, d = [l, a], h = w.makeZerosTypedArray(w.sizeFromShape(d), "int32");
for (let f = 0; f < l; ++f) {
let m = f * c, g = new Float32Array(c - 1);
g[0] = p[m];
for (let v = 1; v < g.length; ++v)
g[v] = g[v - 1] + p[m + v];
let b = tj.alea(o.toString()), y = f * a;
for (let v = 0; v < a; ++v) {
let x = b();
h[y + v] = g.length;
for (let k = 0; k < g.length; k++)
if (x < g[k]) {
h[y + v] = k;
break;
}
}
}
return i || n.disposeIntermediateTensorInfo(u), n.makeTensorInfo(d, "int32", h);
}
var rj = { kernelName: Pg, backendName: "cpu", kernelFunc: sj };
var aj = ws.nonMaxSuppressionV3Impl;
function oj(e) {
let { inputs: t, backend: n, attrs: s } = e, { boxes: r, scores: a } = t, { maxOutputSize: o, iouThreshold: i, scoreThreshold: u } = s;
be(r, "NonMaxSuppression");
let l = n.data.get(r.dataId).values, c = n.data.get(a.dataId).values, { selectedIndices: p } = aj(l, c, o, i, u);
return n.makeTensorInfo([p.length], "int32", new Int32Array(p));
}
var ij = { kernelName: Ai, backendName: "cpu", kernelFunc: oj };
var uj = ws.nonMaxSuppressionV4Impl;
function lj(e) {
let { inputs: t, backend: n, attrs: s } = e, { boxes: r, scores: a } = t, { maxOutputSize: o, iouThreshold: i, scoreThreshold: u, padToMaxOutputSize: l } = s;
be(r, "NonMaxSuppressionPadded");
let c = n.data.get(r.dataId).values, p = n.data.get(a.dataId).values, { selectedIndices: d, validOutputs: h } = uj(c, p, o, i, u, l);
return [n.makeTensorInfo([d.length], "int32", new Int32Array(d)), n.makeTensorInfo([], "int32", new Int32Array([h]))];
}
var cj = { kernelName: Nl, backendName: "cpu", kernelFunc: lj };
var dj = ws.nonMaxSuppressionV5Impl;
function pj(e) {
let { inputs: t, backend: n, attrs: s } = e, { boxes: r, scores: a } = t, { maxOutputSize: o, iouThreshold: i, scoreThreshold: u, softNmsSigma: l } = s;
be(r, "NonMaxSuppressionWithScore");
let c = n.data.get(r.dataId).values, p = n.data.get(a.dataId).values, d = o, h = i, f = u, m = l, { selectedIndices: g, selectedScores: b } = dj(c, p, d, h, f, m);
return [n.makeTensorInfo([g.length], "int32", new Int32Array(g)), n.makeTensorInfo([b.length], "float32", new Float32Array(b))];
}
var hj = { kernelName: Ei, backendName: "cpu", kernelFunc: pj };
function fj(e) {
let { inputs: t, backend: n, attrs: s } = e, { indices: r } = t, { depth: a, onValue: o, offValue: i } = s;
be(r, "oneHot");
let u = w.sizeFromShape(r.shape), l = new Float32Array(u * a);
l.fill(i);
let c = n.data.get(r.dataId).values;
for (let p = 0; p < u; ++p)
c[p] >= 0 && c[p] < a && (l[p * a + c[p]] = o);
return n.makeTensorInfo([...r.shape, a], "int32", l);
}
var mj = { kernelName: Di, backendName: "cpu", kernelFunc: fj };
function Gd(e) {
let { inputs: t, backend: n } = e, { x: s } = t;
if (s.dtype === "string")
throw new Error("zerosLike is not supported for string tensors");
if (s.dtype === "complex64") {
let r = ga({ inputs: { input: s }, backend: n }), a = Gd({ inputs: { x: r }, backend: n }), o = ii({ inputs: { input: s }, backend: n }), i = Gd({ inputs: { x: o }, backend: n }), u = En({ inputs: { real: a, imag: i }, backend: n });
return n.disposeIntermediateTensorInfo(r), n.disposeIntermediateTensorInfo(a), n.disposeIntermediateTensorInfo(o), n.disposeIntermediateTensorInfo(i), u;
} else
return wv({ backend: n, attrs: { shape: s.shape, value: 0, dtype: s.dtype } });
}
var gj = { kernelName: Xi, backendName: "cpu", kernelFunc: Gd };
function n1(e) {
let { inputs: t, backend: n } = e, { x: s } = t;
if (s.dtype === "string")
throw new Error("onesLike is not supported for string tensors");
if (s.dtype === "complex64") {
let r = ga({ inputs: { input: s }, backend: n }), a = n1({ inputs: { x: r }, backend: n }), o = ii({ inputs: { input: s }, backend: n }), i = Gd({ inputs: { x: o }, backend: n }), u = En({ inputs: { real: a, imag: i }, backend: n });
return n.disposeIntermediateTensorInfo(r), n.disposeIntermediateTensorInfo(a), n.disposeIntermediateTensorInfo(o), n.disposeIntermediateTensorInfo(i), u;
} else
return wv({ backend: n, attrs: { shape: s.shape, value: 1, dtype: s.dtype } });
}
var bj = { kernelName: Ri, backendName: "cpu", kernelFunc: n1 };
function s1(e) {
let { inputs: t, backend: n, attrs: s } = e, { axis: r } = s;
if (t.length === 1)
return Ud({ inputs: { input: t[0] }, backend: n, attrs: { dim: r } });
let a = t[0].shape, o = t[0].dtype;
t.forEach((c) => {
w.assertShapesMatch(a, c.shape, "All tensors passed to stack must have matching shapes"), w.assert(o === c.dtype, () => "All tensors passed to stack must have matching dtypes");
});
let i = [], u = t.map((c) => {
let p = Ud({ inputs: { input: c }, backend: n, attrs: { dim: r } });
return i.push(p), p;
}), l = ui({ inputs: u, backend: n, attrs: { axis: r } });
return i.forEach((c) => n.disposeIntermediateTensorInfo(c)), l;
}
var yj = { kernelName: Fi, backendName: "cpu", kernelFunc: s1 };
function vj(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { paddings: a, constantValue: o } = s;
be(r, "pad");
let i = a.map((y, v) => y[0] + r.shape[v] + y[1]), u = a.map((y) => y[0]), l = n.data.get(r.dataId).values, c = w.sizeFromShape(r.shape), p = r.shape.length, d = w.computeStrides(r.shape), h = w.sizeFromShape(i), f = i.length, m = w.computeStrides(i), g = w.getTypedArrayFromDType(r.dtype, h);
o !== 0 && g.fill(o);
for (let y = 0; y < c; y++) {
let x = w.indexToLoc(y, p, d).map((I, $) => I + u[$]), k = w.locToIndex(x, f, m);
g[k] = l[y];
}
return { dataId: n.write(g, i, r.dtype), shape: i, dtype: r.dtype };
}
var r1 = { kernelName: Ja, backendName: "cpu", kernelFunc: vj };
var xj = At((e, t) => Math.pow(e, t));
var wj = Gt(eo, xj);
var kj = { kernelName: eo, backendName: "cpu", kernelFunc: wj };
function Sj(e) {
let { backend: t, attrs: n } = e, { start: s, stop: r, dtype: a, step: o } = n, i = gv(s, r, o, a);
return t.makeTensorInfo([i.length], a, i);
}
var Ij = { kernelName: Tl, backendName: "cpu", kernelFunc: Sj };
var Cj = st($l, (e) => 1 / e);
var Nj = { kernelName: $l, backendName: "cpu", kernelFunc: Cj };
function Tj(e) {
let { inputs: t, backend: n, attrs: s } = e, { images: r } = t, { alignCorners: a, halfPixelCenters: o, size: i } = s;
be(r, "resizeBilinear");
let u = w.computeStrides(r.shape), [l, c] = i, [p, d, h, f] = r.shape, m = n.data.get(r.dataId).values, g = new Float32Array(w.sizeFromShape([p, l, c, f])), b = [a && l > 1 ? d - 1 : d, a && c > 1 ? h - 1 : h], y = [a && l > 1 ? l - 1 : l, a && c > 1 ? c - 1 : c], v = 0, x = b[0] / y[0], k = b[1] / y[1];
for (let I = 0; I < p; I++)
for (let $ = 0; $ < l; $++) {
let R;
o ? R = x * ($ + 0.5) - 0.5 : R = x * $;
let E = Math.max(0, Math.floor(R)), P = R - E, A = Math.min(d - 1, Math.ceil(R)), D = I * u[0] + E * u[1], T = I * u[0] + A * u[1];
for (let L = 0; L < c; L++) {
let W;
o ? W = k * (L + 0.5) - 0.5 : W = k * L;
let j = Math.max(0, Math.floor(W)), Y = W - j, X = Math.min(h - 1, Math.ceil(W)), Z = D + j * u[2], ne = T + j * u[2], ee = D + X * u[2], se = T + X * u[2];
for (let te = 0; te < f; te++) {
let ie = m[Z + te], ae = m[ne + te], de = m[ee + te], me = m[se + te], ke = ie + (de - ie) * Y, Ie = ae + (me - ae) * Y, Re = ke + (Ie - ke) * P;
g[v++] = Re;
}
}
}
return n.makeTensorInfo([p, l, c, f], "float32", g);
}
var $j = { kernelName: ro, backendName: "cpu", kernelFunc: Tj };
function _j(e) {
let { inputs: t, backend: n, attrs: s } = e, { images: r, dy: a } = t, { alignCorners: o } = s;
be([a, r], "resizeBilinearGrad");
let i = w.computeStrides(r.shape), [u, l, c, p] = r.shape, [, d, h] = a.shape, f = new Float32Array(u * l * c * p), m = [o && d > 1 ? l - 1 : l, o && h > 1 ? c - 1 : c], g = [o && d > 1 ? d - 1 : d, o && h > 1 ? h - 1 : h], b = m[0] / g[0], y = m[1] / g[1], v = n.data.get(a.dataId).values, x = 0;
for (let k = 0; k < u; k++) {
let I = k * i[0];
for (let $ = 0; $ < d; $++) {
let R = $ * b, E = Math.floor(R), P = Math.min(Math.ceil(R), l - 1), A = I + E * i[1], D = I + P * i[1], T = R - E, L = 1 - T;
for (let W = 0; W < h; W++) {
let j = W * y, Y = Math.floor(j), X = Math.min(Math.ceil(j), c - 1), Z = j - Y, ne = 1 - Z, ee = A + Y * i[2], se = A + X * i[2], te = D + Y * i[2], ie = D + X * i[2], ae = L * ne, de = L * Z, me = T * ne, ke = T * Z;
for (let Ie = 0; Ie < p; Ie++) {
let Re = v[x++];
f[ee + Ie] += Re * ae, f[se + Ie] += Re * de, f[te + Ie] += Re * me, f[ie + Ie] += Re * ke;
}
}
}
}
return n.makeTensorInfo([u, c, l, p], "float32", f);
}
var Aj = { kernelName: Lg, backendName: "cpu", kernelFunc: _j };
function Ej(e) {
let { inputs: t, backend: n, attrs: s } = e, { images: r } = t, { alignCorners: a, halfPixelCenters: o, size: i } = s;
be(r, "resizeNearestNeighbor");
let u = w.computeStrides(r.shape), [l, c] = i, [p, d, h, f] = r.shape, m = n.data.get(r.dataId).values, g = new Float32Array(p * l * c * f), b = [a && l > 1 ? d - 1 : d, a && c > 1 ? h - 1 : h], y = [a && l > 1 ? l - 1 : l, a && c > 1 ? c - 1 : c], v = b[0] / y[0], x = b[1] / y[1], k = 0;
for (let I = 0; I < p; I++) {
let $ = I * u[0];
for (let R = 0; R < l; R++) {
let E = o ? v * (R + 0.5) : v * R, P = Math.min(d - 1, a ? Math.round(E) : Math.floor(E));
o && (P = Math.max(0, P));
let A = $ + P * u[1];
for (let D = 0; D < c; D++) {
let T = o ? x * (D + 0.5) : x * D, L = Math.min(h - 1, a ? Math.round(T) : Math.floor(T));
o && (L = Math.max(0, L));
let W = A + L * u[2];
for (let j = 0; j < f; j++) {
let Y = m[W + j];
g[k++] = Y;
}
}
}
}
return n.makeTensorInfo([p, l, c, f], r.dtype, g);
}
var Rj = { kernelName: _l, backendName: "cpu", kernelFunc: Ej };
function Dj(e) {
let { inputs: t, backend: n, attrs: s } = e, { images: r, dy: a } = t, { alignCorners: o } = s;
be([a, r], "resizeNearestNeighborGrad");
let i = w.computeStrides(r.shape), u = w.computeStrides(a.shape), [l, c, p, d] = r.shape, [, h, f] = a.shape, m = new Float32Array(l * c * p * d), g = n.data.get(a.dataId).values, b = [o && h > 1 ? c - 1 : c, o && f > 1 ? p - 1 : p], y = [o && h > 1 ? h - 1 : h, o && f > 1 ? f - 1 : f], v = b[0] / y[0], x = b[1] / y[1], k = 1 / v, I = 1 / x, $ = Math.ceil(k) * 2 + 2, R = Math.ceil(I) * 2 + 2;
for (let E = 0; E < l; E++) {
let P = E * i[0];
for (let A = 0; A < c; A++) {
let D = P + A * i[1], T = Math.floor(A * k), L = Math.floor(T - $ / 2);
for (let W = 0; W < p; W++) {
let j = D + W * i[2], Y = Math.floor(W * I), X = Math.floor(Y - R / 2);
for (let Z = 0; Z < d; Z++) {
let ne = 0;
for (let ee = 0; ee < $; ee++) {
let se = ee + L;
if (se < 0 || se >= h)
continue;
let te = P + se * u[1], ie = se * v, ae = Math.min(c - 1, o ? Math.round(ie) : Math.floor(ie));
if (A === ae)
for (let de = 0; de < R; de++) {
let me = de + X;
if (me < 0 || me >= f)
continue;
let ke = te + me * u[2], Ie = me * x, Re = Math.min(p - 1, o ? Math.round(Ie) : Math.floor(Ie));
W === Re && (ne += g[ke + Z]);
}
}
m[j + Z] = ne;
}
}
}
}
return n.makeTensorInfo(r.shape, r.dtype, m);
}
var Fj = { kernelName: zg, backendName: "cpu", kernelFunc: Dj };
function Oj(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { dims: a } = s;
be(r, "reverse");
let o = r.shape.length, i = w.parseAxisParam(a, r.shape);
if (o === 0)
return Os({ inputs: { x: r }, backend: n });
let u = new Vt(r.shape, r.dtype), l = n.bufferSync(r);
for (let c = 0; c < u.size; c++) {
let p = u.indexToLoc(c), d = p.slice();
i.forEach((h) => d[h] = r.shape[h] - 1 - d[h]), u.set(l.get(...d), ...p);
}
return n.makeTensorInfo(u.shape, u.dtype, u.values);
}
var Pj = { kernelName: Pi, backendName: "cpu", kernelFunc: Oj };
var zj = { kernelName: Yi, backendName: "cpu", kernelFunc: ({ inputs: e, attrs: t, backend: n }) => {
let { image: s } = e, { radians: r, fillValue: a, center: o } = t, i = n, u = w.getTypedArrayFromDType(s.dtype, w.sizeFromShape(s.shape)), [l, c, p, d] = s.shape, [h, f] = C.getImageCenter(o, c, p), m = 255, g = Math.sin(r), b = Math.cos(r), y = i.data.get(s.dataId).values;
for (let x = 0; x < l; x++) {
let k = x * p * c * d;
for (let I = 0; I < c; I++) {
let $ = I * (p * d);
for (let R = 0; R < p; R++) {
let E = R * d;
for (let P = 0; P < d; P++) {
let A = [l, I, R, P], D = A[2], T = A[1], L = (D - h) * b - (T - f) * g, W = (D - h) * g + (T - f) * b;
L = Math.round(L + h), W = Math.round(W + f);
let j = a;
if (typeof a != "number" && (P === 3 ? j = m : j = a[P]), L >= 0 && L < p && W >= 0 && W < c) {
let X = W * (p * d), Z = L * d, ne = k + X + Z + P;
j = y[ne];
}
let Y = k + $ + E + P;
u[Y] = j;
}
}
}
}
return { dataId: i.write(u, s.shape, s.dtype), shape: s.shape, dtype: s.dtype };
} };
var Lj = st(zi, (e) => {
let t = Math.floor(e);
return e - t < 0.5 ? Math.floor(e) : e - t > 0.5 ? Math.ceil(e) : t % 2 === 0 ? t : t + 1;
});
var Mj = { kernelName: zi, backendName: "cpu", kernelFunc: Lj };
function Bj(e) {
let { inputs: t, backend: n, attrs: s } = e, { indices: r, updates: a } = t, { shape: o } = s, { sliceRank: i, numUpdates: u, sliceSize: l, strides: c, outputSize: p } = C.calculateShapes(a, r, o), d = true, h = n.bufferSync(r), f = n.bufferSync(a), m = Ko(h, f, o, p, l, u, i, c, 0, d);
return n.makeTensorInfo(o, m.dtype, m.values);
}
var Vj = { kernelName: Li, backendName: "cpu", kernelFunc: Bj };
function Wj(e, t) {
let n = 0, s = e.length, r = 0;
for (; n < s; )
r = Math.floor((n + s) / 2), e[r] < t ? n = r + 1 : s = r;
return s;
}
function Uj(e, t) {
let n = 0, s = e.length, r = 0;
for (; n < s; )
r = Math.floor((n + s) / 2), e[r] <= t ? n = r + 1 : s = r;
return s;
}
function Gj(e, t, n, s, r, a) {
let o = w.getArrayFromDType("int32", n * r);
for (let i = 0; i < n; ++i) {
let u = e.slice(i * s, (i + 1) * s), l = i * r;
for (let c = 0; c < r; ++c)
o[l + c] = a === "left" ? Wj(u, t[c + l]) : Uj(u, t[c + l]);
}
return o;
}
function Hj(e) {
let { inputs: t, backend: n, attrs: s } = e, { sortedSequence: r, values: a } = t, { side: o } = s, i = n.data.get(r.dataId).values, u = n.data.get(a.dataId).values, l = Gj(i, u, r.shape[0], r.shape[1], a.shape[1], o);
return n.makeTensorInfo(a.shape, "int32", l);
}
var qj = { kernelName: Mg, backendName: "cpu", kernelFunc: Hj };
function jj(e) {
let { inputs: t, backend: n } = e, { condition: s, t: r, e: a } = t;
be([s, r, a], "select");
let o = s.shape.length, i = n.data.get(s.dataId).values, u = n.data.get(r.dataId).values, l = n.data.get(a.dataId).values, c = cn(r.dtype, a.dtype), p = w.makeZerosTypedArray(w.sizeFromShape(r.shape), c), d = 0, h = o === 0 || o > 1 || r.shape.length === 1 ? 1 : w.sizeFromShape(r.shape.slice(1));
for (let f = 0; f < i.length; f++)
for (let m = 0; m < h; m++)
i[f] === 1 ? p[d++] = u[f] : p[d++] = l[f];
return n.makeTensorInfo(r.shape, c, p);
}
var Kj = { kernelName: Mi, backendName: "cpu", kernelFunc: jj };
var Xj = C.SELU_SCALEALPHA;
var Yj = C.SELU_SCALE;
var Qj = st(Al, (e) => e >= 0 ? Yj * e : Xj * (Math.exp(e) - 1));
var Zj = { kernelName: Al, backendName: "cpu", kernelFunc: Qj };
var Jj = st(El, (e) => e < 0 ? -1 : e > 0 ? 1 : 0);
var e5 = { kernelName: El, backendName: "cpu", kernelFunc: Jj };
var t5 = st(io, (e) => Math.sin(e));
var n5 = { kernelName: io, backendName: "cpu", kernelFunc: t5 };
var s5 = st(Vi, (e) => Math.sinh(e));
var r5 = { kernelName: Vi, backendName: "cpu", kernelFunc: s5 };
var a5 = 11920928955078125e-23;
var pw = Math.log(a5) + 2;
var o5 = st(Rl, (e) => {
let t = e > -pw, n = e < pw, s = Math.exp(e), r;
return n ? r = s : t ? r = e : r = Math.log(1 + s), r;
});
var i5 = { kernelName: Rl, backendName: "cpu", kernelFunc: o5 };
function u5(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { blockShape: a, paddings: o } = s;
be([r], "spaceToBatchND");
let i = w.sizeFromShape(a), u = [[0, 0]];
u.push(...o);
for (let I = 1 + a.length; I < r.shape.length; ++I)
u.push([0, 0]);
let l = r1.kernelFunc({ inputs: { x: r }, backend: n, attrs: { paddings: u, constantValue: 0 } }), c = C.getReshaped(l.shape, a, i, false), p = C.getPermuted(c.length, a.length, false), d = C.getReshapedPermuted(l.shape, a, i, false), m = pt({ inputs: { x: l }, backend: n, attrs: { shape: c } }), y = wn({ inputs: { x: m }, backend: n, attrs: { perm: p } }), k = pt({ inputs: { x: y }, backend: n, attrs: { shape: d } });
return n.disposeIntermediateTensorInfo(l), n.disposeIntermediateTensorInfo(m), n.disposeIntermediateTensorInfo(y), k;
}
var l5 = { kernelName: Wi, backendName: "cpu", kernelFunc: u5 };
function c5(e) {
let { inputs: t, backend: n } = e, { indices: s, values: r, denseShape: a, defaultValue: o } = t;
if (a.shape.length !== 1)
throw new Error(`Dense shape must be a vector, saw:
${a.shape}`);
if (s.shape.length !== 2)
throw new Error(`Indices must be a matrix, saw:
${s.shape}`);
if (r.shape.length !== 1)
throw new Error(`Values must be a vector, saw:
${r.shape}`);
if (o.shape.length !== 0)
throw new Error(`Default value must be a scalar, saw:
${o.shape}`);
let i = n.data.get(s.dataId).values, u = n.data.get(r.dataId).values, l = n.data.get(a.dataId).values, c = n.data.get(o.dataId).values[0], [p, d, h, f, m] = EC(i, s.shape, s.dtype, u, r.dtype, l, c);
return [n.makeTensorInfo(d, s.dtype, p), n.makeTensorInfo([d[0]], r.dtype, h), n.makeTensorInfo([f.length], "bool", new Uint8Array(f.map((g) => Number(g)))), n.makeTensorInfo([m.length], s.dtype, new Int32Array(m))];
}
var d5 = { kernelName: dp, backendName: "cpu", kernelFunc: c5 };
function p5(e) {
let { inputs: t, backend: n } = e, { inputIndices: s, inputShape: r, newShape: a } = t;
if (s.shape.length !== 2)
throw new Error(`Input indices should be a matrix but received shape
${s.shape}`);
if (r.shape.length !== 1)
throw new Error(`Input shape should be a vector but received shape
${r.shape}`);
if (a.shape.length !== 1)
throw new Error(`Target shape should be a vector but received shape ${a.shape}`);
let o = Array.from(n.data.get(r.dataId).values), i = n.data.get(s.dataId).values, u = Array.from(n.data.get(a.dataId).values), [l, c, p] = RC(i, s.shape, s.dtype, o, u);
return [n.makeTensorInfo(c, s.dtype, l), n.makeTensorInfo([p.length], a.dtype, new Int32Array(p))];
}
var h5 = { kernelName: Dl, backendName: "cpu", kernelFunc: p5 };
function f5(e) {
let { inputs: t, backend: n } = e, { data: s, indices: r, segmentIds: a } = t;
if (s.shape.length < 1)
throw new Error("Data should be at least 1 dimensional but received scalar");
if (r.shape.length !== 1)
throw new Error(`Indices should be a vector but received shape
${r.shape}`);
if (a.shape.length !== 1)
throw new Error(`Segment ids should be a vector but received shape
${a.shape}`);
if (r.shape[0] !== a.shape[0])
throw new Error("segmentIds and indices should have same size.");
let o = n.data.get(s.dataId).values, i = n.data.get(r.dataId).values, u = n.data.get(a.dataId).values, [l, c] = bv(o, s.shape, s.dtype, i, u, true);
return n.makeTensorInfo(c, s.dtype, l);
}
var m5 = { kernelName: pp, backendName: "cpu", kernelFunc: f5 };
function g5(e) {
let { inputs: t, backend: n } = e, { data: s, indices: r, segmentIds: a } = t;
if (s.shape.length < 1)
throw new Error("Data should be at least 1 dimensional but received scalar");
if (r.shape.length !== 1)
throw new Error(`Indices should be a vector but received shape
${r.shape}`);
if (a.shape.length !== 1)
throw new Error(`Segment ids should be a vector but received shape
${a.shape}`);
if (r.shape[0] !== a.shape[0])
throw new Error("segmentIds and indices should have same size.");
let o = n.data.get(s.dataId).values, i = n.data.get(r.dataId).values, u = n.data.get(a.dataId).values, [l, c] = bv(o, s.shape, s.dtype, i, u);
return n.makeTensorInfo(c, s.dtype, l);
}
var b5 = { kernelName: hp, backendName: "cpu", kernelFunc: g5 };
function y5(e) {
let { inputs: t, backend: n, attrs: s } = e, { sparseIndices: r, sparseValues: a, defaultValue: o } = t, { outputShape: i } = s, { sliceRank: u, numUpdates: l, sliceSize: c, strides: p, outputSize: d } = C.calculateShapes(a, r, i), h = false, f = n.bufferSync(r), m;
switch (a.dtype) {
case "bool": {
let g = n.bufferSync(a), b = Boolean(n.data.get(o.dataId).values[0]);
m = Ko(f, g, i, d, c, l, u, p, b, h);
break;
}
case "float32": {
let g = n.bufferSync(a), b = n.data.get(o.dataId).values[0];
m = Ko(f, g, i, d, c, l, u, p, b, h);
break;
}
case "int32": {
let g = n.bufferSync(a), b = n.data.get(o.dataId).values[0];
m = Ko(f, g, i, d, c, l, u, p, b, h);
break;
}
case "string": {
let g = n.bufferSync(a), b = w.decodeString(n.data.get(o.dataId).values[0]);
m = Ko(f, g, i, d, c, l, u, p, b, h);
break;
}
default:
throw new Error(`Unsupported type ${a.dtype}`);
}
return n.makeTensorInfo(i, m.dtype, m.values);
}
var v5 = { kernelName: fp, backendName: "cpu", kernelFunc: y5 };
function x5(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { numOrSizeSplits: a, axis: o } = s, i = w.parseAxisParam(o, r.shape)[0], u = C.prepareSplitSize(r, a, i), l = new Array(r.shape.length).fill(0), c = r.shape.slice();
return u.map((p) => {
let d = [...c];
d[i] = p;
let h = ba({ inputs: { x: r }, backend: n, attrs: { begin: l, size: d } });
return l[i] += p, h;
});
}
var w5 = { kernelName: Ui, backendName: "cpu", kernelFunc: x5 };
var k5 = { kernelName: Fl, backendName: "cpu", kernelFunc: ({ inputs: e, backend: t }) => {
let { x: n } = e, s = t;
be(n, "square");
let r = s.data.get(n.dataId).values, a = new Float32Array(r.length);
for (let i = 0; i < r.length; ++i) {
let u = r[i];
a[i] = u * u;
}
return { dataId: s.write(a, n.shape, n.dtype), shape: n.shape, dtype: n.dtype };
} };
var S5 = st(go, (e, t) => {
let n = t;
return isNaN(e) ? NaN : e > 0 ? 1 : n.alpha;
});
var I5 = { kernelName: go, backendName: "cpu", kernelFunc: S5 };
function C5(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { begin: a, end: o, strides: i, beginMask: u, endMask: l, ellipsisMask: c, newAxisMask: p, shrinkAxisMask: d } = s;
be(r, "stridedSlice");
let { finalShapeSparse: h, finalShape: f, isIdentity: m, sliceDim0: g, isSimpleSlice: b, begin: y, end: v, strides: x } = kt.sliceInfo(r.shape, a, o, i, u, l, c, p, d), k;
if (m)
k = pt({ inputs: { x: r }, backend: n, attrs: { shape: f } });
else if (g || b) {
w.assert(r.shape.length >= 1, () => `Input must have rank at least 1, got: ${r.shape.length}`);
let I = kt.computeOutShape(y, v, x), $ = ba({ inputs: { x: r }, backend: n, attrs: { begin: y, size: I } });
k = pt({ inputs: { x: $ }, backend: n, attrs: { shape: f } }), n.disposeIntermediateTensorInfo($);
} else {
let I = n.bufferSync(r), $ = FC(h, I, x, y);
k = n.makeTensorInfo(f, $.dtype, $.values);
}
return k;
}
var N5 = { kernelName: Gi, backendName: "cpu", kernelFunc: C5 };
function T5(e) {
let { inputs: t, backend: n, attrs: s } = e, { separator: r, nGramWidths: a, leftPad: o, rightPad: i, padWidth: u, preserveShortSequences: l } = s, { data: c, dataSplits: p } = t, d = n.data.get(c.dataId).values, h = n.data.get(p.dataId).values, [f, m] = OC(d, h, r, a, o, i, u, l);
return [n.makeTensorInfo([f.length], "string", f), n.makeTensorInfo(p.shape, "int32", m)];
}
var $5 = { kernelName: mp, backendName: "cpu", kernelFunc: T5 };
function _5(e) {
let { inputs: t, backend: n, attrs: s } = e, { skipEmpty: r } = s, { input: a, delimiter: o } = t;
if (a.dtype !== "string")
throw new Error("Input must be of datatype string");
if (a.shape.length !== 1)
throw new Error(`Input must be a vector, got shape: ${a.shape}`);
if (o.shape.length !== 0)
throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);
let i = n.data.get(a.dataId).values, u = n.data.get(o.dataId).values[0], [l, c, p] = PC(i, u, r), d = c.length;
return [n.makeTensorInfo([d, 2], "int32", l), n.makeTensorInfo([d], "string", c), n.makeTensorInfo([2], "int32", new Int32Array(p))];
}
var A5 = { kernelName: Bg, backendName: "cpu", kernelFunc: _5 };
function E5(e) {
let { inputs: t, backend: n, attrs: s } = e, { numBuckets: r } = s, { input: a } = t;
if (a.dtype !== "string")
throw new Error("Input must be of datatype string");
if (r <= 0)
throw new Error("Number of buckets must be at least 1");
let o = n.data.get(a.dataId).values, i = zC(o, r);
return n.makeTensorInfo(a.shape, "int32", i);
}
var R5 = { kernelName: Vg, backendName: "cpu", kernelFunc: E5 };
var D5 = st(Hi, (e) => Math.tan(e));
var F5 = { kernelName: Hi, backendName: "cpu", kernelFunc: D5 };
var O5 = st(mo, (e) => Math.tanh(e));
var P5 = { kernelName: mo, backendName: "cpu", kernelFunc: O5 };
function z5(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { reps: a } = s;
be(r, "tile");
let o = MC(n.bufferSync(r), a);
return n.makeTensorInfo(o.shape, o.dtype, o.values);
}
var L5 = { kernelName: Tr, backendName: "cpu", kernelFunc: z5 };
function M5(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { k: a, sorted: o } = s;
be(r, "topk");
let i = n.data.get(r.dataId).values, [u, l] = VC(i, r.shape, r.dtype, a, o);
return [n.makeTensorInfo(u.shape, u.dtype, u.values), n.makeTensorInfo(l.shape, l.dtype, l.values)];
}
var B5 = { kernelName: qi, backendName: "cpu", kernelFunc: M5 };
function V5(e) {
let { inputs: t, attrs: n, backend: s } = e, { image: r, transforms: a } = t, { interpolation: o, fillMode: i, fillValue: u, outputShape: l } = n, [c, p, d, h] = r.shape, [f, m] = l != null ? l : [p, d], g = [c, f, m, h], b = w.computeStrides(r.shape), y = b[0], v = b[1], x = b[2], k = w.getTypedArrayFromDType(r.dtype, w.sizeFromShape(g));
k.fill(u);
let I = s.data.get(r.dataId).values, $ = s.data.get(a.dataId).values;
for (let E = 0; E < c; ++E) {
let P = a.shape[0] === 1 ? $ : $.subarray(E * 8, E * 8 + 8);
for (let A = 0; A < f; ++A)
for (let D = 0; D < m; ++D)
for (let T = 0; T < h; ++T) {
let L, W = P[6] * D + P[7] * A + 1;
if (W === 0)
continue;
let j = (P[0] * D + P[1] * A + P[2]) / W, Y = (P[3] * D + P[4] * A + P[5]) / W, X = hw(j, d, i), Z = hw(Y, p, i);
switch (o) {
case "nearest":
L = j5(I, p, d, y, v, x, E, Z, X, T, u);
break;
case "bilinear":
L = K5(I, p, d, y, v, x, E, Z, X, T, u);
break;
default:
throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${o}`);
}
let ne = E * y + A * v + D * x + T;
k[ne] = L;
}
return s.makeTensorInfo(g, r.dtype, k);
}
return { dataId: s.write(k, g, r.dtype), shape: r.shape, dtype: r.dtype };
}
var W5 = { kernelName: ji, backendName: "cpu", kernelFunc: V5 };
function hw(e, t, n) {
switch (n) {
case "reflect":
return U5(e, t);
case "wrap":
return G5(e, t);
case "nearest":
return q5(e, t);
case "constant":
default:
return H5(e, t);
}
}
function U5(e, t) {
let n = e;
if (n < 0)
if (t <= 1)
n = 0;
else {
let s = 2 * t;
n < s && (n = s * Math.trunc(-n / s) + n), n = n < -t ? n + s : -n - 1;
}
else if (n > t - 1)
if (t <= 1)
n = 0;
else {
let s = 2 * t;
n -= s * Math.trunc(n / s), n >= t && (n = s - n - 1);
}
return w.clamp(0, n, t - 1);
}
function G5(e, t) {
let n = e;
if (n < 0)
if (t <= 1)
n = 0;
else {
let s = t - 1;
n += t * (Math.trunc(-n / s) + 1);
}
else if (n > t - 1)
if (t <= 1)
n = 0;
else {
let s = t - 1;
n -= t * Math.trunc(n / s);
}
return w.clamp(0, n, t - 1);
}
function H5(e, t) {
return e;
}
function q5(e, t) {
return w.clamp(0, e, t - 1);
}
function zu(e, t, n, s, r, a, o, i, u, l, c) {
let p = o * s + i * r + u * a + l;
return 0 <= i && i < t && 0 <= u && u < n ? e[p] : c;
}
function j5(e, t, n, s, r, a, o, i, u, l, c) {
let p = Math.round(i), d = Math.round(u);
return zu(e, t, n, s, r, a, o, p, d, l, c);
}
function K5(e, t, n, s, r, a, o, i, u, l, c) {
let p = Math.floor(i), d = Math.floor(u), h = p + 1, f = d + 1, m = (f - u) * zu(e, t, n, s, r, a, o, p, d, l, c) + (u - d) * zu(e, t, n, s, r, a, o, p, f, l, c), g = (f - u) * zu(e, t, n, s, r, a, o, h, d, l, c) + (u - d) * zu(e, t, n, s, r, a, o, h, f, l, c);
return (h - i) * m + (i - p) * g;
}
function X5(e) {
let { inputs: t, attrs: n, backend: s } = e, { axis: r } = n, { x: a } = t;
be(a, "unique");
let o = s.data.get(a.dataId).values, { outputValues: i, outputShape: u, indices: l } = WC(o, r, a.shape, a.dtype);
return [s.makeTensorInfo(u, a.dtype, i), s.makeTensorInfo([l.length], "int32", l)];
}
var Y5 = { kernelName: Wg, backendName: "cpu", kernelFunc: X5 };
function Q5(e) {
let { inputs: t, backend: n, attrs: s } = e, { value: r } = t, { axis: a } = s;
a < 0 && (a += r.shape.length);
let o = r.shape.length, i = r.shape[a], u = new Array(o - 1), l = 0;
for (let h = 0; h < o; h++)
h !== a && (u[l++] = r.shape[h]);
let c = new Array(o).fill(0), p = r.shape.slice();
p[a] = 1;
let d = new Array(i);
for (let h = 0; h < d.length; h++) {
c[a] = h;
let f = ba({ inputs: { x: r }, backend: n, attrs: { begin: c, size: p } });
d[h] = pt({ inputs: { x: f }, backend: n, attrs: { shape: u } }), n.disposeIntermediateTensorInfo(f);
}
return d;
}
var Z5 = { kernelName: Ki, backendName: "cpu", kernelFunc: Q5 };
function J5(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, segmentIds: a } = t, { numSegments: o } = s;
be(r, "unsortedSegmentSum");
let i = r.shape.length, u = a.shape.length, l = [], c = [], p = i - u, d = a;
for (let f = 0; f < p; ++f) {
let m = Ud({ inputs: { input: d }, backend: n, attrs: { dim: f + 1 } });
d = m, c.push(m);
}
for (let f = 0; f < o; ++f) {
let m = w.createScalarValue(f, "int32"), g = n.makeTensorInfo([], "int32", m), b = cC({ inputs: { a: g, b: d }, backend: n }), y = kr({ inputs: { x: b }, backend: n, attrs: { dtype: "float32" } }), v = eh({ inputs: { a: y, b: r }, backend: n }), x = Zl({ inputs: { x: v }, backend: n, attrs: { axis: 0, keepDims: false } });
l.push(x), c.push(g), c.push(b), c.push(y), c.push(v), c.push(x);
}
let h = s1({ inputs: l, backend: n, attrs: { axis: 0 } });
return c.forEach((f) => n.disposeIntermediateTensorInfo(f)), h;
}
var eK = { kernelName: gp, backendName: "cpu", kernelFunc: J5 };
var tK = [tH, KU, sH, aH, eG, iH, lH, dH, hH, mH, bH, vH, wH, IH, NH, _H, EH, DH, OH, JG, zH, MH, VH, UH, ZU, nG, HH, XU, jH, XH, YH, ZH, eq, nq, rq, oq, uq, cq, pq, fq, gq, yq, xq, wq, Sq, Cq, Tq, $q, _q, Aq, Dq, qG, Oq, sG, Uq, rG, Gq, oG, Yq, Qq, Jq, uG, n6, r6, o6, u6, c6, cG, pG, YU, p6, KH, f6, g6, y6, jG, fG, gG, x6, yG, k6, C6, T6, A6, R6, F6, O6, xG, z6, M6, V6, U6, H6, j6, X6, kG, Q6, ej, rj, IG, NG, ij, cj, hj, $G, mj, bj, yj, r1, kj, XG, EG, Ij, QU, Ym, Nj, YG, QG, ZG, $j, Aj, Rj, Fj, Pj, zj, Mj, DG, Vj, qj, Kj, Zj, OG, e5, n5, r5, PG, nj, i5, l5, d5, h5, m5, b5, v5, w5, MG, k5, VG, I5, N5, $5, A5, R5, HG, Eq, F5, P5, L5, B5, W5, _G, Y5, Z5, eK, gj];
for (let e of tK)
Ol(e);
var nK = {};
Ee(nK, { assertNotComplex: () => ou, bindCanvasToFramebuffer: () => fK, bindColorTextureToFramebuffer: () => cd, bindTextureToProgramUniformSampler: () => v1, bindTextureUnit: () => g1, bindVertexBufferToProgramAttribute: () => Zm, callAndCheck: () => fe, canBeRepresented: () => a1, createFragmentShader: () => u1, createFramebuffer: () => m1, createProgram: () => l1, createStaticIndexBuffer: () => p1, createStaticVertexBuffer: () => d1, createTexture: () => h1, createVertexShader: () => i1, getBatchDim: () => ya, getExtensionOrThrow: () => Lu, getFramebufferErrorMessage: () => x1, getMaxTexturesInShader: () => I1, getNumChannels: () => pK, getProgramUniformLocation: () => y1, getProgramUniformLocationOrThrow: () => b1, getRowsCols: () => va, getShapeAs3D: () => dd, getTextureShapeFromLogicalShape: () => k1, getWebGLDisjointQueryTimerVersion: () => C1, getWebGLErrorMessage: () => o1, getWebGLMaxTextureSize: () => S1, hasExtension: () => Mn, isCapableOfRenderingToFloatTexture: () => N1, isDownloadFloatTextureEnabled: () => T1, isReshapeFree: () => al, isWebGLFenceEnabled: () => $1, isWebGLVersionEnabled: () => eg, linkProgram: () => c1, logShaderSourceAndInfoLog: () => Sv, resetMaxTextureSize: () => mK, resetMaxTexturesInShader: () => gK, unbindColorTextureFromFramebuffer: () => Jm, unbindTextureUnit: () => hK, validateFramebuffer: () => Mu, validateProgram: () => ld, validateTextureSize: () => f1 });
var Qr = {};
var rm = { alpha: false, antialias: false, premultipliedAlpha: false, preserveDrawingBuffer: false, depth: false, stencil: false, failIfMajorPerformanceCaveat: true };
function sK(e, t) {
Qr[e] = t;
}
function xs(e, t) {
if (!(e in Qr) || t != null) {
let s = aK(e, t);
if (s !== null)
Qr[e] = s;
else
return console.log("Could not get context for WebGL version", e), null;
}
let n = Qr[e];
return n == null || n.isContextLost() ? (delete Qr[e], xs(e)) : (n.disable(n.DEPTH_TEST), n.disable(n.STENCIL_TEST), n.disable(n.BLEND), n.disable(n.DITHER), n.disable(n.POLYGON_OFFSET_FILL), n.disable(n.SAMPLE_COVERAGE), n.enable(n.SCISSOR_TEST), n.enable(n.CULL_FACE), n.cullFace(n.BACK), Qr[e]);
}
function rK(e) {
if (typeof OffscreenCanvas != "undefined" && e === 2)
return new OffscreenCanvas(300, 150);
if (typeof document != "undefined")
return document.createElement("canvas");
throw new Error("Cannot create a canvas in this context");
}
function aK(e, t) {
if (e !== 1 && e !== 2)
throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");
let n = t == null ? rK(e) : t;
return n.addEventListener("webglcontextlost", (s) => {
s.preventDefault(), delete Qr[e];
}, false), e === 1 ? n.getContext("webgl", rm) || n.getContext("experimental-webgl", rm) : n.getContext("webgl2", rm);
}
function Jl(e, t) {
return [t, e];
}
function oK(e, t) {
return e * t;
}
function td(e) {
let t = w.sizeFromShape(e), n = Math.ceil(t / 4);
return w.sizeToSquarishShape(n);
}
function au(e, t) {
return [Math.max(1, Math.ceil(t / 2)), Math.max(1, Math.ceil(e / 2))];
}
function iK(e, t) {
let [n, s] = au(e, t);
return n * s * 4;
}
function kv(e, t) {
let n = e, s, r, a, o, i, u, l, c, p, d;
return K().getNumber("WEBGL_VERSION") === 2 ? (s = n.R32F, r = n.R16F, a = n.RGBA16F, o = n.RGBA32F, i = n.RED, l = 4, c = 1, p = n.HALF_FLOAT, d = n.FLOAT, u = n.RGBA8) : (s = e.RGBA, r = e.RGBA, a = e.RGBA, o = n.RGBA, i = e.RGBA, l = 4, c = 4, p = t != null ? t.HALF_FLOAT_OES : null, d = e.FLOAT, u = e.RGBA), { internalFormatFloat: s, internalFormatHalfFloat: r, internalFormatPackedHalfFloat: a, internalFormatPackedFloat: o, textureFormatFloat: i, downloadTextureFormat: u, downloadUnpackNumChannels: l, defaultNumChannels: c, textureTypeHalfFloat: p, textureTypeFloat: d };
}
function fe(e, t) {
let n = t();
return K().getBool("DEBUG") && uK(e), n;
}
function uK(e) {
let t = e.getError();
if (t !== e.NO_ERROR)
throw new Error("WebGL Error: " + o1(e, t));
}
var lK = 596e-10;
var cK = 65504;
function a1(e) {
return !!(K().getBool("WEBGL_RENDER_FLOAT32_ENABLED") || e === 0 || lK < Math.abs(e) && Math.abs(e) < cK);
}
function o1(e, t) {
switch (t) {
case e.NO_ERROR:
return "NO_ERROR";
case e.INVALID_ENUM:
return "INVALID_ENUM";
case e.INVALID_VALUE:
return "INVALID_VALUE";
case e.INVALID_OPERATION:
return "INVALID_OPERATION";
case e.INVALID_FRAMEBUFFER_OPERATION:
return "INVALID_FRAMEBUFFER_OPERATION";
case e.OUT_OF_MEMORY:
return "OUT_OF_MEMORY";
case e.CONTEXT_LOST_WEBGL:
return "CONTEXT_LOST_WEBGL";
default:
return `Unknown error code ${t}`;
}
}
function Lu(e, t) {
return Qs(e, () => e.getExtension(t), 'Extension "' + t + '" not supported on this browser.');
}
function i1(e, t) {
let n = Qs(e, () => e.createShader(e.VERTEX_SHADER), "Unable to create vertex WebGLShader.");
if (fe(e, () => e.shaderSource(n, t)), fe(e, () => e.compileShader(n)), e.getShaderParameter(n, e.COMPILE_STATUS) === false)
throw console.log(e.getShaderInfoLog(n)), new Error("Failed to compile vertex shader.");
return n;
}
function u1(e, t) {
let n = Qs(e, () => e.createShader(e.FRAGMENT_SHADER), "Unable to create fragment WebGLShader.");
if (fe(e, () => e.shaderSource(n, t)), fe(e, () => e.compileShader(n)), K().get("ENGINE_COMPILE_ONLY"))
return n;
if (e.getShaderParameter(n, e.COMPILE_STATUS) === false)
throw Sv(t, e.getShaderInfoLog(n)), new Error("Failed to compile fragment shader.");
return n;
}
var dK = /ERROR: [0-9]+:([0-9]+):/g;
function Sv(e, t) {
let n = dK.exec(t);
if (n == null) {
console.log(`Couldn't parse line number in error: ${t}`), console.log(e);
return;
}
let s = +n[1], r = e.split(`
`), a = r.length.toString().length + 2, o = r.map((p, d) => w.rightPad((d + 1).toString(), a) + p), i = 0;
for (let p = 0; p < o.length; p++)
i = Math.max(o[p].length, i);
let u = o.slice(0, s - 1), l = o.slice(s - 1, s), c = o.slice(s);
console.log(u.join(`
`)), console.log(t.split(`
`)[0]), console.log(`%c ${w.rightPad(l[0], i)}`, "border:1px solid red; background-color:#e3d2d2; color:#a61717"), console.log(c.join(`
`));
}
function l1(e) {
return Qs(e, () => e.createProgram(), "Unable to create WebGLProgram.");
}
function c1(e, t) {
if (fe(e, () => e.linkProgram(t)), !K().get("ENGINE_COMPILE_ONLY") && e.getProgramParameter(t, e.LINK_STATUS) === false)
throw console.log(e.getProgramInfoLog(t)), new Error("Failed to link vertex and fragment shaders.");
}
function ld(e, t) {
if (fe(e, () => e.validateProgram(t)), e.getProgramParameter(t, e.VALIDATE_STATUS) === false)
throw console.log(e.getProgramInfoLog(t)), new Error("Shader program validation failed.");
}
function d1(e, t) {
let n = Qs(e, () => e.createBuffer(), "Unable to create WebGLBuffer");
return fe(e, () => e.bindBuffer(e.ARRAY_BUFFER, n)), fe(e, () => e.bufferData(e.ARRAY_BUFFER, t, e.STATIC_DRAW)), n;
}
function p1(e, t) {
let n = Qs(e, () => e.createBuffer(), "Unable to create WebGLBuffer");
return fe(e, () => e.bindBuffer(e.ELEMENT_ARRAY_BUFFER, n)), fe(e, () => e.bufferData(e.ELEMENT_ARRAY_BUFFER, t, e.STATIC_DRAW)), n;
}
function pK() {
return K().getNumber("WEBGL_VERSION") === 2 ? 1 : 4;
}
function h1(e) {
return Qs(e, () => e.createTexture(), "Unable to create WebGLTexture.");
}
function f1(e, t) {
let n = K().getNumber("WEBGL_MAX_TEXTURE_SIZE");
if (e <= 0 || t <= 0) {
let s = `[${e}x${t}]`;
throw new Error("Requested texture size " + s + " is invalid.");
}
if (e > n || t > n) {
let s = `[${e}x${t}]`, r = `[${n}x${n}]`;
throw new Error("Requested texture size " + s + " greater than WebGL maximum on this browser / GPU " + r + ".");
}
}
function m1(e) {
return Qs(e, () => e.createFramebuffer(), "Unable to create WebGLFramebuffer.");
}
function Zm(e, t, n, s, r, a, o) {
let i = e.getAttribLocation(t, n);
return i === -1 ? false : (fe(e, () => e.bindBuffer(e.ARRAY_BUFFER, s)), fe(e, () => e.vertexAttribPointer(i, r, e.FLOAT, false, a, o)), fe(e, () => e.enableVertexAttribArray(i)), true);
}
function g1(e, t, n) {
w1(e, n), fe(e, () => e.activeTexture(e.TEXTURE0 + n)), fe(e, () => e.bindTexture(e.TEXTURE_2D, t));
}
function hK(e, t) {
w1(e, t), fe(e, () => e.activeTexture(e.TEXTURE0 + t)), fe(e, () => e.bindTexture(e.TEXTURE_2D, null));
}
function b1(e, t, n) {
return Qs(e, () => e.getUniformLocation(t, n), 'uniform "' + n + '" not present in program.');
}
function y1(e, t, n) {
return e.getUniformLocation(t, n);
}
function v1(e, t, n, s) {
fe(e, () => g1(e, t, s)), fe(e, () => e.uniform1i(n, s));
}
function fK(e) {
fe(e, () => e.bindFramebuffer(e.FRAMEBUFFER, null)), fe(e, () => e.viewport(0, 0, e.canvas.width, e.canvas.height)), fe(e, () => e.scissor(0, 0, e.canvas.width, e.canvas.height));
}
function cd(e, t, n) {
fe(e, () => e.bindFramebuffer(e.FRAMEBUFFER, n)), fe(e, () => e.framebufferTexture2D(e.FRAMEBUFFER, e.COLOR_ATTACHMENT0, e.TEXTURE_2D, t, 0));
}
function Jm(e, t) {
fe(e, () => e.bindFramebuffer(e.FRAMEBUFFER, t)), fe(e, () => e.framebufferTexture2D(e.FRAMEBUFFER, e.COLOR_ATTACHMENT0, e.TEXTURE_2D, null, 0));
}
function Mu(e) {
let t = e.checkFramebufferStatus(e.FRAMEBUFFER);
if (t !== e.FRAMEBUFFER_COMPLETE)
throw new Error("Error binding framebuffer: " + x1(e, t));
}
function x1(e, t) {
switch (t) {
case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
return "FRAMEBUFFER_INCOMPLETE_ATTACHMENT";
case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
return "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";
case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
return "FRAMEBUFFER_INCOMPLETE_DIMENSIONS";
case e.FRAMEBUFFER_UNSUPPORTED:
return "FRAMEBUFFER_UNSUPPORTED";
default:
return `unknown error ${t}`;
}
}
function Qs(e, t, n) {
let s = fe(e, () => t());
if (s == null)
throw new Error(n);
return s;
}
function w1(e, t) {
let n = e.MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1, s = t + e.TEXTURE0;
if (s < e.TEXTURE0 || s > n) {
let r = `[gl.TEXTURE0, gl.TEXTURE${n}]`;
throw new Error(`textureUnit must be in ${r}.`);
}
}
function ya(e, t = 2) {
return w.sizeFromShape(e.slice(0, e.length - t));
}
function va(e) {
if (e.length === 0)
throw Error("Cannot get rows and columns of an empty shape array.");
return [e.length > 1 ? e[e.length - 2] : 1, e[e.length - 1]];
}
function dd(e) {
let t = [1, 1, 1];
return e.length === 0 || e.length === 1 && e[0] === 1 || (t = [ya(e), ...va(e)]), t;
}
function k1(e, t = false) {
let n = K().getNumber("WEBGL_MAX_TEXTURE_SIZE");
t && (n = n * 2, e = e.map((r, a) => a >= e.length - 2 ? w.nearestLargerEven(e[a]) : e[a]), e.length === 1 && (e = [2, e[0]])), e.length !== 2 && (e = w.squeezeShape(e).newShape);
let s = w.sizeFromShape(e);
if (e.length <= 1 && s <= n)
return [1, s];
if (e.length === 2 && e[0] <= n && e[1] <= n)
return e;
if (e.length === 3 && e[0] * e[1] <= n && e[2] <= n)
return [e[0] * e[1], e[2]];
if (e.length === 3 && e[0] <= n && e[1] * e[2] <= n)
return [e[0], e[1] * e[2]];
if (e.length === 4 && e[0] * e[1] * e[2] <= n && e[3] <= n)
return [e[0] * e[1] * e[2], e[3]];
if (e.length === 4 && e[0] <= n && e[1] * e[2] * e[3] <= n)
return [e[0], e[1] * e[2] * e[3]];
if (t) {
let r = ya(e), a = 2, o = 2;
return e.length && ([a, o] = va(e)), s = r * (a / 2) * (o / 2), w.sizeToSquarishShape(s).map((i) => i * 2);
}
return w.sizeToSquarishShape(s);
}
function nd(e) {
return e % 2 === 0;
}
function al(e, t) {
if (e = e.slice(-2), t = t.slice(-2), w.arraysEqual(e, t) || !e.length || !t.length || e[0] === 0 || e[1] === 0 || t[0] === 0 || t[1] === 0)
return true;
if (e.length !== t.length) {
let n = e.slice(-1)[0], s = t.slice(-1)[0];
if (n === s || nd(n) && nd(s) && (e[0] === 1 || t[0] === 1))
return true;
}
return e[1] === t[1] && nd(e[0]) && nd(t[0]);
}
var pd;
var hd;
function S1(e) {
if (pd == null) {
let t = xs(e);
pd = t.getParameter(t.MAX_TEXTURE_SIZE);
}
return pd;
}
function mK() {
pd = null;
}
function gK() {
hd = null;
}
function I1(e) {
if (hd == null) {
let t = xs(e);
hd = t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);
}
return Math.min(16, hd);
}
function C1(e) {
if (e === 0)
return 0;
let t, n = xs(e);
return Mn(n, "EXT_disjoint_timer_query_webgl2") && e === 2 ? t = 2 : Mn(n, "EXT_disjoint_timer_query") ? t = 1 : t = 0, t;
}
function Mn(e, t) {
return e.getExtension(t) != null;
}
function eg(e) {
try {
if (xs(e) != null)
return true;
} catch (t) {
return console.log("Error when getting WebGL context: ", t), false;
}
return false;
}
function N1(e) {
if (e === 0)
return false;
let t = xs(e);
if (e === 1) {
if (!Mn(t, "OES_texture_float"))
return false;
} else if (!Mn(t, "EXT_color_buffer_float"))
return false;
return tg(t);
}
function T1(e) {
if (e === 0)
return false;
let t = xs(e);
if (e === 1) {
if (!Mn(t, "OES_texture_float") || !Mn(t, "WEBGL_color_buffer_float"))
return false;
} else {
if (Mn(t, "EXT_color_buffer_float"))
return tg(t);
let s = "EXT_color_buffer_half_float";
if (Mn(t, s)) {
let r = t.getExtension(s);
return bK(t, r);
}
return false;
}
return tg(t);
}
function tg(e) {
let t = kv(e), n = e.createTexture();
e.bindTexture(e.TEXTURE_2D, n);
let s = 1, r = 1;
e.texImage2D(e.TEXTURE_2D, 0, t.internalFormatFloat, s, r, 0, t.textureFormatFloat, t.textureTypeFloat, null);
let a = e.createFramebuffer();
e.bindFramebuffer(e.FRAMEBUFFER, a), e.framebufferTexture2D(e.FRAMEBUFFER, e.COLOR_ATTACHMENT0, e.TEXTURE_2D, n, 0);
let o = e.checkFramebufferStatus(e.FRAMEBUFFER) === e.FRAMEBUFFER_COMPLETE;
return e.bindTexture(e.TEXTURE_2D, null), e.bindFramebuffer(e.FRAMEBUFFER, null), e.deleteTexture(n), e.deleteFramebuffer(a), o;
}
function bK(e, t) {
let n = kv(e, t), s = e.createTexture();
e.bindTexture(e.TEXTURE_2D, s);
let r = 1, a = 1;
e.texImage2D(e.TEXTURE_2D, 0, n.internalFormatHalfFloat, r, a, 0, n.textureFormatFloat, n.textureTypeHalfFloat, null);
let o = e.createFramebuffer();
e.bindFramebuffer(e.FRAMEBUFFER, o), e.framebufferTexture2D(e.FRAMEBUFFER, e.COLOR_ATTACHMENT0, e.TEXTURE_2D, s, 0);
let i = e.checkFramebufferStatus(e.FRAMEBUFFER) === e.FRAMEBUFFER_COMPLETE;
return e.bindTexture(e.TEXTURE_2D, null), e.bindFramebuffer(e.FRAMEBUFFER, null), e.deleteTexture(s), e.deleteFramebuffer(o), i;
}
function $1(e) {
return e !== 2 ? false : xs(e).fenceSync != null;
}
function ou(e, t) {
Array.isArray(e) || (e = [e]), e.forEach((n) => {
n != null && w.assert(n.dtype !== "complex64", () => `${t} does not support complex64 tensors in the WebGL backend.`);
});
}
var Ne = K();
Ne.registerFlag("HAS_WEBGL", () => Ne.getNumber("WEBGL_VERSION") > 0);
Ne.registerFlag("WEBGL_VERSION", () => eg(2) ? 2 : eg(1) ? 1 : 0);
Ne.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS", () => false);
Ne.registerFlag("WEBGL_BUFFER_SUPPORTED", () => Ne.get("WEBGL_VERSION") === 2);
Ne.registerFlag("WEBGL_CPU_FORWARD", () => true);
Ne.registerFlag("WEBGL_FORCE_F16_TEXTURES", () => false);
Ne.registerFlag("WEBGL_PACK", () => Ne.getBool("HAS_WEBGL"));
Ne.registerFlag("WEBGL_PACK_NORMALIZATION", () => Ne.getBool("WEBGL_PACK"));
Ne.registerFlag("WEBGL_PACK_CLIP", () => Ne.getBool("WEBGL_PACK"));
Ne.registerFlag("WEBGL_PACK_DEPTHWISECONV", () => Ne.getBool("WEBGL_PACK"));
Ne.registerFlag("WEBGL_PACK_BINARY_OPERATIONS", () => Ne.getBool("WEBGL_PACK"));
Ne.registerFlag("WEBGL_PACK_UNARY_OPERATIONS", () => Ne.getBool("WEBGL_PACK"));
Ne.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS", () => Ne.getBool("WEBGL_PACK"));
Ne.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS", () => Ne.getBool("WEBGL_PACK"));
Ne.registerFlag("WEBGL_PACK_REDUCE", () => Ne.getBool("WEBGL_PACK"));
Ne.registerFlag("WEBGL_LAZILY_UNPACK", () => Ne.getBool("WEBGL_PACK"));
Ne.registerFlag("WEBGL_CONV_IM2COL", () => Ne.getBool("WEBGL_PACK"));
Ne.registerFlag("WEBGL_MAX_TEXTURE_SIZE", () => S1(Ne.getNumber("WEBGL_VERSION")));
Ne.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER", () => I1(Ne.getNumber("WEBGL_VERSION")));
Ne.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION", () => {
let e = Ne.getNumber("WEBGL_VERSION");
return e === 0 ? 0 : C1(e);
});
Ne.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE", () => Ne.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") > 0 && !vp.isMobile());
Ne.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE", () => N1(Ne.getNumber("WEBGL_VERSION")));
Ne.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED", () => Ne.getBool("WEBGL_FORCE_F16_TEXTURES") ? false : Ne.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));
Ne.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED", () => T1(Ne.getNumber("WEBGL_VERSION")));
Ne.registerFlag("WEBGL_FENCE_API_ENABLED", () => $1(Ne.getNumber("WEBGL_VERSION")));
Ne.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM", () => Ne.getBool("WEBGL_RENDER_FLOAT32_ENABLED") ? 4 : 0);
Ne.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD", () => -1, (e) => {
if (e < 0 && e !== -1)
throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`);
});
Ne.registerFlag("WEBGL_FLUSH_THRESHOLD", () => vp.isMobile() ? 1 : -1, (e) => {
if (e < 0 && e !== -1)
throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`);
});
Ne.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD", () => 128);
Ne.registerFlag("WEBGL_USE_SHAPES_UNIFORMS", () => false);
Ne.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD", () => 1e5);
Ne.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD", () => 128);
function mn() {
let e, t, n, s, r, a, o, i, u, l;
return K().getNumber("WEBGL_VERSION") === 2 ? (e = "#version 300 es", t = "in", n = "out", s = "in", r = "texture", a = "outputColor", o = "out vec4 outputColor;", i = `
bool isnan_custom(float val) {
uint floatToUint = floatBitsToUint(val);
return (floatToUint & 0x7fffffffu) > 0x7f800000u;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan_custom(val.x),
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
}
#define isnan(value) isnan_custom(value)
`, u = "", l = `
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
}
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`) : (e = "", t = "attribute", n = "varying", s = "varying", r = "texture2D", a = "gl_FragColor", o = "", i = `
#define isnan(value) isnan_custom(value)
bool isnan_custom(float val) {
return (val > 0. || val < 1. || val == 0.) ? false : true;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
}
`, u = `
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
`, l = `
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`), { version: e, attribute: t, varyingVs: n, varyingFs: s, texture2D: r, output: a, defineOutput: o, defineSpecialNaN: i, defineSpecialInf: u, defineRound: l };
}
function wo(e, t, n = "index") {
let s = w.computeStrides(t);
return s.map((r, a) => {
let o = `int ${e[a]} = ${n} / ${r}`, i = a === s.length - 1 ? `int ${e[a + 1]} = ${n} - ${e[a]} * ${r}` : `index -= ${e[a]} * ${r}`;
return `${o}; ${i};`;
}).join("");
}
function th(e, t, n = "index") {
let s = w.computeStrides(t);
return s.map((r, a) => {
let o = `int ${e[a]} = ${n} / outShapeStrides[${a}]`, i = a === s.length - 1 ? `int ${e[a + 1]} = ${n} - ${e[a]} * outShapeStrides[${a}]` : `index -= ${e[a]} * outShapeStrides[${a}]`;
return `${o}; ${i};`;
}).join("");
}
function yK(e, t) {
let n = e.length, s = e.map((a) => `${t}[${a}]`), r = new Array(n - 1);
r[n - 2] = s[n - 1];
for (let a = n - 3; a >= 0; --a)
r[a] = `(${r[a + 1]} * ${s[a + 1]})`;
return r;
}
function vK(e, t, n = "index") {
let s = e.map((a, o) => o), r = yK(s, t);
return r.map((a, o) => {
let i = `int ${e[o]} = ${n} / ${r[o]}`, u = o === r.length - 1 ? `int ${e[o + 1]} = ${n} - ${e[o]} * ${r[o]}` : `index -= ${e[o]} * ${r[o]}`;
return `${i}; ${u};`;
}).join("");
}
function Iv(e) {
let t = w.computeStrides(e).map((n) => n.toString());
return `
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
`;
}
function Cv() {
return `
int getFlatIndex(ivec3 coords) {
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
}
`;
}
var _1 = `
const float FLOAT_MAX = 1.70141184e38;
const float FLOAT_MIN = 1.17549435e-38;
lowp vec4 encode_float(highp float v) {
if (isnan(v)) {
return vec4(255, 255, 255, 255);
}
highp float av = abs(v);
if(av < FLOAT_MIN) {
return vec4(0.0, 0.0, 0.0, 0.0);
} else if(v > FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
} else if(v < -FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
}
highp vec4 c = vec4(0,0,0,0);
highp float e = floor(log2(av));
highp float m = exp2(fract(log2(av))) - 1.0;
c[2] = floor(128.0 * m);
m -= c[2] / 128.0;
c[1] = floor(32768.0 * m);
m -= c[1] / 32768.0;
c[0] = floor(8388608.0 * m);
highp float ebias = e + 127.0;
c[3] = floor(ebias / 2.0);
ebias -= c[3] * 2.0;
c[2] += floor(ebias) * 128.0;
c[3] += 128.0 * step(0.0, -v);
return c / 255.0;
}
`;
var { getBroadcastDims: A1 } = C;
function xK(e, t, n) {
let s = [];
if (e.forEach((h) => {
let f = w.sizeFromShape(h.shapeInfo.logicalShape);
if (h.shapeInfo.isUniform ? s.push(`uniform float ${h.name}${f > 1 ? `[${f}]` : ""};`) : (s.push(`uniform sampler2D ${h.name};`), s.push(`uniform int offset${h.name};`)), n.enableShapeUniforms) {
let { uniformShape: m } = Nv(n.packedInputs, h.shapeInfo.logicalShape, h.shapeInfo.texShape);
switch (m.length) {
case 1:
s.push(`uniform int ${h.name}Shape;`);
break;
case 2:
s.push(`uniform ivec2 ${h.name}Shape;`);
break;
case 3:
s.push(`uniform ivec3 ${h.name}Shape;`);
break;
case 4:
s.push(`uniform ivec4 ${h.name}Shape;`);
break;
default:
break;
}
s.push(`uniform ivec2 ${h.name}TexShape;`);
}
}), n.enableShapeUniforms) {
switch (t.logicalShape.length) {
case 1:
s.push("uniform int outShape;");
break;
case 2:
s.push("uniform ivec2 outShape;"), s.push("uniform int outShapeStrides;");
break;
case 3:
s.push("uniform ivec3 outShape;"), s.push("uniform ivec2 outShapeStrides;");
break;
case 4:
s.push("uniform ivec4 outShape;"), s.push("uniform ivec3 outShapeStrides;");
break;
default:
break;
}
s.push("uniform ivec2 outTexShape;");
}
n.customUniforms && n.customUniforms.forEach((h) => {
s.push(`uniform ${h.type} ${h.name}${h.arrayIndex ? `[${h.arrayIndex}]` : ""};`);
});
let r = s.join(`
`), a = e.map((h) => wK(h, t, n.packedInputs, n.enableShapeUniforms)).join(`
`), o = t.texShape, i = mn(), u = IK(i), l, c, p = TK(i);
return t.isPacked ? (l = kK(t.logicalShape, o, n.enableShapeUniforms), c = NK(i)) : (l = SK(t.logicalShape, o, n.enableShapeUniforms), c = CK(i)), n.packedInputs && (p += EK), [p, u, c, r, l, a, n.userCode].join(`
`);
}
function iu(e, t = false) {
let n = e.shapeInfo.logicalShape;
switch (n.length) {
case 0:
return UK(e, t);
case 1:
return HK(e, t);
case 2:
return jK(e, t);
case 3:
return XK(e, t);
case 4:
return QK(e, t);
case 5:
return ZK(e);
case 6:
return JK(e);
default:
throw new Error(`${n.length}-D input sampling is not yet supported`);
}
}
function E1(e, t) {
switch (e.shapeInfo.logicalShape.length) {
case 0:
return WK(e);
case 1:
return GK(e, t);
case 2:
return qK(e, t);
case 3:
return KK(e, t);
default:
return YK(e, t);
}
}
function wK(e, t, n = false, s) {
let r = "";
n ? r += E1(e, s) : r += iu(e, s);
let a = e.shapeInfo.logicalShape, o = t.logicalShape;
return a.length <= o.length && (n ? r += eX(e, t) : r += tX(e, t)), r;
}
function kK(e, t, n) {
switch (e.length) {
case 0:
return R1();
case 1:
return RK(e, t, n);
case 2:
return BK(e, t, n);
case 3:
return FK(e, t, n);
default:
return PK(e, t, n);
}
}
function SK(e, t, n) {
switch (e.length) {
case 0:
return R1();
case 1:
return DK(e, t, n);
case 2:
return VK(e, t, n);
case 3:
return OK(e, t, n);
case 4:
return zK(e, t, n);
case 5:
return LK(e, t);
case 6:
return MK(e, t);
default:
throw new Error(`${e.length}-D output sampling is not yet supported`);
}
}
function IK(e) {
return `
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
}
`;
}
function CK(e) {
return `
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
}
`;
}
function NK(e) {
return `
void setOutput(vec4 val) {
${e.output} = val;
}
`;
}
function TK(e) {
return `${e.version}
precision highp float;
precision highp int;
precision highp sampler2D;
${e.varyingFs} vec2 resultUV;
${e.defineOutput}
const vec2 halfCR = vec2(0.5, 0.5);
struct ivec5
{
int x;
int y;
int z;
int w;
int u;
};
struct ivec6
{
int x;
int y;
int z;
int w;
int u;
int v;
};
uniform float NAN;
${e.defineSpecialNaN}
${e.defineSpecialInf}
${e.defineRound}
int imod(int x, int y) {
return x - y * (x / y);
}
int idiv(int a, int b, float sign) {
int res = a / b;
int mod = imod(a, b);
if (sign < 0. && mod != 0) {
res -= 1;
}
return res;
}
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
#define HASHSCALE1 443.8975
float random(float seed){
vec2 p = resultUV * seed;
vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);
}
${$K}
${_K}
${AK}
`;
}
var $K = `
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
int texelIndex = index / 2;
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`;
var _K = `
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
int texNumC, int row, int col) {
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`;
var AK = `
vec2 packedUVfrom3D(int texNumR, int texNumC,
int texelsInBatch, int texelsInLogicalRow, int b,
int row, int col) {
int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`;
var EK = `
float getChannel(vec4 frag, vec2 innerDims) {
vec2 modCoord = mod(innerDims, 2.);
return modCoord.x == 0. ?
(modCoord.y == 0. ? frag.r : frag.g) :
(modCoord.y == 0. ? frag.b : frag.a);
}
float getChannel(vec4 frag, int dim) {
float modCoord = mod(float(dim), 2.);
return modCoord == 0. ? frag.r : frag.g;
}
`;
function R1() {
return `
int getOutputCoords() {
return 0;
}
`;
}
function RK(e, t, n) {
let s = [Math.ceil(t[0] / 2), Math.ceil(t[1] / 2)];
return s[0] === 1 ? n ? `
int getOutputCoords() {
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
}
` : `
int getOutputCoords() {
return 2 * int(resultUV.x * ${s[1]}.0);
}
` : s[1] === 1 ? n ? `
int getOutputCoords() {
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
}
` : `
int getOutputCoords() {
return 2 * int(resultUV.y * ${s[0]}.0);
}
` : n ? `
int getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);
}
` : `
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
return 2 * (resTexRC.x * ${s[1]} + resTexRC.y);
}
`;
}
function DK(e, t, n) {
return t[0] === 1 ? n ? `
int getOutputCoords() {
return int(resultUV.x * float(outTexShape[1]));
}
` : `
int getOutputCoords() {
return int(resultUV.x * ${t[1]}.0);
}
` : t[1] === 1 ? n ? `
int getOutputCoords() {
return int(resultUV.y * float(outTexShape[0]));
}
` : `
int getOutputCoords() {
return int(resultUV.y * ${t[0]}.0);
}
` : n ? `
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
return resTexRC.x * outTexShape[1] + resTexRC.y;
}
` : `
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
return resTexRC.x * ${t[1]} + resTexRC.y;
}
`;
}
function FK(e, t, n) {
if (n)
return `
ivec3 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int b = index / texelsInBatch;
index -= b * texelsInBatch;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec3(b, r, c);
}
`;
let s = [Math.ceil(t[0] / 2), Math.ceil(t[1] / 2)], r = Math.ceil(e[2] / 2), a = r * Math.ceil(e[1] / 2);
return `
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
int index = resTexRC.x * ${s[1]} + resTexRC.y;
int b = index / ${a};
index -= b * ${a};
int r = 2 * (index / ${r});
int c = imod(index, ${r}) * 2;
return ivec3(b, r, c);
}
`;
}
function OK(e, t, n) {
if (n)
return `
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
${th(["r", "c", "d"], e)}
return ivec3(r, c, d);
}
`;
let s = wo(["r", "c", "d"], e);
return `
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${s}
return ivec3(r, c, d);
}
`;
}
function PK(e, t, n) {
if (n)
return `
ivec4 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));
int texelsInBatchN = texelsInBatch * outShape[1];
int b2 = index / texelsInBatchN;
index -= b2 * texelsInBatchN;
int b = index / texelsInBatch;
index -= b * texelsInBatch;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec4(b2, b, r, c);
}
`;
let s = [Math.ceil(t[0] / 2), Math.ceil(t[1] / 2)], r = Math.ceil(e[e.length - 1] / 2), a = r * Math.ceil(e[e.length - 2] / 2), o = a, i = "", u = "b, r, c";
for (let l = 2; l < e.length - 1; l++)
o *= e[e.length - l - 1], i = `
int b${l} = index / ${o};
index -= b${l} * ${o};
` + i, u = `b${l}, ` + u;
return `
ivec${e.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
int index = resTexRC.x * ${s[1]} + resTexRC.y;
${i}
int b = index / ${a};
index -= b * ${a};
int r = 2 * (index / ${r});
int c = imod(index, ${r}) * 2;
return ivec${e.length}(${u});
}
`;
}
function zK(e, t, n) {
if (n)
return `
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
${th(["r", "c", "d", "d2"], e)}
return ivec4(r, c, d, d2);
}
`;
let s = wo(["r", "c", "d", "d2"], e);
return `
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${s}
return ivec4(r, c, d, d2);
}
`;
}
function LK(e, t) {
let n = wo(["r", "c", "d", "d2", "d3"], e);
return `
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
`;
}
function MK(e, t) {
let n = wo(["r", "c", "d", "d2", "d3", "d4"], e);
return `
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
`;
}
function BK(e, t, n) {
let s = [Math.ceil(t[0] / 2), Math.ceil(t[1] / 2)];
if (w.arraysEqual(e, t))
return n ? `
ivec2 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));
}
` : `
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${s[0]}, ${s[1]}));
}
`;
let r = Math.ceil(e[1] / 2);
return n ? `
ivec2 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec2(r, c);
}
` : `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
int index = resTexRC.x * ${s[1]} + resTexRC.y;
int r = 2 * (index / ${r});
int c = imod(index, ${r}) * 2;
return ivec2(r, c);
}
`;
}
function VK(e, t, n) {
return w.arraysEqual(e, t) ? n ? `
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
}
` : `
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
}
` : e[1] === 1 ? n ? `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(index, 0);
}
` : `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(index, 0);
}
` : e[0] === 1 ? n ? `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(0, index);
}
` : `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(0, index);
}
` : n ? `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
int r = index / outShape[1];
int c = index - r * outShape[1];
return ivec2(r, c);
}
` : `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
int r = index / ${e[1]};
int c = index - r * ${e[1]};
return ivec2(r, c);
}
`;
}
function ko(e) {
return `offset${e}`;
}
function WK(e) {
let t = e.name, n = "get" + t.charAt(0).toUpperCase() + t.slice(1), s = mn();
return `
vec4 ${n}() {
return ${s.texture2D}(${t}, halfCR);
}
`;
}
function UK(e, t) {
let n = e.name, s = "get" + n.charAt(0).toUpperCase() + n.slice(1);
if (e.shapeInfo.isUniform)
return `float ${s}() {return ${n};}`;
let [r, a] = e.shapeInfo.texShape;
if (r === 1 && a === 1)
return `
float ${s}() {
return sampleTexture(${n}, halfCR);
}
`;
let o = ko(n);
if (t)
return `
float ${s}() {
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${o});
return sampleTexture(${n}, uv);
}
`;
let [i, u] = e.shapeInfo.texShape;
return `
float ${s}() {
vec2 uv = uvFromFlat(${i}, ${u}, ${o});
return sampleTexture(${n}, uv);
}
`;
}
function GK(e, t) {
let n = e.name, s = "get" + n.charAt(0).toUpperCase() + n.slice(1), r = e.shapeInfo.texShape, a = mn();
if (t)
return `
vec4 ${s}(int index) {
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
vec2 uv = packedUVfrom1D(
packedTexShape[0], packedTexShape[1], index);
return ${a.texture2D}(${n}, uv);
}
`;
let o = [Math.ceil(r[0] / 2), Math.ceil(r[1] / 2)];
return `
vec4 ${s}(int index) {
vec2 uv = packedUVfrom1D(
${o[0]}, ${o[1]}, index);
return ${a.texture2D}(${n}, uv);
}
`;
}
function HK(e, t) {
let n = e.name, s = "get" + n.charAt(0).toUpperCase() + n.slice(1);
if (e.shapeInfo.isUniform)
return `
float ${s}(int index) {
${uu(e)}
}
`;
let r = e.shapeInfo.texShape, a = r[0], o = r[1];
if (o === 1 && a === 1)
return `
float ${s}(int index) {
return sampleTexture(${n}, halfCR);
}
`;
let i = ko(n);
return o === 1 ? t ? `
float ${s}(int index) {
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / float(${n}TexShape[0]));
return sampleTexture(${n}, uv);
}
` : `
float ${s}(int index) {
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / ${a}.0);
return sampleTexture(${n}, uv);
}
` : a === 1 ? t ? `
float ${s}(int index) {
vec2 uv = vec2((float(index + ${i}) + 0.5) / float(${n}TexShape[1]), 0.5);
return sampleTexture(${n}, uv);
}
` : `
float ${s}(int index) {
vec2 uv = vec2((float(index + ${i}) + 0.5) / ${o}.0, 0.5);
return sampleTexture(${n}, uv);
}
` : t ? `
float ${s}(int index) {
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${i});
return sampleTexture(${n}, uv);
}
` : `
float ${s}(int index) {
vec2 uv = uvFromFlat(${a}, ${o}, index + ${i});
return sampleTexture(${n}, uv);
}
`;
}
function qK(e, t) {
let n = e.shapeInfo.logicalShape, s = e.name, r = "get" + s.charAt(0).toUpperCase() + s.slice(1), a = e.shapeInfo.texShape, o = a[0], i = a[1], u = mn();
if (a != null && w.arraysEqual(n, a))
return t ? `
vec4 ${r}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);
return ${u.texture2D}(${s}, uv);
}
` : `
vec4 ${r}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}.0, ${o}.0);
return ${u.texture2D}(${s}, uv);
}
`;
if (t)
return `
vec4 ${r}(int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${s}TexShape[0]) / 2.0), ceil(float(${s}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${s}Shape[1]) / 2.0));
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
return ${u.texture2D}(${s}, uv);
}
`;
let l = [Math.ceil(a[0] / 2), Math.ceil(a[1] / 2)], c = Math.ceil(n[1] / 2);
return `
vec4 ${r}(int row, int col) {
vec2 uv = packedUVfrom2D(${c}, ${l[0]}, ${l[1]}, row, col);
return ${u.texture2D}(${s}, uv);
}
`;
}
function jK(e, t) {
let n = e.shapeInfo.logicalShape, s = e.name, r = "get" + s.charAt(0).toUpperCase() + s.slice(1), a = e.shapeInfo.texShape;
if (a != null && w.arraysEqual(n, a)) {
if (t)
return `
float ${r}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);
return sampleTexture(${s}, uv);
}
`;
let d = a[0], h = a[1];
return `
float ${r}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${h}.0, ${d}.0);
return sampleTexture(${s}, uv);
}
`;
}
let { newShape: o, keptDims: i } = w.squeezeShape(n), u = o;
if (u.length < n.length) {
let d = lu(e, u), h = ["row", "col"];
return `
${iu(d, t)}
float ${r}(int row, int col) {
return ${r}(${cu(h, i)});
}
`;
}
if (e.shapeInfo.isUniform)
return `
float ${r}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));
${uu(e)}
}
`;
let l = a[0], c = a[1], p = ko(s);
return c === 1 ? t ? `
float ${r}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${s}Shape[1], 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / float(${s}TexShape[0]));
return sampleTexture(${s}, uv);
}
` : `
float ${r}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${n[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);
return sampleTexture(${s}, uv);
}
` : l === 1 ? t ? `
float ${r}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${s}Shape[1], 1, 1));
vec2 uv = vec2((index + 0.5) / float(${s}TexShape[1]), 0.5);
return sampleTexture(${s}, uv);
}
` : `
float ${r}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${n[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);
return sampleTexture(${s}, uv);
}
` : t ? `
float ${r}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${s}Shape[1] + col + ${p};
vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index);
return sampleTexture(${s}, uv);
}
` : `
float ${r}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${n[1]} + col + ${p};
vec2 uv = uvFromFlat(${l}, ${c}, index);
return sampleTexture(${s}, uv);
}
`;
}
function KK(e, t) {
let n = e.shapeInfo.logicalShape, s = e.name, r = "get" + s.charAt(0).toUpperCase() + s.slice(1), a = e.shapeInfo.texShape, o = [Math.ceil(a[0] / 2), Math.ceil(a[1] / 2)];
if (n[0] === 1) {
let d = n.slice(1), h = [1, 2], f = lu(e, d), m = ["b", "row", "col"];
return `
${E1(f, t)}
vec4 ${r}(int b, int row, int col) {
return ${r}(${cu(m, h)});
}
`;
}
let i = mn();
if (t)
return `
vec4 ${r}(int b, int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${s}TexShape[0]) / 2.0), ceil(float(${s}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${s}Shape[2]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${s}Shape[1]) / 2.0));
vec2 uv = packedUVfrom3D(
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
return ${i.texture2D}(${s}, uv);
}
`;
let u = o[0], l = o[1], c = Math.ceil(n[2] / 2), p = c * Math.ceil(n[1] / 2);
return `
vec4 ${r}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${u}, ${l}, ${p}, ${c}, b, row, col);
return ${i.texture2D}(${s}, uv);
}
`;
}
function XK(e, t) {
let n = e.shapeInfo.logicalShape, s = e.name, r = "get" + s.charAt(0).toUpperCase() + s.slice(1), a = n[1] * n[2], o = n[2], { newShape: i, keptDims: u } = w.squeezeShape(n), l = i;
if (l.length < n.length) {
let m = lu(e, l), g = ["row", "col", "depth"];
return `
${iu(m, t)}
float ${r}(int row, int col, int depth) {
return ${r}(${cu(g, u)});
}
`;
}
if (e.shapeInfo.isUniform)
return `
float ${r}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${a}, ${o}, 1)));
${uu(e)}
}
`;
let c = e.shapeInfo.texShape, p = c[0], d = c[1], h = e.shapeInfo.flatOffset;
if (d === a && h == null)
return t ? `
float ${r}(int row, int col, int depth) {
int stride1 = ${s}Shape[2];
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(stride1, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${s}TexShape[1], ${s}TexShape[0]);
return sampleTexture(${s}, uv);
}
` : `
float ${r}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${o}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${d}.0, ${p}.0);
return sampleTexture(${s}, uv);
}
`;
if (d === o && h == null)
return t ? `
float ${r}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${s}Shape[1], 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);
return sampleTexture(${s}, uv);
}
` : `
float ${r}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${n[1]}, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${d}.0, ${p}.0);
return sampleTexture(${s}, uv);
}
`;
let f = ko(s);
return t ? `
float ${r}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int stride0 = ${s}Shape[1] * ${s}Shape[2];
int stride1 = ${s}Shape[2];
int index = row * ${a} + col * ${o} + depth + ${f};
vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index);
return sampleTexture(${s}, uv);
}
` : `
float ${r}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${a} + col * ${o} + depth + ${f};
vec2 uv = uvFromFlat(${p}, ${d}, index);
return sampleTexture(${s}, uv);
}
`;
}
function YK(e, t) {
let n = e.name, s = "get" + n.charAt(0).toUpperCase() + n.slice(1), r = mn();
if (t)
return `
vec4 ${s}(int b2, int b, int row, int col) {
int valuesPerRow = int(ceil(float(${n}Shape[3]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[2]) / 2.0));
int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
texelsInBatch *= ${n}Shape[1];
index = b2 * texelsInBatch + index;
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
int texR = index / packedTexShape[1];
int texC = index - texR * packedTexShape[1];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${r.texture2D}(${n}, uv);
}
`;
let a = e.shapeInfo.logicalShape, o = a.length, i = e.shapeInfo.texShape, u = [Math.ceil(i[0] / 2), Math.ceil(i[1] / 2)], l = u[0], c = u[1], p = Math.ceil(a[o - 1] / 2), d = p * Math.ceil(a[o - 2] / 2), h = "int b, int row, int col", f = `b * ${d} + (row / 2) * ${p} + (col / 2)`;
for (let m = 2; m < o - 1; m++)
h = `int b${m}, ` + h, d *= a[o - m - 1], f = `b${m} * ${d} + ` + f;
return `
vec4 ${s}(${h}) {
int index = ${f};
int texR = index / ${c};
int texC = index - texR * ${c};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${c}, ${l});
return ${r.texture2D}(${n}, uv);
}
`;
}
function QK(e, t) {
let n = e.shapeInfo.logicalShape, s = e.name, r = "get" + s.charAt(0).toUpperCase() + s.slice(1), a = n[3], o = n[2] * a, i = n[1] * o, { newShape: u, keptDims: l } = w.squeezeShape(n);
if (u.length < n.length) {
let y = lu(e, u), v = ["row", "col", "depth", "depth2"];
return `
${iu(y, t)}
float ${r}(int row, int col, int depth, int depth2) {
return ${r}(${cu(v, l)});
}
`;
}
if (e.shapeInfo.isUniform)
return `
float ${r}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${i}, ${o}, ${a}, 1)));
${uu(e)}
}
`;
let c = e.shapeInfo.flatOffset, p = e.shapeInfo.texShape, d = p[0], h = p[1], f = `int stride2 = ${s}Shape[3];`, m = `int stride1 = ${s}Shape[2] * stride2;`, g = `int stride0 = ${s}Shape[1] * stride1;`;
if (h === i && c == null)
return t ? `
float ${r}(int row, int col, int depth, int depth2) {
${f}
${m}
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(stride1, stride2, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${s}TexShape[1], ${s}TexShape[0]);
return sampleTexture(${s}, uv);
}
` : `
float ${r}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${o}, ${a}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${d}.0);
return sampleTexture(${s}, uv);
}
`;
if (h === a && c == null)
return t ? `
float ${r}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${s}Shape[1] * ${s}Shape[2], ${s}Shape[2], 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${s}TexShape[1], ${s}TexShape[0]);
return sampleTexture(${s}, uv);
}
` : `
float ${r}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${n[1] * n[2]}, ${n[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${d}.0);
return sampleTexture(${s}, uv);
}
`;
let b = ko(s);
return t ? `
float ${r}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
${f}
${m}
${g}
int index = row * stride0 + col * stride1 +
depth * stride2 + depth2;
vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index + ${b});
return sampleTexture(${s}, uv);
}
` : `
float ${r}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${i} + col * ${o} +
depth * ${a} + depth2;
vec2 uv = uvFromFlat(${d}, ${h}, index + ${b});
return sampleTexture(${s}, uv);
}
`;
}
function ZK(e) {
let t = e.shapeInfo.logicalShape, n = e.name, s = "get" + n.charAt(0).toUpperCase() + n.slice(1), r = t[4], a = t[3] * r, o = t[2] * a, i = t[1] * o, { newShape: u, keptDims: l } = w.squeezeShape(t);
if (u.length < t.length) {
let m = lu(e, u), g = ["row", "col", "depth", "depth2", "depth3"];
return `
${iu(m)}
float ${s}(int row, int col, int depth, int depth2, int depth3) {
return ${s}(${cu(g, l)});
}
`;
}
if (e.shapeInfo.isUniform)
return `
float ${s}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${i}, ${o}, ${a}, ${r})) +
depth3;
${uu(e)}
}
`;
let c = e.shapeInfo.flatOffset, p = e.shapeInfo.texShape, d = p[0], h = p[1];
if (h === i && c == null)
return `
float ${s}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${o}, ${a}, ${r}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${d}.0);
return sampleTexture(${n}, uv);
}
`;
if (h === r && c == null)
return `
float ${s}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${t[1] * t[2] * t[3]},
${t[2] * t[3]}, ${t[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${d}.0);
return sampleTexture(${n}, uv);
}
`;
let f = ko(n);
return `
float ${s}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${i} + col * ${o} + depth * ${a} +
depth2 * ${r} + depth3 + ${f};
vec2 uv = uvFromFlat(${d}, ${h}, index);
return sampleTexture(${n}, uv);
}
`;
}
function JK(e) {
let t = e.shapeInfo.logicalShape, n = e.name, s = "get" + n.charAt(0).toUpperCase() + n.slice(1), { newShape: r, keptDims: a } = w.squeezeShape(t);
if (r.length < t.length) {
let g = lu(e, r), b = ["row", "col", "depth", "depth2", "depth3", "depth4"];
return `
${iu(g)}
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${s}(${cu(b, a)});
}
`;
}
let o = t[5], i = t[4] * o, u = t[3] * i, l = t[2] * u, c = t[1] * l;
if (e.shapeInfo.isUniform)
return `
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${c}, ${l}, ${u}, ${i})) +
dot(
vec2(depth3, depth4),
vec2(${o}, 1)));
${uu(e)}
}
`;
let p = e.shapeInfo.flatOffset, d = e.shapeInfo.texShape, h = d[0], f = d[1];
if (f === c && p == null)
return `
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${l}, ${u}, ${i}, ${o})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${h}.0);
return sampleTexture(${n}, uv);
}
`;
if (f === o && p == null)
return `
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${t[1] * t[2] * t[3] * t[4]},
${t[2] * t[3] * t[4]},
${t[3] * t[4]},
${t[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${h}.0);
return sampleTexture(${n}, uv);
}
`;
let m = ko(n);
return `
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${c} + col * ${l} + depth * ${u} +
depth2 * ${i} + depth3 * ${o} + depth4 + ${m};
vec2 uv = uvFromFlat(${h}, ${f}, index);
return sampleTexture(${n}, uv);
}
`;
}
function uu(e) {
let t = e.name, n = w.sizeFromShape(e.shapeInfo.logicalShape);
return n < 2 ? `return ${t};` : `
for (int i = 0; i < ${n}; i++) {
if (i == index) {
return ${t}[i];
}
}
`;
}
function eX(e, t) {
let n = e.name, s = n.charAt(0).toUpperCase() + n.slice(1), r = "get" + s + "AtOutCoords", a = e.shapeInfo.logicalShape.length, o = t.logicalShape.length, i = A1(e.shapeInfo.logicalShape, t.logicalShape), u = rt(o), l = o - a, c, p = ["x", "y", "z", "w", "u", "v"];
a === 0 ? c = "" : o < 2 && i.length >= 1 ? c = "coords = 0;" : c = i.map((y) => `coords.${p[y + l]} = 0;`).join(`
`);
let d = "";
o < 2 && a > 0 ? d = "coords" : d = e.shapeInfo.logicalShape.map((y, v) => `coords.${p[v + l]}`).join(", ");
let h = "return outputValue;", m = w.sizeFromShape(e.shapeInfo.logicalShape) === 1, b = w.sizeFromShape(t.logicalShape) === 1;
if (a === 1 && !m && !b)
h = `
return vec4(outputValue.xy, outputValue.xy);
`;
else if (m && !b)
o === 1 ? h = `
return vec4(outputValue.x, outputValue.x, 0., 0.);
` : h = `
return vec4(outputValue.x);
`;
else if (i.length) {
let y = a - 2, v = a - 1;
i.indexOf(y) > -1 && i.indexOf(v) > -1 ? h = "return vec4(outputValue.x);" : i.indexOf(y) > -1 ? h = "return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);" : i.indexOf(v) > -1 && (h = "return vec4(outputValue.xx, outputValue.zz);");
}
return `
vec4 ${r}() {
${u} coords = getOutputCoords();
${c}
vec4 outputValue = get${s}(${d});
${h}
}
`;
}
function tX(e, t) {
let n = e.name, s = n.charAt(0).toUpperCase() + n.slice(1), r = "get" + s + "AtOutCoords", a = t.texShape, o = e.shapeInfo.texShape, i = e.shapeInfo.logicalShape.length, u = t.logicalShape.length;
if (!e.shapeInfo.isUniform && i === u && e.shapeInfo.flatOffset == null && w.arraysEqual(o, a))
return `
float ${r}() {
return sampleTexture(${n}, resultUV);
}
`;
let l = rt(u), c = A1(e.shapeInfo.logicalShape, t.logicalShape), p = u - i, d, h = ["x", "y", "z", "w", "u", "v"];
i === 0 ? d = "" : u < 2 && c.length >= 1 ? d = "coords = 0;" : d = c.map((m) => `coords.${h[m + p]} = 0;`).join(`
`);
let f = "";
return u < 2 && i > 0 ? f = "coords" : f = e.shapeInfo.logicalShape.map((m, g) => `coords.${h[g + p]}`).join(", "), `
float ${r}() {
${l} coords = getOutputCoords();
${d}
return get${s}(${f});
}
`;
}
function rt(e) {
if (e <= 1)
return "int";
if (e === 2)
return "ivec2";
if (e === 3)
return "ivec3";
if (e === 4)
return "ivec4";
if (e === 5)
return "ivec5";
if (e === 6)
return "ivec6";
throw Error(`GPU for rank ${e} is not yet supported`);
}
function Nv(e, t, n) {
let { newShape: s, keptDims: r } = w.squeezeShape(t), a = t.length, o = e && a === 3 && t[0] === 1, i = o ? t.slice(1) : s, u = !e && a > 1 && !w.arraysEqual(t, n) && s.length < a || o;
return { useSqueezeShape: u, uniformShape: u ? i : t, keptDims: r };
}
function lu(e, t) {
let n = JSON.parse(JSON.stringify(e));
return n.shapeInfo.logicalShape = t, n;
}
function cu(e, t) {
return t.map((n) => e[n]).join(", ");
}
function nX(e, t, n, s) {
let r = n.map((c, p) => {
let d = { logicalShape: c.shape, texShape: c.isUniform ? null : c.texData.texShape, isUniform: c.isUniform, isPacked: c.isUniform ? false : c.texData.isPacked, flatOffset: null };
return c.texData != null && c.texData.slice != null && c.texData.slice.flatOffset > 0 && (d.flatOffset = c.texData.slice.flatOffset), { name: t.variableNames[p], shapeInfo: d };
}), a = r.map((c) => c.shapeInfo), o = { logicalShape: s.shape, texShape: s.texData.texShape, isUniform: false, isPacked: s.texData.isPacked, flatOffset: null }, i = xK(r, o, t), u = u1(e.gl, i), l = e.createProgram(u);
return K().get("ENGINE_COMPILE_ONLY") ? { program: t, fragmentShader: u, source: i, webGLProgram: l, inShapeInfos: a, outShapeInfo: o, uniformLocations: null, customUniformLocations: null, infLoc: null, nanLoc: null, inShapesLocations: null, inTexShapesLocations: null, outShapeLocation: null, outShapeStridesLocation: null, outTexShapeLocation: null } : { program: t, fragmentShader: u, source: i, webGLProgram: l, inShapeInfos: a, outShapeInfo: o, ...D1(e, t, l) };
}
function D1(e, t, n) {
let s = {}, r = {}, a = {}, o = [], i, u, l, c = null, p = null;
p = e.getUniformLocation(n, "NAN", false), K().getNumber("WEBGL_VERSION") === 1 && (c = e.getUniformLocation(n, "INFINITY", false));
let d = false;
for (let h = 0; h < t.variableNames.length; h++) {
let f = t.variableNames[h];
s[f] = e.getUniformLocation(n, f, d), s[`offset${f}`] = e.getUniformLocation(n, `offset${f}`, d), t.enableShapeUniforms && (r[`${f}Shape`] = e.getUniformLocation(n, `${f}Shape`, d), a[`${f}TexShape`] = e.getUniformLocation(n, `${f}TexShape`, d));
}
return t.enableShapeUniforms && (i = e.getUniformLocation(n, "outShape", d), l = e.getUniformLocation(n, "outShapeStrides", d), u = e.getUniformLocation(n, "outTexShape", d)), t.customUniforms && t.customUniforms.forEach((h, f) => {
o[f] = e.getUniformLocation(n, h.name, d);
}), { uniformLocations: s, customUniformLocations: o, infLoc: c, nanLoc: p, inShapesLocations: r, inTexShapesLocations: a, outShapeLocation: i, outShapeStridesLocation: l, outTexShapeLocation: u };
}
function fw(e, t) {
if (e.length !== t.length)
throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);
e.forEach((n, s) => {
let r = n.logicalShape, a = t[s], o = a.shape;
if (!w.arraysEqual(r, o))
throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${o} must match`);
if (n.isUniform && a.isUniform)
return;
let i = n.texShape, u = a.isUniform ? null : a.texData.texShape;
if (!w.arraysEqual(i, u))
throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${u} must match`);
});
}
function sX(e, t, n, s, r) {
t.program.enableShapeUniforms || (fw(t.inShapeInfos, n), fw([t.outShapeInfo], [s]));
let a = s.texData.texture, o = s.texData.texShape;
s.texData.isPacked ? e.setOutputPackedMatrixTexture(a.texture, o[0], o[1]) : e.setOutputMatrixTexture(a.texture, o[0], o[1]), e.setProgram(t.webGLProgram), K().getNumber("WEBGL_VERSION") === 1 && t.infLoc !== null && e.gl.uniform1f(t.infLoc, 1 / 0), t.nanLoc !== null && e.gl.uniform1f(t.nanLoc, NaN), n.forEach((u, l) => {
let c = t.program.variableNames[l], p = t.uniformLocations[c], d = t.uniformLocations[`offset${c}`], h = t.inShapesLocations[`${c}Shape`], f = t.inTexShapesLocations[`${c}TexShape`];
if (h) {
let { uniformShape: m } = Nv(t.program.packedInputs, u.shape, u.texData.texShape);
switch (m.length) {
case 1:
e.gl.uniform1iv(h, new Int32Array(m));
break;
case 2:
e.gl.uniform2iv(h, new Int32Array(m));
break;
case 3:
e.gl.uniform3iv(h, new Int32Array(m));
break;
case 4:
e.gl.uniform4iv(h, new Int32Array(m));
break;
default:
break;
}
}
if (f && e.gl.uniform2i(f, u.texData.texShape[0], u.texData.texShape[1]), p != null) {
if (u.isUniform) {
if (w.sizeFromShape(u.shape) < 2)
e.gl.uniform1f(p, u.uniformValues[0]);
else {
let m = u.uniformValues;
m instanceof Float32Array || (m = new Float32Array(m)), e.gl.uniform1fv(p, m);
}
return;
}
u.texData.slice != null && d != null && e.gl.uniform1i(d, u.texData.slice.flatOffset), e.setInputMatrixTexture(u.texData.texture.texture, p, l);
}
});
let i = t.outShapeLocation;
if (i)
switch (s.shape.length) {
case 1:
e.gl.uniform1iv(i, new Int32Array(s.shape));
break;
case 2:
e.gl.uniform2iv(i, new Int32Array(s.shape));
break;
case 3:
e.gl.uniform3iv(i, new Int32Array(s.shape));
break;
case 4:
e.gl.uniform4iv(i, new Int32Array(s.shape));
break;
default:
break;
}
if (t.outShapeStridesLocation) {
let u = w.computeStrides(s.shape);
switch (s.shape.length) {
case 2:
e.gl.uniform1iv(t.outShapeStridesLocation, new Int32Array(u));
break;
case 3:
e.gl.uniform2iv(t.outShapeStridesLocation, new Int32Array(u));
break;
case 4:
e.gl.uniform3iv(t.outShapeStridesLocation, new Int32Array(u));
break;
default:
break;
}
}
t.outTexShapeLocation && e.gl.uniform2i(t.outTexShapeLocation, s.texData.texShape[0], s.texData.texShape[1]), t.program.customUniforms && r && t.program.customUniforms.forEach((u, l) => {
let c = t.customUniformLocations[l], p = r[l];
if (u.type === "float")
e.gl.uniform1fv(c, p);
else if (u.type === "vec2")
e.gl.uniform2fv(c, p);
else if (u.type === "vec3")
e.gl.uniform3fv(c, p);
else if (u.type === "vec4")
e.gl.uniform4fv(c, p);
else if (u.type === "int")
e.gl.uniform1iv(c, p);
else if (u.type === "ivec2")
e.gl.uniform2iv(c, p);
else if (u.type === "ivec3")
e.gl.uniform3iv(c, p);
else if (u.type === "ivec4")
e.gl.uniform4iv(c, p);
else
throw Error(`uniform type ${u.type} is not supported yet.`);
}), e.executeProgram();
}
function rX(e, t, n) {
let s = "";
t.concat(n).forEach((o) => {
let i = o.texData != null && o.texData.slice != null && o.texData.slice.flatOffset > 0;
if (e.enableShapeUniforms && !o.isUniform) {
let u = o.texData.texShape, { useSqueezeShape: l, uniformShape: c, keptDims: p } = Nv(e.packedInputs, o.shape, u), d = "", h = "", f = "";
if (c.length === 1 && e.packedInputs) {
let k = [Math.ceil(u[0] / 2), Math.ceil(u[1] / 2)];
d = `${k[0] > 1}_${k[1] > 1}`;
} else if (c.length === 2 && !e.packedInputs)
h = `${c[0] > 1}_${c[1] > 1}`;
else if (c.length > 2 && !e.packedInputs) {
let k = w.computeStrides(c);
f = `${k[0] === u[1]}_${k[k.length - 1] === u[1]}`;
}
let m = o.shape.length, g = c.length === 2 && w.arraysEqual(o.shape, u), b = w.sizeFromShape(o.shape) === 1, y = C.getBroadcastDims(o.shape, n.shape), v = !e.packedInputs && m === n.shape.length && w.arraysEqual(u, n.texData.texShape), x = e.packedInputs || c.length > 2 ? "" : `${u[0] > 1}_${u[1] > 1}`;
s += `${m}_${v}_${l ? p : ""}_${c.length}_${b}_${y}_${g}_${d}_${h}_${f}_${x}_${i}`;
} else {
let u = o.isUniform ? "uniform" : o.texData.texShape;
s += `${o.shape}_${u}_${i}`;
}
});
let r = e.userCode, a = e.constructor.name;
return a += "_" + s + "_" + r + `${K().getNumber("WEBGL_VERSION")}`, a;
}
function Sn(e) {
return K().getBool("WEBGL_USE_SHAPES_UNIFORMS") && e <= 4;
}
var aX = class {
constructor(e) {
this.variableNames = ["A"], this.packedInputs = false, this.packedOutput = true, this.outPackingScheme = 0, this.customUniforms = [{ name: "texShape", type: "ivec2" }];
let t = mn();
this.outputShape = e, this.enableShapeUniforms = Sn(this.outputShape.length), this.userCode = `
ivec3 outCoordsFromFlatIndex(int index) {
${this.enableShapeUniforms ? th(["r", "c", "d"], e) : wo(["r", "c", "d"], e)}
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getA(rc.x, rc.y, rc.z);
}
${t.output} = result;
}
`;
}
};
var oX = class {
constructor(e) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.outPackingScheme = 0, this.customUniforms = [{ name: "texShape", type: "ivec2" }];
let t = mn();
this.outputShape = e, this.enableShapeUniforms = Sn(this.outputShape.length), this.userCode = `
ivec3 outCoordsFromFlatIndex(int index) {
${this.enableShapeUniforms ? th(["r", "c", "d"], e) : wo(["r", "c", "d"], e)}
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
}
${t.output} = result;
}
`;
}
};
var iX = class {
constructor(e) {
this.variableNames = ["A"], this.outTexUsage = 3;
let t = mn();
this.outputShape = e, this.userCode = `
${_1}
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
`;
}
};
var uX = class {
constructor(e) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = false, this.outTexUsage = 3;
let t = mn();
this.outputShape = e, this.userCode = `
${_1}
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
`;
}
};
var lX = class {
constructor(e, t = false) {
this.variableNames = ["A"], this.customUniforms = [{ name: "texShape", type: "ivec2" }];
let n = mn();
this.outputShape = e, this.enableShapeUniforms = Sn(this.outputShape.length);
let s = "result";
t && (s = "floor(result * 255. + 0.5)"), this.userCode = `
${this.enableShapeUniforms ? Cv() : Iv(e)}
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
int offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
int r = flatIndex / texShape[1];
int c = imod(flatIndex, texShape[1]);
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
vec4 values = ${n.texture2D}(A, uv);
float result;
if(offset == 0) {
result = values[0];
} else if(offset == 1) {
result = values[1];
} else if(offset == 2) {
result = values[2];
} else {
result = values[3];
}
${n.output} = vec4(${s}, 0., 0., 0.);
}
`;
}
};
var cX = class {
constructor(e, t = false) {
this.variableNames = ["A"], this.packedInputs = false, this.packedOutput = true, this.customUniforms = [{ name: "texShape", type: "ivec2" }];
let n = mn();
this.outputShape = e, this.enableShapeUniforms = Sn(this.outputShape.length);
let s = "", r = "result";
t && (r = "floor(result * 255. + 0.5)");
for (let a = 0; a <= 1; a++)
for (let o = 0; o <= 1; o++) {
let i = a * 2 + o;
s += `
localCoords = coords;
if(localCoords[2] + ${o} < ${this.enableShapeUniforms ? "outShape[2]" : `${e[2]}`}) {
localCoords[2] += ${o};
if (localCoords[1] + ${a} < ${this.enableShapeUniforms ? "outShape[1]" : `${e[1]}`}) {
localCoords[1] += ${a};
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
int r = flatIndex / texShape[1];
int c = imod(flatIndex, texShape[1]);
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
values = ${n.texture2D}(A, uv);
if (offset == 0) {
result[${i}] = values[0];
} else if (offset == 1) {
result[${i}] = values[1];
} else if (offset == 2) {
result[${i}] = values[2];
} else {
result[${i}] = values[3];
}
}
}
`;
}
this.userCode = `
${this.enableShapeUniforms ? Cv() : Iv(e)}
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
${s}
${n.output} = ${r};
}
`;
}
};
var dX = {};
Ee(dX, { bindVertexProgramAttributeStreams: () => W1, createBufferFromOutputTexture: () => H1, createFloat16MatrixTexture: () => L1, createFloat16PackedMatrixTexture: () => V1, createFloat32MatrixTexture: () => z1, createIndexBuffer: () => P1, createPackedMatrixTexture: () => B1, createUnsignedBytesMatrixTexture: () => M1, createVertexBuffer: () => O1, createVertexShader: () => F1, downloadByteEncodedFloatMatrixFromOutputTexture: () => j1, downloadFloat32MatrixFromBuffer: () => q1, downloadMatrixFromPackedOutputTexture: () => X1, downloadPackedMatrixFromBuffer: () => K1, getInternalFormatForFloat16MatrixTexture: () => $v, getInternalFormatForFloat16PackedMatrixTexture: () => Ev, getInternalFormatForFloat32MatrixTexture: () => Tv, getInternalFormatForPackedMatrixTexture: () => Av, getInternalFormatForUnsignedBytesMatrixTexture: () => _v, uploadDenseMatrixToTexture: () => U1, uploadPixelDataToTexture: () => G1 });
function F1(e) {
let t = mn(), n = `${t.version}
precision highp float;
${t.attribute} vec3 clipSpacePos;
${t.attribute} vec2 uv;
${t.varyingVs} vec2 resultUV;
void main() {
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
}`;
return i1(e, n);
}
function O1(e) {
let t = new Float32Array([-1, 1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0]);
return d1(e, t);
}
function P1(e) {
let t = new Uint16Array([0, 1, 2, 2, 1, 3]);
return p1(e, t);
}
function ec(e, t, n, s, r, a) {
f1(t, n);
let o = h1(e), i = e.TEXTURE_2D;
return fe(e, () => e.bindTexture(i, o)), fe(e, () => e.texParameteri(i, e.TEXTURE_WRAP_S, e.CLAMP_TO_EDGE)), fe(e, () => e.texParameteri(i, e.TEXTURE_WRAP_T, e.CLAMP_TO_EDGE)), fe(e, () => e.texParameteri(i, e.TEXTURE_MIN_FILTER, e.NEAREST)), fe(e, () => e.texParameteri(i, e.TEXTURE_MAG_FILTER, e.NEAREST)), K().getNumber("WEBGL_VERSION") === 1 ? fe(e, () => e.texImage2D(i, 0, s, t, n, 0, r, a, null)) : fe(e, () => e.texStorage2D(i, 1, s, t, n)), fe(e, () => e.bindTexture(e.TEXTURE_2D, null)), { texture: o, texShape: [n, t] };
}
function Tv(e) {
return e.internalFormatFloat;
}
function z1(e, t, n, s) {
let [r, a] = Jl(t, n);
return ec(e, r, a, Tv(s), s.textureFormatFloat, e.FLOAT);
}
function $v(e) {
return e.internalFormatHalfFloat;
}
function L1(e, t, n, s) {
let [r, a] = Jl(t, n);
return ec(e, r, a, $v(s), s.textureFormatFloat, s.textureTypeHalfFloat);
}
function _v(e) {
return e.downloadTextureFormat;
}
function M1(e, t, n, s) {
let [r, a] = Jl(t, n);
return ec(e, r, a, _v(s), e.RGBA, e.UNSIGNED_BYTE);
}
function Av(e) {
return e.internalFormatPackedFloat;
}
function B1(e, t, n, s) {
let [r, a] = au(t, n);
return ec(e, r, a, Av(s), e.RGBA, e.FLOAT);
}
function Ev(e) {
return e.internalFormatPackedHalfFloat;
}
function V1(e, t, n, s) {
let [r, a] = au(t, n);
return ec(e, r, a, Ev(s), e.RGBA, s.textureTypeHalfFloat);
}
function W1(e, t, n) {
return fe(e, () => e.bindBuffer(e.ARRAY_BUFFER, n)), Zm(e, t, "clipSpacePos", n, 3, 20, 0) && Zm(e, t, "uv", n, 2, 20, 12);
}
function U1(e, t, n, s, r, a) {
fe(e, () => e.bindTexture(e.TEXTURE_2D, t));
let o, i, u;
r instanceof Uint8Array ? (o = new Uint8Array(n * s * 4), i = e.UNSIGNED_BYTE, u = e.RGBA) : (o = new Float32Array(n * s * 4), i = e.FLOAT, u = a.internalFormatPackedFloat), o.set(r), K().getNumber("WEBGL_VERSION") === 2 ? fe(e, () => e.texSubImage2D(e.TEXTURE_2D, 0, 0, 0, n, s, e.RGBA, i, o)) : fe(e, () => e.texImage2D(e.TEXTURE_2D, 0, u, n, s, 0, e.RGBA, i, o)), fe(e, () => e.bindTexture(e.TEXTURE_2D, null));
}
function G1(e, t, n) {
fe(e, () => e.bindTexture(e.TEXTURE_2D, t)), n.data instanceof Uint8Array ? K().getNumber("WEBGL_VERSION") === 2 ? fe(e, () => e.texSubImage2D(e.TEXTURE_2D, 0, 0, 0, n.width, n.height, e.RGBA, e.UNSIGNED_BYTE, n.data)) : fe(e, () => e.texImage2D(e.TEXTURE_2D, 0, e.RGBA, n.width, n.height, 0, e.RGBA, e.UNSIGNED_BYTE, n.data)) : K().getNumber("WEBGL_VERSION") === 2 ? fe(e, () => e.texSubImage2D(e.TEXTURE_2D, 0, 0, 0, e.RGBA, e.UNSIGNED_BYTE, n)) : fe(e, () => e.texImage2D(e.TEXTURE_2D, 0, e.RGBA, e.RGBA, e.UNSIGNED_BYTE, n)), fe(e, () => e.bindTexture(e.TEXTURE_2D, null));
}
function H1(e, t, n, s) {
let r = e.createBuffer();
fe(e, () => e.bindBuffer(e.PIXEL_PACK_BUFFER, r));
let i = 4 * 4 * t * n;
return fe(e, () => e.bufferData(e.PIXEL_PACK_BUFFER, i, e.STREAM_READ)), fe(e, () => e.readPixels(0, 0, n, t, e.RGBA, e.FLOAT, 0)), fe(e, () => e.bindBuffer(e.PIXEL_PACK_BUFFER, null)), r;
}
function q1(e, t, n) {
let s = e, r = new Float32Array(n);
return s.bindBuffer(s.PIXEL_PACK_BUFFER, t), s.getBufferSubData(s.PIXEL_PACK_BUFFER, 0, r), s.bindBuffer(s.PIXEL_PACK_BUFFER, null), r;
}
function j1(e, t, n, s) {
let [r, a] = Jl(t, n), o = 4, i = new Uint8Array(oK(t * n, o));
return fe(e, () => e.readPixels(0, 0, r, a, s.downloadTextureFormat, e.UNSIGNED_BYTE, i)), new Float32Array(i.buffer);
}
function K1(e, t, n, s, r, a, o, i) {
let u = e, l = new Float32Array(iK(a, o));
return u.bindBuffer(u.PIXEL_PACK_BUFFER, t), u.getBufferSubData(u.PIXEL_PACK_BUFFER, 0, l), u.bindBuffer(u.PIXEL_PACK_BUFFER, null), l;
}
function X1(e, t, n) {
let s = new Float32Array(t * n * 4);
return fe(e, () => e.readPixels(0, 0, n, t, e.RGBA, e.FLOAT, s)), s;
}
var am = class {
constructor(e) {
this.outputTexture = null, this.program = null, this.disposed = false, this.vertexAttrsAreBound = false, this.itemsToPoll = [];
let t = K().getNumber("WEBGL_VERSION");
e != null ? (this.gl = e, sK(t, e)) : this.gl = xs(t);
let n = "WEBGL_color_buffer_float", s = "EXT_color_buffer_half_float";
if (this.parallelCompilationExtension = this.gl.getExtension("KHR_parallel_shader_compile"), K().getNumber("WEBGL_VERSION") === 1) {
let r = "OES_texture_float", a = "OES_texture_half_float";
if (this.textureFloatExtension = Lu(this.gl, r), Mn(this.gl, a))
this.textureHalfFloatExtension = Lu(this.gl, a);
else if (K().get("WEBGL_FORCE_F16_TEXTURES"))
throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");
if (this.colorBufferFloatExtension = this.gl.getExtension(n), Mn(this.gl, s))
this.colorBufferHalfFloatExtension = Lu(this.gl, s);
else if (K().get("WEBGL_FORCE_F16_TEXTURES"))
throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");
} else if (n = "EXT_color_buffer_float", Mn(this.gl, n))
this.colorBufferFloatExtension = this.gl.getExtension(n);
else if (Mn(this.gl, s))
this.colorBufferHalfFloatExtension = this.gl.getExtension(s);
else
throw new Error("GL context does not support color renderable floats");
this.vertexBuffer = O1(this.gl), this.indexBuffer = P1(this.gl), this.framebuffer = m1(this.gl), this.textureConfig = kv(this.gl, this.textureHalfFloatExtension);
}
get debug() {
return K().getBool("DEBUG");
}
dispose() {
if (this.disposed)
return;
this.program != null && console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."), this.outputTexture != null && console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");
let e = this.gl;
fe(e, () => e.finish()), fe(e, () => e.bindFramebuffer(e.FRAMEBUFFER, null)), fe(e, () => e.deleteFramebuffer(this.framebuffer)), fe(e, () => e.bindBuffer(e.ARRAY_BUFFER, null)), fe(e, () => e.bindBuffer(e.ELEMENT_ARRAY_BUFFER, null)), fe(e, () => e.deleteBuffer(this.indexBuffer)), this.disposed = true;
}
createFloat32MatrixTexture(e, t) {
return this.throwIfDisposed(), z1(this.gl, e, t, this.textureConfig);
}
createFloat16MatrixTexture(e, t) {
return this.throwIfDisposed(), L1(this.gl, e, t, this.textureConfig);
}
createUnsignedBytesMatrixTexture(e, t) {
return this.throwIfDisposed(), M1(this.gl, e, t, this.textureConfig);
}
uploadPixelDataToTexture(e, t) {
this.throwIfDisposed(), G1(this.gl, e, t);
}
uploadDenseMatrixToTexture(e, t, n, s) {
this.throwIfDisposed(), U1(this.gl, e, t, n, s, this.textureConfig);
}
createFloat16PackedMatrixTexture(e, t) {
return this.throwIfDisposed(), V1(this.gl, e, t, this.textureConfig);
}
createPackedMatrixTexture(e, t) {
return this.throwIfDisposed(), B1(this.gl, e, t, this.textureConfig);
}
deleteMatrixTexture(e) {
this.throwIfDisposed(), this.outputTexture === e && (Jm(this.gl, this.framebuffer), this.outputTexture = null), fe(this.gl, () => this.gl.deleteTexture(e));
}
downloadByteEncodedFloatMatrixFromOutputTexture(e, t, n) {
return this.downloadMatrixDriver(e, () => j1(this.gl, t, n, this.textureConfig));
}
downloadPackedMatrixFromBuffer(e, t, n, s, r, a) {
return K1(this.gl, e, t, n, s, r, a, this.textureConfig);
}
downloadFloat32MatrixFromBuffer(e, t) {
return q1(this.gl, e, t);
}
createBufferFromTexture(e, t, n) {
this.bindTextureToFrameBuffer(e);
let s = H1(this.gl, t, n, this.textureConfig);
return this.unbindTextureToFrameBuffer(), s;
}
createAndWaitForFence() {
let e = this.createFence(this.gl);
return this.pollFence(e);
}
createFence(e) {
let t, n;
if (K().getBool("WEBGL_FENCE_API_ENABLED")) {
let s = e, r = s.fenceSync(s.SYNC_GPU_COMMANDS_COMPLETE, 0);
e.flush(), n = () => {
let a = s.clientWaitSync(r, 0, 0);
return a === s.ALREADY_SIGNALED || a === s.CONDITION_SATISFIED;
}, t = r;
} else
K().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") > 0 ? (t = this.beginQuery(), this.endQuery(), n = () => this.isQueryAvailable(t, K().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))) : n = () => true;
return { query: t, isFencePassed: n };
}
downloadMatrixFromPackedTexture(e, t, n) {
return this.downloadMatrixDriver(e, () => X1(this.gl, t, n));
}
createProgram(e) {
this.throwIfDisposed();
let t = this.gl;
this.vertexShader == null && (this.vertexShader = F1(t));
let n = l1(t);
return fe(t, () => t.attachShader(n, this.vertexShader)), fe(t, () => t.attachShader(n, e)), c1(t, n), this.debug && ld(t, n), this.vertexAttrsAreBound || (this.setProgram(n), this.vertexAttrsAreBound = W1(t, this.program, this.vertexBuffer)), n;
}
deleteProgram(e) {
this.throwIfDisposed(), e === this.program && (this.program = null), e != null && fe(this.gl, () => this.gl.deleteProgram(e));
}
setProgram(e) {
this.throwIfDisposed(), this.program = e, this.program != null && this.debug && ld(this.gl, this.program), fe(this.gl, () => this.gl.useProgram(e));
}
getUniformLocation(e, t, n = true) {
return this.throwIfDisposed(), n ? b1(this.gl, e, t) : y1(this.gl, e, t);
}
getAttributeLocation(e, t) {
return this.throwIfDisposed(), fe(this.gl, () => this.gl.getAttribLocation(e, t));
}
getUniformLocationNoThrow(e, t) {
return this.throwIfDisposed(), this.gl.getUniformLocation(e, t);
}
setInputMatrixTexture(e, t, n) {
this.throwIfDisposed(), this.throwIfNoProgram(), v1(this.gl, e, t, n);
}
setOutputMatrixTexture(e, t, n) {
this.setOutputMatrixTextureDriver(e, n, t);
}
setOutputPackedMatrixTexture(e, t, n) {
this.throwIfDisposed();
let [s, r] = au(t, n);
this.setOutputMatrixTextureDriver(e, s, r);
}
setOutputMatrixWriteRegion(e, t, n, s) {
this.setOutputMatrixWriteRegionDriver(n, e, s, t);
}
setOutputPackedMatrixWriteRegion(e, t, n, s) {
throw new Error("setOutputPackedMatrixWriteRegion not implemented.");
}
debugValidate() {
this.program != null && ld(this.gl, this.program), Mu(this.gl);
}
executeProgram() {
this.throwIfDisposed(), this.throwIfNoProgram();
let e = this.gl;
this.debug && this.debugValidate(), fe(e, () => e.drawElements(e.TRIANGLES, 6, e.UNSIGNED_SHORT, 0));
}
blockUntilAllProgramsCompleted() {
this.throwIfDisposed(), fe(this.gl, () => this.gl.finish());
}
getQueryTimerExtension() {
return this.disjointQueryTimerExtension == null && (this.disjointQueryTimerExtension = Lu(this.gl, K().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2 ? "EXT_disjoint_timer_query_webgl2" : "EXT_disjoint_timer_query")), this.disjointQueryTimerExtension;
}
getQueryTimerExtensionWebGL2() {
return this.getQueryTimerExtension();
}
getQueryTimerExtensionWebGL1() {
return this.getQueryTimerExtension();
}
beginQuery() {
if (K().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2) {
let n = this.gl, s = this.getQueryTimerExtensionWebGL2(), r = n.createQuery();
return n.beginQuery(s.TIME_ELAPSED_EXT, r), r;
}
let e = this.getQueryTimerExtensionWebGL1(), t = e.createQueryEXT();
return e.beginQueryEXT(e.TIME_ELAPSED_EXT, t), t;
}
endQuery() {
if (K().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2) {
let t = this.gl, n = this.getQueryTimerExtensionWebGL2();
t.endQuery(n.TIME_ELAPSED_EXT);
return;
}
let e = this.getQueryTimerExtensionWebGL1();
e.endQueryEXT(e.TIME_ELAPSED_EXT);
}
async waitForQueryAndGetTime(e) {
return await w.repeatedTry(() => this.disposed || this.isQueryAvailable(e, K().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))), this.getQueryTime(e, K().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"));
}
getQueryTime(e, t) {
if (t === 0)
return null;
if (t === 2) {
let n = this.gl;
return n.getQueryParameter(e, n.QUERY_RESULT) / 1e6;
} else {
let n = this.getQueryTimerExtensionWebGL1();
return n.getQueryObjectEXT(e, n.QUERY_RESULT_EXT) / 1e6;
}
}
isQueryAvailable(e, t) {
if (t === 0)
return true;
if (t === 2) {
let n = this.gl, s = this.getQueryTimerExtensionWebGL2(), r = n.getQueryParameter(e, n.QUERY_RESULT_AVAILABLE);
return this.disjoint == null && (this.disjoint = this.gl.getParameter(s.GPU_DISJOINT_EXT)), r && !this.disjoint;
} else {
let n = this.getQueryTimerExtensionWebGL1(), s = n.getQueryObjectEXT(e, n.QUERY_RESULT_AVAILABLE_EXT);
return this.disjoint == null && (this.disjoint = this.gl.getParameter(n.GPU_DISJOINT_EXT)), s && !this.disjoint;
}
}
pollFence(e) {
return new Promise((t) => {
this.addItemToPoll(() => e.isFencePassed(), () => t());
});
}
pollItems() {
let e = pX(this.itemsToPoll.map((t) => t.isDoneFn));
for (let t = 0; t <= e; ++t) {
let { resolveFn: n } = this.itemsToPoll[t];
n();
}
this.itemsToPoll = this.itemsToPoll.slice(e + 1);
}
addItemToPoll(e, t) {
this.itemsToPoll.push({ isDoneFn: e, resolveFn: t }), !(this.itemsToPoll.length > 1) && w.repeatedTry(() => (this.pollItems(), this.itemsToPoll.length === 0));
}
bindTextureToFrameBuffer(e) {
this.throwIfDisposed(), cd(this.gl, e, this.framebuffer), this.debug && Mu(this.gl);
}
unbindTextureToFrameBuffer() {
this.outputTexture != null ? (cd(this.gl, this.outputTexture, this.framebuffer), this.debug && Mu(this.gl)) : Jm(this.gl, this.framebuffer);
}
downloadMatrixDriver(e, t) {
this.bindTextureToFrameBuffer(e);
let n = t();
return this.unbindTextureToFrameBuffer(), n;
}
setOutputMatrixTextureDriver(e, t, n) {
this.throwIfDisposed();
let s = this.gl;
cd(s, e, this.framebuffer), this.debug && Mu(s), this.outputTexture = e, fe(s, () => s.viewport(0, 0, t, n)), fe(s, () => s.scissor(0, 0, t, n));
}
setOutputMatrixWriteRegionDriver(e, t, n, s) {
this.throwIfDisposed(), fe(this.gl, () => this.gl.scissor(e, t, n, s));
}
throwIfDisposed() {
if (this.disposed)
throw new Error("Attempted to use disposed GPGPUContext.");
}
throwIfNoProgram() {
if (this.program == null)
throw new Error("No GPU program is currently set.");
}
};
function pX(e) {
let t = 0;
for (; t < e.length && e[t](); ++t)
;
return t - 1;
}
var { addImpl: hX, bincountImpl: Y1, bincountReduceImpl: fX, ceilImpl: mX, concatImpl: gX, equalImpl: bX, expImpl: yX, expm1Impl: vX, floorImpl: xX, gatherNdImpl: wX, gatherV2Impl: kX, greaterImpl: SX, greaterEqualImpl: IX, lessImpl: CX, lessEqualImpl: NX, linSpaceImpl: TX, logImpl: $X, maxImpl: _X, maximumImpl: AX, minimumImpl: EX, multiplyImpl: RX, negImpl: DX, notEqualImpl: FX, prodImpl: OX, rangeImpl: PX, rsqrtImpl: zX, scatterImpl: LX, sigmoidImpl: MX, simpleAbsImpl: Q1, sliceImpl: BX, sparseFillEmptyRowsImpl: VX, sparseReshapeImpl: WX, sparseSegmentReductionImpl: Z1, sqrtImpl: UX, stridedSliceImpl: GX, stringNGramsImpl: HX, stringSplitImpl: qX, stringToHashBucketFastImpl: jX, subImpl: KX, tileImpl: XX, topKImpl: YX, transposeImpl: Rv, uniqueImpl: QX } = cv;
function J1(e, t) {
return ["x", "y", "z", "w", "u", "v"].slice(0, t).map((n) => `${e}.${n}`);
}
function ln(e, t) {
return t === 1 ? [e] : J1(e, t);
}
function ZX(e, t) {
if (e === 1)
return "rc";
let n = "";
for (let s = 0; s < e; s++)
n += t[s], s < e - 1 && (n += ",");
return n;
}
var JX = class {
constructor(e) {
if (this.variableNames = ["A"], this.packedInputs = false, this.packedOutput = true, this.outputShape = e, this.rank = e.length, this.enableShapeUniforms = Sn(this.outputShape.length), this.rank === 0)
this.userCode = `
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
`;
else {
let t = ln("rc", this.rank), n = rt(this.rank), s = this.getOutOfBoundsCondition(t), r = this.getSetup(t), a = this.getOutput(t);
this.userCode = `
void main() {
${n} rc = getOutputCoords();
if(${s}) {
setOutput(vec4(0));
} else {
${r}
setOutput(vec4(${a}));
}
}
`;
}
}
getSourceCoordsArr(e) {
let t = [];
for (let n = 0; n <= 1; n++)
for (let s = 0; s <= 1; s++) {
let r = `${n === 0 ? "r" : "rp1"}, ${s === 0 ? "c" : "cp1"}`;
for (let a = 2; a < this.rank; a++)
r = `${e[e.length - 1 - a]},` + r;
t.push(r);
}
return t;
}
getOutOfBoundsCondition(e) {
if (this.rank === 1)
return `rc > ${this.enableShapeUniforms ? "outShape" : this.outputShape[0]}`;
let t = "";
for (let n = this.rank - 2; n < this.rank; n++)
t += `${e[n]} >= ${this.enableShapeUniforms ? `outShape[${n}]` : this.outputShape[n]}`, n < this.rank - 1 && (t += "||");
return t;
}
getSetup(e) {
if (this.rank === 1)
return "";
let t = e.slice(-2), n = this.enableShapeUniforms ? `outShape[${this.rank} - 1]` : this.outputShape[this.rank - 1], s = this.enableShapeUniforms ? `outShape[${this.rank} - 2]` : this.outputShape[this.rank - 2];
return `
int r = ${t[0]};
int c = ${t[1]};
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${n};
bool rEdge = rp1 >= ${s};
`;
}
getOutput(e) {
let t = this.getSourceCoordsArr(e);
return this.rank === 1 ? `getA(rc), (rc + 1 >= ${this.enableShapeUniforms ? "outShape" : this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0` : `getA(${t[0]}),
cEdge ? 0. : getA(${t[1]}),
rEdge ? 0. : getA(${t[2]}),
rEdge || cEdge ? 0. : getA(${t[3]})`;
}
};
var e2 = class {
constructor(e, t) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.customUniforms = [{ name: "inputShape", type: "ivec3" }], this.outputShape = e, this.enableShapeUniforms = Sn(this.outputShape.length);
let n = "";
for (let s = 0; s < 4; s++) {
let r = "thisRC = rc;";
s % 2 === 1 && (r += "thisRC.z += 1;"), s > 1 && (r += "thisRC.y += 1;"), n += `
${r}
${s > 0 ? "if(thisRC.y < rows && thisRC.z < cols){" : ""}
int flatIndex = getFlatIndex(thisRC);
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
result[${s}] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
${s > 0 ? "}" : ""}
`;
}
this.userCode = `
${e8(t, this.enableShapeUniforms)}
${this.enableShapeUniforms ? Cv() : Iv(e)}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${this.enableShapeUniforms ? "outShape[1]" : e[1]};
int cols = ${this.enableShapeUniforms ? "outShape[2]" : e[2]};
${n}
setOutput(result);
}
`;
}
};
function e8(e, t) {
return `
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t ? vK(["r", "c", "d"], "inputShape") : wo(["r", "c", "d"], e)}
return ivec3(r, c, d);
}
`;
}
var t8 = class {
constructor(e) {
this.gpgpu = e, this.numUsedTextures = 0, this.numFreeTextures = 0, this._numBytesAllocated = 0, this._numBytesFree = 0, this.freeTextures = {}, this.logEnabled = false, this.usedTextures = {};
}
acquireTexture(e, t, n) {
let s = gw(t, n), r = bw(e, s, n);
r in this.freeTextures || (this.freeTextures[r] = []), r in this.usedTextures || (this.usedTextures[r] = []);
let a = mw(e, s, this.gpgpu.gl, this.gpgpu.textureConfig, n);
if (this.freeTextures[r].length > 0) {
this.numFreeTextures--, this.numUsedTextures++, this._numBytesFree -= a, this.log();
let i = this.freeTextures[r].shift();
return this.usedTextures[r].push(i), i;
}
let o;
return s === 3 ? o = this.gpgpu.createPackedMatrixTexture(e[0], e[1]) : s === 4 ? o = this.gpgpu.createFloat16PackedMatrixTexture(e[0], e[1]) : s === 1 ? o = this.gpgpu.createFloat32MatrixTexture(e[0], e[1]) : s === 0 ? o = this.gpgpu.createFloat16MatrixTexture(e[0], e[1]) : s === 2 && (o = this.gpgpu.createUnsignedBytesMatrixTexture(e[0], e[1])), this.usedTextures[r].push(o), this.numUsedTextures++, this._numBytesAllocated += a, this.log(), o;
}
releaseTexture(e, t, n, s) {
if (this.freeTextures == null)
return;
let r = gw(n, s), a = bw(t, r, s);
a in this.freeTextures || (this.freeTextures[a] = []);
let o = mw(t, r, this.gpgpu.gl, this.gpgpu.textureConfig, s), i = K().get("WEBGL_DELETE_TEXTURE_THRESHOLD");
i !== -1 && this._numBytesAllocated > i ? (this.gpgpu.deleteMatrixTexture(e.texture), this._numBytesAllocated -= o) : (this.freeTextures[a].push(e), this.numFreeTextures++, this._numBytesFree += o), this.numUsedTextures--;
let u = this.usedTextures[a], l = u.indexOf(e);
if (l < 0)
throw new Error("Cannot release a texture that was never provided by this texture manager");
u.splice(l, 1), this.log();
}
log() {
if (!this.logEnabled)
return;
let e = this.numFreeTextures + this.numUsedTextures;
console.log("Free/Used", `${this.numFreeTextures} / ${this.numUsedTextures}`, `(${e})`);
let t = this._numBytesFree / this._numBytesAllocated;
console.log(`Bytes allocated: ${this._numBytesAllocated}`), console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100 * t)}%)`);
}
get numBytesAllocated() {
return this._numBytesAllocated;
}
get numBytesFree() {
return this._numBytesFree;
}
getNumUsedTextures() {
return this.numUsedTextures;
}
getNumFreeTextures() {
return this.numFreeTextures;
}
dispose() {
if (this.freeTextures != null) {
for (let e in this.freeTextures)
this.freeTextures[e].forEach((t) => {
this.gpgpu.deleteMatrixTexture(t.texture);
});
for (let e in this.usedTextures)
this.usedTextures[e].forEach((t) => {
this.gpgpu.deleteMatrixTexture(t.texture);
});
this.freeTextures = null, this.usedTextures = null, this.numUsedTextures = 0, this.numFreeTextures = 0, this._numBytesAllocated = 0, this._numBytesFree = 0;
}
}
};
function n8(e, t) {
let n = e;
if (t === n.R32F)
return 4;
if (t === n.R16F)
return 2;
if (t === n.RGBA32F)
return 16;
if (t === e.RGBA)
return 16;
if (t === n.RGBA16F)
return 8;
if (t === n.RGBA8)
return 4;
throw new Error(`Unknown internal format ${t}`);
}
function mw(e, t, n, s, r) {
let a = s8(t, s), o;
if (r) {
let [u, l] = au(e[0], e[1]);
o = u * l;
} else {
let [u, l] = Jl(e[0], e[1]);
o = u * l;
}
let i = n8(n, a);
return o * i;
}
function s8(e, t) {
switch (e) {
case 3:
return Av(t);
case 4:
return Ev(t);
case 1:
return Tv(t);
case 0:
return $v(t);
case 2:
return _v(t);
default:
throw new Error(`Unknown physical texture type ${e}`);
}
}
function r8(e) {
return K().getBool("WEBGL_RENDER_FLOAT32_ENABLED") ? e ? 3 : 1 : e ? 4 : 0;
}
function gw(e, t) {
if (e === 1)
return 3;
if (e === 0 || e == null)
return r8(t);
if (e === 3 || e === 2)
return 2;
throw new Error(`Unknown logical texture type ${e}`);
}
function bw(e, t, n) {
return `${e[0]}_${e[1]}_${t}_${n}`;
}
var Gs = class {
constructor(e, t) {
this.variableNames = ["A"], this.outputShape = e, this.enableShapeUniforms = Sn(this.outputShape.length), this.userCode = `
float unaryOperation(float x) {
${t}
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
`;
}
};
var ss = "if (isnan(x)) return x;";
var a8 = "return x;";
var yw = "return abs(x);";
var o8 = "return (x >= 0.0) ? x : (exp(x) - 1.0);";
var i8 = ss + `
return (x < 0.0) ? 0.0 : x;
`;
var u8 = ss + `
return (x < 0.0) ? 0.0 : min(6.0, x);
`;
var Vo = "return x;";
var l8 = "return 1.0 / (1.0 + exp(-1.0 * x));";
var c8 = "return x;";
var d8 = `
vec4 result;
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
return result;
`;
var p8 = `
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`;
var h8 = `
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`;
var f8 = "return 1.0 / (1.0 + exp(-1.0 * x));";
var ea = class {
constructor(e, t) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.outputShape = e, this.enableShapeUniforms = Sn(this.outputShape.length), this.userCode = `
vec4 unaryOperation(vec4 x) {
${t}
}
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
}
`;
}
};
var m8 = class {
constructor(e) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = false, this.outputShape = e, this.enableShapeUniforms = Sn(this.outputShape.length);
let t = e.length, n = ln("rc", t), s = rt(t), r = ZX(t, n), a = n.slice(-2), o = t <= 1 ? "rc" : `vec2(${a.join(",")})`;
this.userCode = `
void main() {
${s} rc = getOutputCoords();
vec4 packedInput = getA(${r});
setOutput(getChannel(packedInput, ${o}));
}
`;
}
};
var g8 = ws.whereImpl;
var b8 = 1e-7;
var y8 = 1e-4;
var sd = {};
function v8(e) {
return e in sd || (sd[e] = {}), sd[e];
}
var x8 = K().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");
var w8 = 600;
function k8() {
return K().global.screen == null ? 1024 : K().global.screen.height * K().global.screen.width * window.devicePixelRatio * w8 / 1024 / 1024;
}
var t2 = class extends il {
constructor(e) {
if (super(), this.pendingRead = /* @__PURE__ */ new WeakMap(), this.pendingDisposal = /* @__PURE__ */ new WeakSet(), this.dataRefCount = /* @__PURE__ */ new WeakMap(), this.numBytesInGPU = 0, this.uploadWaitMs = 0, this.downloadWaitMs = 0, this.lastGlFlushTime = 0, this.warnedAboutMemory = false, this.pendingDeletes = 0, this.disposed = false, !K().getBool("HAS_WEBGL"))
throw new Error("WebGL is not supported on this device");
let t;
if (e != null) {
if (e instanceof am)
t = e;
else {
let n = xs(K().getNumber("WEBGL_VERSION"), e);
t = new am(n);
}
this.binaryCache = {}, this.gpgpuCreatedLocally = false;
} else {
let n = xs(K().getNumber("WEBGL_VERSION"));
t = new am(n), this.binaryCache = v8(K().getNumber("WEBGL_VERSION")), this.gpgpuCreatedLocally = true;
}
this.gpgpu = t, this.canvas = this.gpgpu.gl.canvas, this.textureManager = new t8(this.gpgpu), this.numMBBeforeWarning = k8(), this.texData = new Zd(this, ds());
}
nextDataId() {
return t2.nextDataId++;
}
numDataIds() {
return this.texData.numDataIds() - this.pendingDeletes;
}
write(e, t, n) {
if ((K().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS") || K().getBool("DEBUG")) && this.checkNumericalProblems(e), n === "complex64" && e != null)
throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");
let s = { id: this.nextDataId() };
return this.texData.set(s, { shape: t, dtype: n, values: e, usage: 1, refCount: 1 }), s;
}
refCount(e) {
return this.texData.has(e) ? this.texData.get(e).refCount : 0;
}
incRef(e) {
let t = this.texData.get(e);
t.refCount++;
}
decRef(e) {
if (this.texData.has(e)) {
let t = this.texData.get(e);
t.refCount--;
}
}
move(e, t, n, s, r) {
if (K().getBool("DEBUG") && this.checkNumericalProblems(t), s === "complex64")
throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");
this.texData.set(e, { shape: n, dtype: s, values: t, usage: 1, refCount: r });
}
disposeIntermediateTensorInfo(e) {
this.disposeData(e.dataId);
}
readSync(e) {
let t = this.texData.get(e), { values: n, dtype: s, complexTensorInfos: r, slice: a, shape: o, isPacked: i } = t;
if (a != null) {
let p;
i ? p = new ea(o, Vo) : p = new Gs(o, Vo);
let d = this.runWebGLProgram(p, [{ dataId: e, shape: o, dtype: s }], s), h = this.readSync(d.dataId);
return this.disposeIntermediateTensorInfo(d), h;
}
if (n != null)
return this.convertAndCacheOnCPU(e);
if (s === "string")
return n;
let u = this.activeTimers != null, l;
u && (l = w.now());
let c;
if (s === "complex64") {
let p = this.readSync(r.real.dataId), d = this.readSync(r.imag.dataId);
c = C.mergeRealAndImagArrays(p, d);
} else
c = this.getValuesFromTexture(e);
return u && (this.downloadWaitMs += w.now() - l), this.convertAndCacheOnCPU(e, c);
}
async read(e) {
if (this.pendingRead.has(e)) {
let h = this.pendingRead.get(e);
return new Promise((f) => h.push(f));
}
let t = this.texData.get(e), { values: n, shape: s, slice: r, dtype: a, complexTensorInfos: o, isPacked: i } = t;
if (r != null) {
let h;
i ? h = new ea(s, Vo) : h = new Gs(s, Vo);
let f = this.runWebGLProgram(h, [{ dataId: e, shape: s, dtype: a }], a), m = this.read(f.dataId);
return this.disposeIntermediateTensorInfo(f), m;
}
if (n != null)
return this.convertAndCacheOnCPU(e);
if (K().getBool("DEBUG") && !K().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED") && K().getNumber("WEBGL_VERSION") === 2)
throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");
let u = null, l;
if (a !== "complex64" && K().get("WEBGL_BUFFER_SUPPORTED")) {
l = this.decode(e);
let h = this.texData.get(l.dataId);
u = this.gpgpu.createBufferFromTexture(h.texture.texture, ...td(s));
}
this.pendingRead.set(e, []), a !== "complex64" && await this.gpgpu.createAndWaitForFence();
let c;
if (a === "complex64") {
let h = await Promise.all([this.read(o.real.dataId), this.read(o.imag.dataId)]), f = h[0], m = h[1];
c = C.mergeRealAndImagArrays(f, m);
} else if (u == null)
c = this.getValuesFromTexture(e);
else {
let h = w.sizeFromShape(s);
c = this.gpgpu.downloadFloat32MatrixFromBuffer(u, h);
}
if (l != null && this.disposeIntermediateTensorInfo(l), u != null) {
let h = this.gpgpu.gl;
fe(h, () => h.deleteBuffer(u));
}
let p = this.convertAndCacheOnCPU(e, c), d = this.pendingRead.get(e);
return this.pendingRead.delete(e), d.forEach((h) => h(p)), this.pendingDisposal.has(e) && (this.pendingDisposal.delete(e), this.disposeData(e) && ds().removeDataId(e, this), this.pendingDeletes--), p;
}
readToGPU(e, t = {}) {
let n = this.texData.get(e), { values: s, shape: r, slice: a, dtype: o, isPacked: i, texture: u } = n;
if (o === "complex64")
throw new Error("Does not support reading texture for complex64 dtype.");
if (a != null) {
let d;
i ? d = new ea(r, Vo) : d = new Gs(r, Vo);
let h = this.runWebGLProgram(d, [{ dataId: e, shape: r, dtype: o }], o), f = this.readToGPU(h, t);
return this.disposeIntermediateTensorInfo(h), f;
}
if (u == null)
throw s != null ? new Error("Data is not on GPU but on CPU.") : new Error("There is no data on GPU or CPU.");
let l = this.decode(e, t.customTexShape), c = ds().makeTensorFromTensorInfo(l), p = this.texData.get(l.dataId);
return { tensorRef: c, ...p.texture };
}
bufferSync(e) {
let t = this.readSync(e.dataId);
if (e.dtype === "string")
try {
let n = t.map((s) => w.decodeString(s));
return Ae(e.shape, e.dtype, n);
} catch (n) {
throw new Error("Failed to decode encoded string bytes into utf-8");
}
return Ae(e.shape, e.dtype, t);
}
checkNumericalProblems(e) {
if (e != null)
for (let t = 0; t < e.length; t++) {
let n = e[t];
if (!a1(n))
throw K().getBool("WEBGL_RENDER_FLOAT32_CAPABLE") ? Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`) : Error(`The value ${n} cannot be represented on this device.`);
}
}
getValuesFromTexture(e) {
let { shape: t, dtype: n, isPacked: s } = this.texData.get(e), r = w.sizeFromShape(t);
if (K().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")) {
let p = this.decode(e), d = this.texData.get(p.dataId), h = this.gpgpu.downloadMatrixFromPackedTexture(d.texture.texture, ...td(t)).subarray(0, r);
return this.disposeIntermediateTensorInfo(p), h;
}
let a = K().getBool("WEBGL_PACK") && s === true, o = a ? dd(t) : t, i = a ? new uX(o) : new iX(o), u = this.runWebGLProgram(i, [{ shape: o, dtype: n, dataId: e }], "float32"), l = this.texData.get(u.dataId), c = this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(l.texture.texture, l.texShape[0], l.texShape[1]).subarray(0, r);
return this.disposeIntermediateTensorInfo(u), c;
}
timerAvailable() {
return K().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0;
}
time(e) {
let t = this.activeTimers, n = [], s = false;
this.programTimersStack == null ? (this.programTimersStack = n, s = true) : this.activeTimers.push(n), this.activeTimers = n, e();
let r = w.flatten(this.activeTimers.map((i) => i.query)).filter((i) => i != null), a = w.flatten(this.activeTimers.map((i) => i.name)).filter((i) => i != null);
this.activeTimers = t, s && (this.programTimersStack = null);
let o = { uploadWaitMs: this.uploadWaitMs, downloadWaitMs: this.downloadWaitMs, kernelMs: null, wallMs: null };
return (async () => {
if (K().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0) {
let i = await Promise.all(r);
o.kernelMs = w.sum(i), o.getExtraProfileInfo = () => i.map((u, l) => ({ name: a[l], ms: u })).map((u) => `${u.name}: ${u.ms}`).join(", ");
} else
o.kernelMs = { error: "WebGL query timers are not supported in this environment." };
return this.uploadWaitMs = 0, this.downloadWaitMs = 0, o;
})();
}
memory() {
return { unreliable: false, numBytesInGPU: this.numBytesInGPU, numBytesInGPUAllocated: this.textureManager.numBytesAllocated, numBytesInGPUFree: this.textureManager.numBytesFree };
}
startTimer() {
return K().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0 ? this.gpgpu.beginQuery() : { startMs: w.now(), endMs: null };
}
endTimer(e) {
return K().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0 ? (this.gpgpu.endQuery(), e) : (e.endMs = w.now(), e);
}
async getQueryTime(e) {
if (K().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0)
return this.gpgpu.waitForQueryAndGetTime(e);
let t = e;
return t.endMs - t.startMs;
}
disposeData(e, t = false) {
if (this.pendingDisposal.has(e))
return false;
if (!this.texData.has(e))
return true;
if (t ? this.texData.get(e).refCount = 0 : this.texData.get(e).refCount--, !t && this.texData.get(e).refCount > 0)
return false;
if (this.pendingRead.has(e))
return this.pendingDisposal.add(e), this.pendingDeletes++, false;
this.releaseGPUData(e);
let { complexTensorInfos: n } = this.texData.get(e);
return n != null && (this.disposeData(n.real.dataId, t), this.disposeData(n.imag.dataId, t)), this.texData.delete(e), true;
}
releaseGPUData(e) {
let { texture: t, dtype: n, texShape: s, usage: r, isPacked: a, slice: o } = this.texData.get(e), i = o && o.origDataId || e, u = this.dataRefCount.get(i);
u > 1 ? this.dataRefCount.set(i, u - 1) : (this.dataRefCount.delete(i), t != null && (this.numBytesInGPU -= this.computeBytes(s, n), this.textureManager.releaseTexture(t, s, r, a)));
let l = this.texData.get(e);
l.texture = null, l.texShape = null, l.isPacked = false, l.slice = null;
}
getTexture(e) {
return this.uploadToGPU(e), this.texData.get(e).texture.texture;
}
getDataInfo(e) {
return this.texData.get(e);
}
shouldExecuteOnCPU(e, t = x8) {
return K().getBool("WEBGL_CPU_FORWARD") && e.every((n) => this.texData.get(n.dataId).texture == null && w.sizeFromShape(n.shape) < t);
}
getGPGPUContext() {
return this.gpgpu;
}
where(e) {
C.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");
let t = e.dataSync();
return g8(e.shape, t);
}
packedUnaryOp(e, t, n) {
let s = new ea(e.shape, t), r = this.compileAndRun(s, [e], n);
return ds().makeTensorFromTensorInfo(r);
}
abs(e) {
if (this.shouldExecuteOnCPU([e]) && e.dtype !== "complex64") {
let s = Q1(this.texData.get(e.dataId).values);
return this.makeOutput(e.shape, e.dtype, s);
}
if (K().getBool("WEBGL_PACK_UNARY_OPERATIONS"))
return this.packedUnaryOp(e, yw, e.dtype);
let t = new Gs(e.shape, yw), n = this.compileAndRun(t, [e]);
return ds().makeTensorFromTensorInfo(n);
}
makeTensorInfo(e, t, n) {
let s;
if (t === "string" && n != null && n.length > 0 && w.isString(n[0])) {
let r = n.map((a) => w.encodeString(a));
s = this.write(r, e, t);
} else
s = this.write(n, e, t);
return this.texData.get(s).usage = null, { dataId: s, shape: e, dtype: t };
}
makeOutput(e, t, n) {
return ds().makeTensorFromTensorInfo(this.makeTensorInfo(e, t, n), this);
}
unpackTensor(e) {
let t = new m8(e.shape);
return this.runWebGLProgram(t, [e], e.dtype);
}
packTensor(e) {
let t = new JX(e.shape), n = true;
return this.runWebGLProgram(t, [e], e.dtype, null, n);
}
packedReshape(e, t) {
let n = [ya(e.shape), ...va(e.shape)], s = { dtype: e.dtype, shape: n, dataId: e.dataId }, r = [ya(t), ...va(t)], a = new e2(r, n), o = true, i = [n], u = this.runWebGLProgram(a, [s], e.dtype, i, o);
return { dataId: u.dataId, shape: t, dtype: u.dtype };
}
decode(e, t) {
let n = this.texData.get(e), { isPacked: s, shape: r, dtype: a } = n;
if (t != null) {
let p = w.sizeFromShape(r), d = t[0] * t[1] * 4;
w.assert(p <= d, () => "customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.");
}
let o = dd(r), i;
s ? i = new oX(o) : i = new aX(o);
let u = true, l = [t != null ? t : td(o)], c = this.runWebGLProgram(i, [{ shape: o, dtype: a, dataId: e }], a, l, u, t);
return { dtype: a, shape: r, dataId: c.dataId };
}
runWebGLProgram(e, t, n, s, r = false, a) {
let o = this.makeTensorInfo(e.outputShape, n), i = this.texData.get(o.dataId);
if (e.packedOutput && (i.isPacked = true), e.outPackingScheme === 0) {
let g = a != null ? a : td(e.outputShape);
i.texShape = g.map((b) => b * 2);
}
if (e.outTexUsage != null && (i.usage = e.outTexUsage), w.sizeFromShape(o.shape) === 0)
return i.values = w.getTypedArrayFromDType(o.dtype, 0), o;
let u = [], l = t.map((g) => {
if (g.dtype === "complex64")
throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");
let b = this.texData.get(g.dataId);
if (b.texture == null) {
if (!e.packedInputs && w.sizeFromShape(g.shape) <= K().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))
return { shape: g.shape, texData: null, isUniform: true, uniformValues: b.values };
e.packedInputs && (b.isPacked = true, b.shape = g.shape);
}
if (this.uploadToGPU(g.dataId), !!b.isPacked != !!e.packedInputs)
g = b.isPacked ? this.unpackTensor(g) : this.packTensor(g), u.push(g), b = this.texData.get(g.dataId);
else if (b.isPacked && !al(b.shape, g.shape)) {
let y = g, v = g.shape;
g.shape = b.shape, g = this.packedReshape(g, v), u.push(g), b = this.texData.get(g.dataId), y.shape = v;
}
return { shape: g.shape, texData: b, isUniform: false };
});
this.uploadToGPU(o.dataId);
let c = { shape: o.shape, texData: i, isUniform: false }, p = rX(e, l, c), d = this.getAndSaveBinary(p, () => nX(this.gpgpu, e, l, c)), h = this.activeTimers != null, f;
h && (f = this.startTimer()), K().get("ENGINE_COMPILE_ONLY") || sX(this.gpgpu, d, l, c, s), u.forEach((g) => this.disposeIntermediateTensorInfo(g)), h && (f = this.endTimer(f), this.activeTimers.push({ name: e.constructor.name, query: this.getQueryTime(f) }));
let m = K().get("WEBGL_FLUSH_THRESHOLD");
if (m > 0) {
let g = w.now();
g - this.lastGlFlushTime > m && (this.gpgpu.gl.flush(), this.lastGlFlushTime = g);
}
if (!K().getBool("WEBGL_LAZILY_UNPACK") && i.isPacked && r === false) {
let g = this.unpackTensor(o);
return this.disposeIntermediateTensorInfo(o), g;
}
return o;
}
compileAndRun(e, t, n, s, r = false) {
return n = n || t[0].dtype, this.runWebGLProgram(e, t, n, s, r);
}
getAndSaveBinary(e, t) {
return e in this.binaryCache || (this.binaryCache[e] = t()), this.binaryCache[e];
}
getTextureManager() {
return this.textureManager;
}
dispose() {
this.disposed || (K().getBool("IS_TEST") || Object.keys(this.binaryCache).forEach((t) => {
this.gpgpu.deleteProgram(this.binaryCache[t].webGLProgram), delete this.binaryCache[t];
}), this.textureManager.dispose(), this.canvas != null && typeof HTMLCanvasElement != "undefined" && this.canvas instanceof HTMLCanvasElement ? this.canvas.remove() : this.canvas = null, this.gpgpuCreatedLocally && (this.gpgpu.program = null, this.gpgpu.dispose()), this.disposed = true);
}
floatPrecision() {
return this.floatPrecisionValue == null && (this.floatPrecisionValue = q(() => {
if (!K().get("WEBGL_RENDER_FLOAT32_ENABLED")) {
let e = K().getBool("DEBUG");
K().set("DEBUG", false);
let t = this.abs(we(1e-8)).dataSync()[0];
if (K().set("DEBUG", e), t > 0)
return 32;
}
return 16;
})), this.floatPrecisionValue;
}
epsilon() {
return this.floatPrecision() === 32 ? b8 : y8;
}
uploadToGPU(e) {
let t = this.texData.get(e), { shape: n, dtype: s, values: r, texture: a, usage: o, isPacked: i } = t;
if (a != null)
return;
let u = this.activeTimers != null, l;
u && (l = w.now());
let c = t.texShape;
if (c == null && (c = k1(n, i), t.texShape = c), r != null) {
let p = dd(n), d, h = c[1], f = c[0], m = r instanceof Uint8Array || r instanceof Uint8ClampedArray;
(i || !m) && ([h, f] = au(c[0], c[1])), i ? d = new cX(p, m) : d = new lX(p, m);
let g = m ? [f, h] : c, b = this.makeTensorInfo(g, s), y = this.texData.get(b.dataId);
m ? y.usage = 2 : y.usage = 1, y.texShape = g, this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(b.dataId), h, f, r);
let v = [[f, h]], x = true, k = this.runWebGLProgram(d, [b], s, v, x), I = this.texData.get(k.dataId);
t.texShape = I.texShape, t.isPacked = I.isPacked, t.usage = I.usage, K().get("ENGINE_COMPILE_ONLY") ? this.disposeData(k.dataId) : (t.texture = I.texture, t.values = null, this.texData.delete(k.dataId)), this.disposeIntermediateTensorInfo(b), u && (this.uploadWaitMs += w.now() - l);
} else {
let p = this.acquireTexture(c, o, s, i);
t.texture = p;
}
}
convertAndCacheOnCPU(e, t) {
let n = this.texData.get(e), { dtype: s } = n;
return this.releaseGPUData(e), t != null && (n.values = S8(t, s)), n.values;
}
acquireTexture(e, t, n, s) {
if (this.numBytesInGPU += this.computeBytes(e, n), !this.warnedAboutMemory && this.numBytesInGPU > this.numMBBeforeWarning * 1024 * 1024) {
let r = (this.numBytesInGPU / 1024 / 1024).toFixed(2);
this.warnedAboutMemory = true, console.warn(`High memory usage in GPU: ${r} MB, most likely due to a memory leak`);
}
return this.textureManager.acquireTexture(e, t, s);
}
computeBytes(e, t) {
return e[0] * e[1] * w.bytesPerElement(t);
}
checkCompileCompletion() {
for (let [, e] of Object.entries(this.binaryCache))
this.checkCompletion_(e);
}
async checkCompileCompletionAsync() {
let e = [];
if (this.gpgpu.parallelCompilationExtension) {
for (let [, t] of Object.entries(this.binaryCache))
e.push(this.checkCompletionAsync_(t));
return Promise.all(e);
} else {
for (let [, t] of Object.entries(this.binaryCache)) {
let n = new Promise((s) => {
try {
this.checkCompletion_(t), s(true);
} catch (r) {
throw r;
}
});
e.push(n);
}
return Promise.all(e);
}
}
async checkCompletionAsync_(e) {
return this.gpgpu.gl.getProgramParameter(e.webGLProgram, this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR) ? this.checkCompletion_(e) : (await ZS(), this.checkCompletionAsync_(e));
}
checkCompletion_(e) {
if (this.gpgpu.gl.getProgramParameter(e.webGLProgram, this.gpgpu.gl.LINK_STATUS) === false)
throw console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)), this.gpgpu.gl.getShaderParameter(e.fragmentShader, this.gpgpu.gl.COMPILE_STATUS) === false ? (Sv(e.source, this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)), new Error("Failed to compile fragment shader.")) : new Error("Failed to link vertex and fragment shaders.");
return true;
}
getUniformLocations() {
for (let [, e] of Object.entries(this.binaryCache)) {
let { uniformLocations: t, customUniformLocations: n, infLoc: s, nanLoc: r, inShapesLocations: a, inTexShapesLocations: o, outShapeLocation: i, outShapeStridesLocation: u, outTexShapeLocation: l } = D1(this.gpgpu, e.program, e.webGLProgram);
e.uniformLocations = t, e.customUniformLocations = n, e.infLoc = s, e.nanLoc = r, e.inShapesLocations = a, e.inTexShapesLocations = o, e.outShapeLocation = i, e.outShapeStridesLocation = u, e.outTexShapeLocation = l;
}
}
};
var n2 = t2;
n2.nextDataId = 0;
function S8(e, t) {
if (t === "float32" || t === "complex64")
return e;
if (t === "int32" || t === "bool") {
let n = t === "int32" ? new Int32Array(e.length) : new Uint8Array(e.length);
for (let s = 0; s < n.length; ++s)
n[s] = Math.round(e[s]);
return n;
} else
throw new Error(`Unknown dtype ${t}`);
}
var Phe = "0.0.0";
function I8() {
K().set("WEBGL_FORCE_F16_TEXTURES", true);
}
vp.isBrowser() && xp("webgl", () => new n2(), 2);
var zhe = { forceHalfFloat: I8 };
var s2 = `
if (isnan(a)) return a;
if (isnan(b)) return b;
`;
var li = class {
constructor(e, t, n) {
this.variableNames = ["A", "B"], this.outputShape = C.assertAndGetBroadcastShape(t, n), this.enableShapeUniforms = Sn(this.outputShape.length), this.userCode = `
float binaryOperation(float a, float b) {
${e}
}
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
`;
}
};
var nh = `
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
`;
var tc = class {
constructor(e, t, n, s = false) {
this.variableNames = ["A", "B"], this.supportsBroadcasting = true, this.packedInputs = true, this.packedOutput = true, this.outputShape = C.assertAndGetBroadcastShape(t, n);
let r = this.outputShape.length;
this.enableShapeUniforms = Sn(r);
let a = "";
if (s)
if (r === 0 || w.sizeFromShape(this.outputShape) === 1)
a = `
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;
else if (a = `
${rt(r)} coords = getOutputCoords();
`, r === 1)
this.enableShapeUniforms ? a += `
result.y = (coords + 1) >= outShape ? 0. : result.y;
result.z = 0.;
result.w = 0.;
` : a += `
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`;
else {
let i = ln("coords", r);
this.enableShapeUniforms ? a += `
bool nextRowOutOfBounds =
(${i[r - 2]} + 1) >= outShape[${r} - 2];
bool nextColOutOfBounds =
(${i[r - 1]} + 1) >= outShape[${r} - 1];
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
` : a += `
bool nextRowOutOfBounds =
(${i[r - 2]} + 1) >= ${this.outputShape[r - 2]};
bool nextColOutOfBounds =
(${i[r - 1]} + 1) >= ${this.outputShape[r - 1]};
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`;
}
this.userCode = `
vec4 binaryOperation(vec4 a, vec4 b) {
${e}
}
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = binaryOperation(a, b);
${a}
setOutput(result);
}
`;
}
};
function Rn(e) {
let { inputs: t, backend: n } = e, { x: s } = t;
return n.incRef(s.dataId), { dataId: s.dataId, shape: s.shape, dtype: s.dtype };
}
var C8 = { kernelName: Wa, backendName: "webgl", kernelFunc: Rn };
function Fr(e) {
let { inputs: t, backend: n } = e, { real: s, imag: r } = t, a = n.makeTensorInfo(s.shape, "complex64"), o = n.texData.get(a.dataId), i = Rn({ inputs: { x: s }, backend: n }), u = Rn({ inputs: { x: r }, backend: n });
return o.complexTensorInfos = { real: i, imag: u }, a;
}
var N8 = { kernelName: np, backendName: "webgl", kernelFunc: Fr };
var r2 = "return (a < 0.) ? b * a : a;";
var a2 = `
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;
function T8(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { alpha: a } = s, o = n.makeTensorInfo([], "float32", w.createScalarValue(a, "float32")), i = K().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new tc(a2, r.shape, o.shape) : new li(r2, r.shape, o.shape), u = n.runWebGLProgram(i, [r, o], "float32");
return n.disposeIntermediateTensorInfo(o), u;
}
var $8 = { kernelName: Ua, backendName: "webgl", kernelFunc: T8 };
var o2 = "return (a < 0.) ? b * a : a;";
var i2 = `
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;
function _8(e) {
let { inputs: t, backend: n } = e, { x: s, alpha: r } = t, a = K().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new tc(i2, s.shape, r.shape) : new li(o2, s.shape, r.shape);
return n.runWebGLProgram(a, [s, r], "float32");
}
var A8 = { kernelName: to, backendName: "webgl", kernelFunc: _8 };
var du = "if (isnan(x)) return x;";
var E8 = `
if (isnan(a)) return a;
if (isnan(b)) return b;
`;
var R8 = `
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
`;
function Ke({ opSnippet: e, packedOpSnippet: t, cpuKernelImpl: n, dtype: s }) {
return ({ inputs: r, backend: a }) => {
let { x: o } = r, i = a, u = s || o.dtype;
if (i.shouldExecuteOnCPU([o]) && n != null) {
let p = i.texData.get(o.dataId), d = n(p.values, u);
return i.makeTensorInfo(o.shape, u, d);
}
let l = K().getBool("WEBGL_PACK_UNARY_OPERATIONS") && t != null, c;
return l ? c = new ea(o.shape, t) : c = new Gs(o.shape, e), i.runWebGLProgram(c, [o], u);
};
}
function jt({ opSnippet: e, packedOpSnippet: t, checkOutOfBounds: n = false, supportsComplex: s = false, cpuKernelImpl: r, dtype: a }) {
return ({ inputs: o, backend: i }) => {
let { a: u, b: l } = o, c = i;
if (s && u.dtype === "complex64") {
let f = c.texData.get(u.dataId), m = c.texData.get(l.dataId), [g, b] = [[f.complexTensorInfos.real, m.complexTensorInfos.real], [f.complexTensorInfos.imag, m.complexTensorInfos.imag]].map((v) => {
let [x, k] = v, I = { dataId: x.dataId, dtype: x.dtype, shape: u.shape }, $ = { dataId: k.dataId, dtype: k.dtype, shape: l.shape }, R = new li(e, u.shape, l.shape);
return c.runWebGLProgram(R, [I, $], cn(x.dtype, k.dtype));
}), y = Fr({ inputs: { real: g, imag: b }, backend: c });
return c.disposeIntermediateTensorInfo(g), c.disposeIntermediateTensorInfo(b), y;
}
let p = a || cn(u.dtype, l.dtype);
if ((u.dtype === "string" || l.dtype === "string" || c.shouldExecuteOnCPU([u, l])) && r != null) {
let f = c.texData.get(u.dataId).values, m = c.texData.get(l.dataId).values, g = u.dtype === "string" ? C.fromUint8ToStringArray(f) : f, b = u.dtype === "string" ? C.fromUint8ToStringArray(m) : m, [y, v] = r(u.shape, l.shape, g, b, p), x = c.makeTensorInfo(v, p), k = c.texData.get(x.dataId);
return k.values = y, x;
}
let d = K().getBool("WEBGL_PACK_BINARY_OPERATIONS") && t != null, h;
return d ? h = new tc(t, u.shape, l.shape, n) : h = new li(e, u.shape, l.shape), c.runWebGLProgram(h, [u, l], p);
};
}
function sh(e, t = false) {
if (e === "linear")
return t ? c8 : a8;
if (e === "relu")
return t ? p8 : i8;
if (e === "elu")
return t ? d8 : o8;
if (e === "relu6")
return t ? h8 : u8;
if (e === "prelu")
return t ? i2 : o2;
if (e === "leakyrelu")
return t ? a2 : r2;
if (e === "sigmoid")
return t ? f8 : l8;
throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`);
}
var u2 = class {
constructor(e, t, n, s = false, r = false, a = false, o = null, i = false, u = false) {
this.variableNames = ["matrixA", "matrixB"], this.packedInputs = true, this.packedOutput = true, this.outputShape = n, this.enableShapeUniforms = Sn(this.outputShape.length);
let l = s ? e[1] : e[2], c = Math.ceil(l / 2), p = s ? "i * 2, rc.y" : "rc.y, i * 2", d = r ? "rc.z, i * 2" : "i * 2, rc.z", h = s ? ["a.xxyy", "a.zzww"] : ["a.xxzz", "a.yyww"], f = r ? ["b.xzxz", "b.ywyw"] : ["b.xyxy", "b.zwzw"], m = "", g = "";
o && (i ? m = `vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${o}
}` : u ? m = `vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${o}
}` : m = `vec4 activation(vec4 x) {
${o}
}`, g = "result = activation(result);");
let b = a ? "result += getBiasAtOutCoords();" : "";
a && this.variableNames.push("bias"), i && this.variableNames.push("preluActivationWeights"), u && this.variableNames.push("leakyreluAlpha");
let y = "rc.x", v = "rc.x";
e[0] < t[0] ? y = `int(min(float(rc.x), ${e[0] - 1}.))` : t[0] < e[0] && (v = `int(min(float(rc.x), ${t[0] - 1}.))`), this.userCode = `
${m}
// Don't use uniform for sharedDimensionPacked for performance.
const float sharedDimension = ${c}.0;
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
for (int i = 0; i < ${c}; i++) {
int batchA = ${y};
int batchB = ${v};
vec4 a = getMatrixA(batchA, ${p});
vec4 b = getMatrixB(batchB, ${d});
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${h[0]} * ${f[0]});
result += (${h[1]} * ${f[1]});
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
${b}
${g}
setOutput(result);
}
`;
}
};
var vw = { REAL: "return areal * breal - aimag * bimag;", IMAG: "return areal * bimag + aimag * breal;" };
var xw = class {
constructor(e, t, n) {
this.variableNames = ["AReal", "AImag", "BReal", "BImag"], this.outputShape = C.assertAndGetBroadcastShape(t, n), this.userCode = `
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${e}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
`;
}
};
var ww = "return a * b;";
function Dv(e) {
let { inputs: t, backend: n } = e, { a: s, b: r } = t, a = C.upcastType(s.dtype, r.dtype);
if (s.dtype === "complex64") {
let i = n.texData.get(s.dataId), u = n.texData.get(r.dataId), l = new xw(vw.REAL, s.shape, r.shape), c = new xw(vw.IMAG, s.shape, r.shape), p = [{ dataId: i.complexTensorInfos.real.dataId, dtype: i.complexTensorInfos.real.dtype, shape: s.shape }, { dataId: i.complexTensorInfos.imag.dataId, dtype: i.complexTensorInfos.imag.dtype, shape: s.shape }, { dataId: u.complexTensorInfos.real.dataId, dtype: u.complexTensorInfos.real.dtype, shape: r.shape }, { dataId: u.complexTensorInfos.imag.dataId, dtype: u.complexTensorInfos.imag.dtype, shape: r.shape }], d = n.runWebGLProgram(l, p, "float32"), h = n.runWebGLProgram(c, p, "float32"), f = Fr({ inputs: { real: d, imag: h }, backend: n });
return n.disposeIntermediateTensorInfo(d), n.disposeIntermediateTensorInfo(h), f;
}
if (n.shouldExecuteOnCPU([s, r])) {
let i = n.texData.get(s.dataId), u = n.texData.get(r.dataId), [l, c] = RX(s.shape, r.shape, i.values, u.values, a), p = n.makeTensorInfo(c, a), d = n.texData.get(p.dataId);
return d.values = l, p;
}
let o;
return K().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? o = new tc(ww, s.shape, r.shape) : o = new li(ww, s.shape, r.shape), n.runWebGLProgram(o, [s, r], a);
}
var D8 = { kernelName: Za, backendName: "webgl", kernelFunc: Dv };
function F8(e, t, n) {
let s = [ya(e.shape), ...va(e.shape)], r = { dtype: e.dtype, shape: s, dataId: e.dataId }, a = [ya(t), ...va(t)], o = new e2(a, s), i = true, u = [s], l = n.runWebGLProgram(o, [r], e.dtype, u, i);
return { dataId: l.dataId, shape: t, dtype: l.dtype };
}
function pe(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { shape: a } = s, o = n, i = w.sizeFromShape(r.shape), u = w.inferFromImplicitShape(a, i), l = w.sizeFromShape(u);
w.assert(i === l, () => `The new shape (${u}) has ${l} elements and the old shape (${r.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);
let c = o.texData.get(r.dataId);
return c.isPacked && !al(r.shape, u) && !(c.texture !== null && al(c.shape, u)) ? F8(r, u, o) : (o.incRef(r.dataId), { dataId: r.dataId, shape: u, dtype: r.dtype });
}
var O8 = { kernelName: Oi, backendName: "webgl", kernelFunc: pe };
var kw = class {
constructor(e, t) {
this.variableNames = ["x"];
let { windowSize: n, batchSize: s, inSize: r, outSize: a } = e;
this.outputShape = [s, a];
let o = Math.floor(n / 4) * 4, i = n % 4, u = "sumValue += dot(values, ones);";
if (t != null) {
let c = 1 / t;
u = `sumValue += dot(values * ${w.isInt(c) ? c.toPrecision(2) : c}, ones);`;
}
let l = "";
r % n > 0 && (l = `
if (inIdx < 0 || inIdx >= ${r}) {
return 0.0;
}
`), this.userCode = `
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${l}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
float sumValue = 0.0;
for (int i = 0; i < ${o}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${u}
}
int inIdx = inOffset + ${o};
if (${i === 1}) {
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
${u}
} else if (${i === 2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1), 0.0, 0.0);
${u}
} else if (${i === 3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2), 0.0);
${u}
}
setOutput(sumValue);
}
`;
}
};
var P8 = class {
constructor(e, t) {
this.variableNames = ["x"];
let { windowSize: n, batchSize: s, inSize: r, outSize: a } = e;
this.outputShape = [s, a];
let o = "0.0", i = "";
t === "prod" ? o = "1.0" : t === "min" ? (o = "1.0 / 1e-20", i = "min") : t === "max" && (o = "-1.0 / 1e-20", i = "max");
let u = `${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;
t === "sum" ? u = "sumValue" : t === "prod" ? u = "prodValue" : t === "all" ? u = "allValue" : t === "any" && (u = "anyValue");
let l = Math.floor(n / 4) * 4, c = n % 4, p = `
if (${t === "sum"}) {
sumValue += dot(values, ones);
} else if (${t === "prod"}) {
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
minMaxValue = ${i}(values, minMaxValue);
if (${t === "min"} || ${t === "max"}) {
minMaxValue = ${i}(values, minMaxValue);
bvec4 isNaN = isnan(values);
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
minMaxValue = vec4(NAN);
}
}
}
`, d = "vec4";
t === "all" ? (o = "1.0", p = `
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`, d = "bvec4") : t === "any" && (o = "0.0", p = `
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
`, d = "bvec4");
let h = "";
r % n > 0 && (h = `
if (inIdx < 0 || inIdx >= ${r}) {
return initializationValue;
}
`), this.userCode = `
const float initializationValue = ${o};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${h}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
vec4 minMaxValue = vec4(${o});
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
for (int i = 0; i < ${l}; i += 4) {
int inIdx = inOffset + i;
${d} values = ${d}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${p}
}
int inIdx = inOffset + ${l};
if (${c === 1}) {
${d} values = ${d}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
${p}
} else if (${c === 2}) {
${d} values = ${d}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
${p}
} else if (${c === 3}) {
${d} values = ${d}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
${p}
}
setOutput(${u});
}
`;
}
};
function z8(e) {
let t = [];
for (; t.length === 0 || t[t.length - 1].outSize !== 1; ) {
let n = t.length ? t[t.length - 1].outSize : e[1], s = C.computeOptimalWindowSize(n);
t.push({ inSize: n, windowSize: s, outSize: Math.ceil(n / s) });
}
return t;
}
function So(e, t, n, s) {
let r = z8(e.shape), a = e;
for (let o = 0; o < r.length; o++) {
let { inSize: i, windowSize: u, outSize: l } = r[o], c, p;
n === "mean" ? c = o === 0 ? new kw({ windowSize: u, inSize: i, batchSize: e.shape[0], outSize: l }, i) : new kw({ windowSize: u, inSize: i, batchSize: e.shape[0], outSize: l }) : c = new P8({ windowSize: u, inSize: i, batchSize: e.shape[0], outSize: l }, n), p = a, a = s.runWebGLProgram(c, [a], t), p.dataId !== e.dataId && s.disposeIntermediateTensorInfo(p);
}
return a;
}
var L8 = class {
constructor(e, t) {
this.variableNames = ["A"];
let n = new Array(e.length);
for (let a = 0; a < n.length; a++)
n[a] = e[t[a]];
this.outputShape = n, this.rank = n.length;
let s = rt(this.rank), r = M8(t);
this.userCode = `
void main() {
${s} resRC = getOutputCoords();
setOutput(getA(${r}));
}
`;
}
};
function M8(e) {
let t = e.length;
if (t > 6)
throw Error(`Transpose for rank ${t} is not yet supported`);
let n = ["resRC.x", "resRC.y", "resRC.z", "resRC.w", "resRC.u", "resRC.v"], s = new Array(t);
for (let r = 0; r < e.length; r++)
s[e[r]] = n[r];
return s.join();
}
var B8 = class {
constructor(e, t) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true;
let n = new Array(e.length);
for (let l = 0; l < n.length; l++)
n[l] = e[t[l]];
if (this.outputShape = n, this.rank = n.length, this.rank > 6)
throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);
let s = rt(this.rank), r = J1("rc", this.rank), a = new Array(this.rank);
for (let l = 0; l < t.length; l++)
a[t[l]] = r[l];
let o = `vec2(${a.slice(-2).join()})`, i = `++${r[this.rank - 1]} < ${n[this.rank - 1]}`, u = `getChannel(getA(${a.join()}), ${o})`;
this.userCode = `
void main() {
${s} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${u};
if(${i}) {
result[1] = ${u};
}
--${r[this.rank - 1]};
if(++${r[this.rank - 2]} < ${n[this.rank - 2]}) {
result[2] = ${u};
if(${i}) {
result[3] = ${u};
}
}
setOutput(result);
}
`;
}
};
function rh(e, t, n) {
let s = K().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new B8(e.shape, t) : new L8(e.shape, t);
return n.runWebGLProgram(s, [e], e.dtype);
}
function V8(e, t, n, s) {
let r = t, a = e.shape.length, o = w.parseAxisParam(r, e.shape), i = o, u = C.getAxesPermutation(i, a), l = u != null, c = e;
l && (c = rh(e, u, s), i = C.getInnerMostAxes(i.length, a)), C.assertAxesAreInnerMostDims("sum", i, a);
let [p, d] = C.computeOutAndReduceShapes(c.shape, i), h = p;
n && (h = C.expandShapeToKeepDim(p, o));
let f = w.sizeFromShape(d), g = w.sizeFromShape(e.shape) / f, b = pe({ inputs: { x: c }, attrs: { shape: [g, f] }, backend: s }), y = yp(e.dtype), v = So(b, y, "sum", s), x = pe({ inputs: { x: v }, attrs: { shape: h }, backend: s });
return s.disposeIntermediateTensorInfo(b), s.disposeIntermediateTensorInfo(v), l && s.disposeIntermediateTensorInfo(c), x;
}
function ah(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, keepDims: o } = s;
return V8(r, a, o, n);
}
var W8 = { kernelName: co, backendName: "webgl", kernelFunc: ah };
function pn(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { perm: a } = s, o = n, i = r.shape.length, u = new Array(i);
for (let c = 0; c < u.length; c++)
u[c] = r.shape[a[c]];
let l;
if (o.shouldExecuteOnCPU([r])) {
let p = o.texData.get(r.dataId).values, d = Rv(p, r.shape, r.dtype, a, u);
l = o.makeTensorInfo(u, r.dtype);
let h = o.texData.get(l.dataId);
h.values = d;
} else
l = rh(r, a, o);
return l;
}
var U8 = { kernelName: Hs, backendName: "webgl", kernelFunc: pn };
var l2 = 1e3;
function Hd({ a: e, b: t, transposeA: n, transposeB: s, backend: r, bias: a = null, preluActivationWeights: o = null, leakyreluAlpha: i = 0, activation: u = null }) {
let l = e.shape.length, c = t.shape.length, p = n ? e.shape[l - 2] : e.shape[l - 1], d = s ? t.shape[c - 1] : t.shape[c - 2], h = n ? e.shape[l - 1] : e.shape[l - 2], f = s ? t.shape[c - 2] : t.shape[c - 1], m = e.shape.slice(0, -2), g = t.shape.slice(0, -2), b = w.sizeFromShape(m), y = w.sizeFromShape(g), x = Qi.assertAndGetBroadcastShape(e.shape.slice(0, -2), t.shape.slice(0, -2)).concat([h, f]);
w.assert(p === d, () => `Error in matMul: inner shapes (${p}) and (${d}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${s} must match.`);
let k = n ? [b, p, h] : [b, h, p], I = s ? [y, f, d] : [y, d, f], $ = pe({ inputs: { x: e }, backend: r, attrs: { shape: k } }), R = pe({ inputs: { x: t }, backend: r, attrs: { shape: I } }), E = [$, R], P = Math.max(b, y), A = n ? $.shape[1] : $.shape[2], D = a != null, T = o != null, L = u === "leakyrelu", W = u != null ? sh(u, true) : null, j = D || T || L || W != null, Y;
if ((h === 1 || f === 1) && A > l2 && j === false) {
let Z = $, ne = R;
n && (Z = pn({ inputs: { x: $ }, backend: r, attrs: { perm: [0, 2, 1] } }), E.push(Z)), s && (ne = pn({ inputs: { x: R }, backend: r, attrs: { perm: [0, 2, 1] } }), E.push(ne));
let ee = f !== 1, se = f === 1, te = Z;
ee && (te = pe({ inputs: { x: Z }, backend: r, attrs: { shape: [P, A, 1] } }), E.push(te));
let ie = f === 1 ? 2 : 1, ae = ne;
se && (ae = pe({ inputs: { x: ne }, backend: r, attrs: { shape: [P, 1, A] } }), E.push(ae));
let de = Dv({ inputs: { a: te, b: ae }, backend: r });
Y = ah({ inputs: { x: de }, backend: r, attrs: { axis: ie, keepDims: true } }), E.push(de);
} else {
let Z = cn(e.dtype, t.dtype), ne = new u2(k, I, [P, h, f], n, s, D, W, T, L), ee = [$, R];
if (a != null && ee.push(a), T && ee.push(o), L) {
let se = r.makeTensorInfo([], "float32", w.createScalarValue(i, "float32"));
ee.push(se), E.push(se);
}
Y = r.runWebGLProgram(ne, ee, Z);
}
let X = pe({ inputs: { x: Y }, backend: r, attrs: { shape: x } });
E.push(Y);
for (let Z of E)
r.disposeIntermediateTensorInfo(Z);
return X;
}
function G8(e) {
let { inputs: t, backend: n, attrs: s } = e, { a: r, b: a, bias: o, preluActivationWeights: i } = t, { transposeA: u, transposeB: l, activation: c, leakyreluAlpha: p } = s;
return Hd({ a: r, b: a, transposeA: u, transposeB: l, backend: n, bias: o, preluActivationWeights: i, leakyreluAlpha: p, activation: c });
}
var H8 = { kernelName: oa, backendName: "webgl", kernelFunc: G8 };
var Sw = "return abs(x);";
function q8(e) {
let { inputs: t, backend: n } = e, { x: s } = t;
if (n.shouldExecuteOnCPU([s]) && s.dtype !== "complex64") {
let a = n.texData.get(s.dataId), o = Q1(a.values);
return n.makeTensorInfo(s.shape, s.dtype, o);
}
let r;
return K().getBool("WEBGL_PACK_UNARY_OPERATIONS") ? r = new ea(s.shape, Sw) : r = new Gs(s.shape, Sw), n.runWebGLProgram(r, [s], s.dtype);
}
var j8 = { kernelName: di, backendName: "webgl", kernelFunc: q8 };
var K8 = ss + `
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
`;
var X8 = Ke({ opSnippet: K8 });
var Y8 = { kernelName: ul, backendName: "webgl", kernelFunc: X8 };
var Q8 = ss + `
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`;
var Z8 = Ke({ opSnippet: Q8 });
var J8 = { kernelName: ll, backendName: "webgl", kernelFunc: Z8 };
var Iw = "return a + b;";
var eY = jt({ opSnippet: Iw, packedOpSnippet: Iw, supportsComplex: true, cpuKernelImpl: hX });
var tY = { kernelName: Cr, backendName: "webgl", kernelFunc: eY };
var nY = class {
constructor(e, t) {
this.outputShape = [], this.outputShape = e, this.variableNames = t.map((r, a) => `T${a}`);
let n = [];
this.variableNames.forEach((r) => {
n.push(`float v${r} = get${r}AtOutCoords();`);
});
let s = this.variableNames.map((r) => `v${r}`).join(" + ");
this.userCode = `
void main() {
${n.join(`
`)}
float result = ${s};
setOutput(result);
}
`;
}
};
var sY = class {
constructor(e, t) {
this.outputShape = [], this.packedInputs = true, this.packedOutput = true, this.outputShape = e, this.variableNames = t.map((r, a) => `T${a}`);
let n = [];
this.variableNames.forEach((r) => {
n.push(`vec4 v${r} = get${r}AtOutCoords();`);
});
let s = this.variableNames.map((r) => `v${r}`).join(" + ");
this.userCode = `
void main() {
${n.join(`
`)}
vec4 result = ${s};
setOutput(result);
}
`;
}
};
function fd(e) {
let { inputs: t, backend: n } = e, s = t;
if (s.length === 1)
return Rn({ inputs: { x: s[0] }, backend: n });
if (s.length > K().get("WEBGL_MAX_TEXTURES_IN_SHADER")) {
let u = Math.floor(s.length / 2), l = fd({ inputs: s.slice(0, u), backend: n }), c = fd({ inputs: s.slice(u), backend: n });
return fd({ inputs: [l, c], backend: n });
}
let r = s.map((u) => u.dtype).reduce((u, l) => cn(u, l)), a = s.map((u) => u.shape), i = K().getBool("WEBGL_PACK") ? new sY(s[0].shape, a) : new nY(s[0].shape, a);
return n.runWebGLProgram(i, s, r);
}
var rY = { kernelName: Sa, backendName: "webgl", kernelFunc: fd };
function aY(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, keepDims: o } = s, i = r.shape.length, u = w.parseAxisParam(a, r.shape), l = u, c = C.getAxesPermutation(l, i), p = r;
c != null && (p = pn({ inputs: { x: r }, backend: n, attrs: { perm: c } }), l = C.getInnerMostAxes(l.length, i)), C.assertAxesAreInnerMostDims("all", l, i);
let [d, h] = C.computeOutAndReduceShapes(p.shape, l), f = w.sizeFromShape(h), m = pe({ inputs: { x: p }, backend: n, attrs: { shape: [-1, f] } }), g = So(m, m.dtype, "all", n), b;
if (o) {
let y = C.expandShapeToKeepDim(d, u);
b = pe({ inputs: { x: g }, backend: n, attrs: { shape: y } });
} else
b = pe({ inputs: { x: g }, backend: n, attrs: { shape: d } });
return n.disposeIntermediateTensorInfo(m), n.disposeIntermediateTensorInfo(g), c != null && n.disposeIntermediateTensorInfo(p), b;
}
var oY = { kernelName: cl, backendName: "webgl", kernelFunc: aY };
function iY(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, keepDims: o } = s, i = r.shape.length, u = w.parseAxisParam(a, r.shape), l = u, c = C.getAxesPermutation(l, i), p = r;
c != null && (p = pn({ inputs: { x: r }, backend: n, attrs: { perm: c } }), l = C.getInnerMostAxes(l.length, i)), C.assertAxesAreInnerMostDims("any", l, i);
let [d, h] = C.computeOutAndReduceShapes(p.shape, l), f = w.sizeFromShape(h), m = pe({ inputs: { x: p }, backend: n, attrs: { shape: [-1, f] } }), g = So(m, m.dtype, "any", n), b;
if (o) {
let y = C.expandShapeToKeepDim(d, u);
b = pe({ inputs: { x: g }, backend: n, attrs: { shape: y } });
} else
b = pe({ inputs: { x: g }, backend: n, attrs: { shape: d } });
return n.disposeIntermediateTensorInfo(m), n.disposeIntermediateTensorInfo(g), c != null && n.disposeIntermediateTensorInfo(p), b;
}
var uY = { kernelName: dl, backendName: "webgl", kernelFunc: iY };
var lY = class {
constructor(e, t, n) {
this.variableNames = ["A"];
let { windowSize: s, batchSize: r, outSize: a } = e;
n || this.variableNames.push("bestIndicesA"), this.outputShape = [r, a];
let o = t === "max" ? ">" : "<", i = n ? "inOffset + i;" : "round(getBestIndicesA(batch, inOffset + i));";
this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${s};
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
for (int i = 0; i < ${s}; i++) {
int inIdx = ${i};
float candidate = getA(batch, inIdx);
if (candidate ${o} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
`;
}
};
var cY = class {
constructor(e, t, n, s) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, w.assert(e.length > 2, () => `Packed arg${n.charAt(0).toUpperCase() + n.slice(1)} supports only inputs with rank above 2.`);
let r = e[e.length - 1], a = Math.ceil(r / t);
this.outputShape = e.slice(0, -1), a > 1 && this.outputShape.push(a), s || this.variableNames.push("bestIndicesA");
let o = this.outputShape, i = o.length, u = rt(i), l = ln("coords", i), c, p;
if (a === 1) {
p = i + 1;
let $ = rt(p);
c = `
${$} sourceLocR = ${$}(${l.join()}, 0);
++${l[i - 1]};
${$} sourceLocG = ${$}(${l.join()}, 0);
++${l[i - 2]};
${$} sourceLocA = ${$}(${l.join()}, 0);
--${l[i - 1]};
${$} sourceLocB = ${$}(${l.join()}, 0);
--${l[i - 2]};`;
} else
p = i, c = `
${u} sourceLocR = coords;
++${l[i - 1]};
${u} sourceLocG = coords;
++${l[i - 2]};
${u} sourceLocA = coords;
--${l[i - 1]};
${u} sourceLocB = coords;
--${l[i - 2]};`;
let d = ["x", "y", "z", "w", "u", "v"].slice(0, p), h = "." + d[p - 1], f = d.map(($) => "int " + $), m = ln("sourceLocR", p - 1).concat("inIdx.r"), g = ln("sourceLocG", p - 1).concat("inIdx.g"), b = ln("sourceLocB", p - 1).concat("inIdx.b"), y = ln("sourceLocA", p - 1).concat("inIdx.a"), v = n === "max" ? "greaterThan" : "lessThan", x = s ? "" : `
inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),
getBestIndicesAChannel(${g.join()}),
getBestIndicesAChannel(${b.join()}),
getBestIndicesAChannel(${y.join()})));`, k = `vec4(
getAChannel(${m.join()}),
hasNextCol ? getAChannel(${g.join()}) : 0.,
hasNextRow ? getAChannel(${b.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${y.join()}) : 0.)`, I = s ? "" : `
float getBestIndicesAChannel(${f.join()}) {
return getChannel(getBestIndicesA(${d.join()}),
vec2(${d.slice(-2).join()}));
}`;
this.userCode = `
float getAChannel(${f.join()}) {
return getChannel(getA(${d.join()}),
vec2(${d.slice(-2).join()}));
}
${I}
void main() {
${u} coords = getOutputCoords();
bool hasNextCol = ${l[i - 1]} < ${o[i - 1] - 1};
bool hasNextRow = ${l[i - 2]} < ${o[i - 2] - 1};
${c}
ivec4 srcIdx = ivec4(sourceLocR${h}, sourceLocG${h},
sourceLocB${h}, sourceLocA${h}) * ${t};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${k};
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
${x}
vec4 candidate = ${k};
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(${v}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
}
setOutput(bestIndex);
}
`;
}
};
function c2(e, t, n, s = null) {
let r = t.shape[0], a = t.shape[1];
s != null && (r = s.shape[0], a = s.shape[1]);
let o = C.computeOptimalWindowSize(a), i = { windowSize: o, inSize: a, batchSize: r, outSize: Math.ceil(a / o) }, u = new lY(i, n, s == null), l = [t];
s != null && l.push(s);
let c = e.runWebGLProgram(u, l, "int32");
if (c.shape[1] === 1)
return c;
let p = c2(e, t, n, c);
return e.disposeIntermediateTensorInfo(c), p;
}
function d2(e, t, n, s = null) {
let r = s != null ? s.shape : t.shape, a = r[r.length - 1], o = C.computeOptimalWindowSize(a), i = new cY(r, o, n, s == null), u = s == null ? [t] : [t, s], l = e.runWebGLProgram(i, u, "int32");
if (l.shape.length === t.shape.length) {
let c = d2(e, t, n, l);
return e.disposeIntermediateTensorInfo(l), c;
}
return l;
}
function p2(e, t, n, s) {
let r = [n];
if (C.assertAxesAreInnerMostDims("arg" + s.charAt(0).toUpperCase() + s.slice(1), r, t.shape.length), !K().getBool("WEBGL_PACK_REDUCE") || t.shape.length <= 2) {
let a = [], o = e.texData.get(t.dataId), i = o !== null && o.isPacked, u = t;
i && (u = e.unpackTensor(t), a.push(u));
let [l, c] = C.computeOutAndReduceShapes(u.shape, r), p = w.sizeFromShape(c), d = pe({ inputs: { x: u }, backend: e, attrs: { shape: [-1, p] } });
a.push(d);
let h = c2(e, d, s);
a.push(h);
let f = pe({ inputs: { x: h }, backend: e, attrs: { shape: l } });
return a.forEach((m) => e.disposeIntermediateTensorInfo(m)), f;
}
return d2(e, t, s);
}
function dY(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a } = s, o = w.parseAxisParam(a, r.shape), i = C.getAxesPermutation(o, r.shape.length), u = r, l = [];
i != null && (u = pn({ inputs: { x: r }, backend: n, attrs: { perm: i } }), l.push(u), o = C.getInnerMostAxes(o.length, u.shape.length)), C.assertAxesAreInnerMostDims("argMax", [o[0]], u.shape.length);
let c = p2(n, u, o[0], "max");
return l.forEach((p) => n.disposeIntermediateTensorInfo(p)), c;
}
var pY = { kernelName: Ia, backendName: "webgl", kernelFunc: dY };
function hY(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a } = s, o = w.parseAxisParam(a, r.shape), i = C.getAxesPermutation(o, r.shape.length), u = r, l = [];
i != null && (u = pn({ inputs: { x: r }, backend: n, attrs: { perm: i } }), l.push(u), o = C.getInnerMostAxes(o.length, u.shape.length)), C.assertAxesAreInnerMostDims("argMin", [o[0]], u.shape.length);
let c = p2(n, u, o[0], "min");
return l.forEach((p) => n.disposeIntermediateTensorInfo(p)), c;
}
var fY = { kernelName: pl, backendName: "webgl", kernelFunc: hY };
var mY = ss + `
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
`;
var gY = Ke({ opSnippet: mY });
var bY = { kernelName: hl, backendName: "webgl", kernelFunc: gY };
var yY = ss + "return log(x + sqrt(x * x + 1.0));";
var vY = Ke({ opSnippet: yY });
var xY = { kernelName: fl, backendName: "webgl", kernelFunc: vY };
var wY = ss + `
return atan(x);
`;
var kY = Ke({ opSnippet: wY });
var SY = { kernelName: ml, backendName: "webgl", kernelFunc: kY };
var IY = E8 + `
return atan(a, b);
`;
var CY = `
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
` + R8 + `
return result;
`;
var NY = jt({ opSnippet: IY, packedOpSnippet: CY });
var TY = { kernelName: bl, backendName: "webgl", kernelFunc: NY };
var $Y = ss + `
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`;
var _Y = Ke({ opSnippet: $Y });
var AY = { kernelName: gl, backendName: "webgl", kernelFunc: _Y };
var ol = class {
constructor(e, t, n, s = false, r = false) {
if (this.variableNames = ["x"], t === "avg" && n)
throw new Error("Cannot compute positions for average pool.");
let a = e.filterWidth, o = e.strideHeight, i = e.strideWidth, u = e.dilationHeight, l = e.dilationWidth, c = e.effectiveFilterHeight, p = e.effectiveFilterWidth, d = e.padInfo.top, h = e.padInfo.left;
this.outputShape = e.outShape;
let f = t === "avg", m = `((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`, g = `(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`, b = "0.0";
if (f || (b = "-1.0 / 1e-20"), n) {
let $ = ">=";
this.userCode = `
const ivec2 strides = ivec2(${o}, ${i});
const ivec2 pads = ivec2(${d}, ${h});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
float avgValue = 0.0;
for (int wR = 0; wR < ${c};
wR += ${u}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${p};
wC += ${l}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xR, xC, d);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${$} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${s ? r ? m : g : `wR * ${p} + wC`};
}
}
}
setOutput(float(minMaxPosition));
}
`;
return;
}
let y = "max", v = `${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;
t === "avg" && (v = "avgValue / count");
let x = Math.floor(a / 4) * 4, k = a % 4, I = `
if (${f}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${y}(values, minMaxValue);
}
`;
this.userCode = `
const ivec2 strides = ivec2(${o}, ${i});
const ivec2 pads = ivec2(${d}, ${h});
const float initializationValue = ${b};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xR, int xC, int d) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xR, xC, d);
}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
vec4 minMaxValue = vec4(${b});
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < ${c};
wR += ${u}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${x}; wC += 4) {
int xC = xCCorner + wC * ${l};
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${l}, d),
getValue(batch, xR, xC + 2 * ${l}, d),
getValue(batch, xR, xC + 3 * ${l}, d)
);
${I}
}
int xC = xCCorner + ${x};
if (${k === 1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${I}
} else if (${k === 2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${l}, d),
initializationValue,
initializationValue
);
${I}
} else if (${k === 3}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${l}, d),
getValue(batch, xR, xC + 2 * ${l}, d),
initializationValue
);
${I}
}
}
setOutput(${v});
}
`;
}
};
var Fv = class {
constructor(e, t, n, s = false, r = false) {
if (this.variableNames = ["x"], t === "avg" && n)
throw new Error("Cannot compute positions for average pool.");
let a = e.filterWidth, o = e.strideDepth, i = e.strideHeight, u = e.strideWidth, l = e.dilationDepth, c = e.dilationHeight, p = e.dilationWidth, d = e.effectiveFilterDepth, h = e.effectiveFilterHeight, f = e.effectiveFilterWidth, m = e.padInfo.front, g = e.padInfo.top, b = e.padInfo.left;
this.outputShape = e.outShape;
let y = t === "avg", v = "0.0";
if (y || (v = "-1.0 / 1e-20"), n) {
let E = ">=";
this.userCode = `
const ivec3 strides =
ivec3(${o}, ${i}, ${u});
const ivec3 pads = ivec3(${m}, ${g}, ${b});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
for (int wD = 0; wD < ${d};
wD += ${l}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${h};
wR += ${c}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${f};
wC += ${p}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xD, xR, xC, ch);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${E} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${s ? r ? `(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch` : `((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch` : `wD * ${h} * ${f} +
wR * ${f} + wC`};
}
}
}
}
setOutput(float(minMaxPosition));
}
`;
return;
}
let x = "max", k = `${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;
t === "avg" && (k = "avgValue / count");
let I = Math.floor(a / 4) * 4, $ = a % 4, R = `
if (${y}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${x}(values, minMaxValue);
}
`;
this.userCode = `
const ivec3 strides =
ivec3(${o}, ${i}, ${u});
const ivec3 pads = ivec3(${m}, ${g}, ${b});
const float initializationValue = ${v};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
vec4 minMaxValue = vec4(${v});
float avgValue = 0.0;
count = 0.0;
for (int wD = 0; wD < ${d};
wD += ${l}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${h};
wR += ${c}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${I}; wC += 4) {
int xC = xCCorner + wC * ${p};
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${p}, ch),
getValue(batch, xD, xR, xC + 2 * ${p}, ch),
getValue(batch, xD, xR, xC + 3 * ${p}, ch)
);
${R}
}
int xC = xCCorner + ${I};
if (${$ === 1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${R}
} else if (${$ === 2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${p}, ch),
initializationValue,
initializationValue
);
${R}
} else if (${$ === 3}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${p}, ch),
getValue(batch, xD, xR, xC + 2 * ${p}, ch),
initializationValue
);
${R}
}
}
setOutput(${k});
}
}
`;
}
};
function EY(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t;
ou(r, "avgPool");
let { filterSize: a, strides: o, pad: i, dimRoundingMode: u } = s, l = 1;
w.assert(C.eitherStridesOrDilationsAreOne(o, l), () => `Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${l}'`);
let c = C.computePool2DInfo(r.shape, a, o, l, i, u);
if (c.filterWidth === 1 && c.filterHeight === 1 && w.arraysEqual(c.inShape, c.outShape))
return Rn({ inputs: { x: r }, backend: n });
let p = new ol(c, "avg", false);
return n.runWebGLProgram(p, [r], "float32");
}
var RY = { kernelName: Ca, backendName: "webgl", kernelFunc: EY };
function DY(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { filterSize: a, strides: o, pad: i, dimRoundingMode: u, dataFormat: l } = s, c = [1, 1, 1], p = C.computePool3DInfo(r.shape, a, o, c, i, u, l), d = new Fv(p, "avg", false);
return n.runWebGLProgram(d, [r], "float32");
}
var FY = { kernelName: tp, backendName: "webgl", kernelFunc: DY };
var OY = class {
constructor(e) {
this.variableNames = ["dy"], this.outputShape = e.inShape;
let t = e.filterHeight, n = e.filterWidth, s = e.strideHeight, r = e.strideWidth, a = e.dilationHeight, o = e.dilationWidth, i = e.effectiveFilterHeight, u = e.effectiveFilterWidth, l = i - 1 - e.padInfo.top, c = u - 1 - e.padInfo.left, p = 1 / (t * n);
this.userCode = `
const ivec2 pads = ivec2(${l}, ${c});
const float avgMultiplier = float(${p});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${i};
wR += ${a}) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${u};
wC+= ${o}) {
float dyC = float(dyCCorner + wC) / ${r}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
dotProd += dyValue * avgMultiplier;
}
}
setOutput(dotProd);
}
`;
}
};
var PY = class {
constructor(e) {
this.variableNames = ["dy"], this.outputShape = e.inShape;
let t = e.filterDepth, n = e.filterHeight, s = e.filterWidth, r = e.strideDepth, a = e.strideHeight, o = e.strideWidth, i = e.dilationDepth, u = e.dilationHeight, l = e.dilationWidth, c = e.effectiveFilterDepth, p = e.effectiveFilterHeight, d = e.effectiveFilterWidth, h = c - 1 - e.padInfo.front, f = p - 1 - e.padInfo.top, m = d - 1 - e.padInfo.left, g = 1 / (t * n * s);
this.userCode = `
const ivec3 pads = ivec3(${h}, ${f}, ${m});
const float avgMultiplier = float(${g});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${c};
wD += ${i}) {
float dyD = float(dyDCorner + wD) / ${r}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${p};
wR += ${u}) {
float dyR = float(dyRCorner + wR) / ${a}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${d};
wC += ${l}) {
float dyC = float(dyCCorner + wC) / ${o}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
dotProd += dyValue * avgMultiplier;
}
}
}
setOutput(dotProd);
}
`;
}
};
function zY(e) {
let { inputs: t, backend: n, attrs: s } = e, { dy: r, input: a } = t, o = a, { filterSize: i, strides: u, pad: l, dimRoundingMode: c } = s, p = [1, 1, 1], d = C.computePool3DInfo(o.shape, i, u, p, l, c), h = new PY(d);
return n.runWebGLProgram(h, [r], o.dtype);
}
var LY = { kernelName: yg, backendName: "webgl", kernelFunc: zY };
function MY(e) {
let { inputs: t, backend: n, attrs: s } = e, { dy: r, input: a } = t, o = a;
ou([r, a], "avgPoolGrad");
let { filterSize: i, strides: u, pad: l } = s, c = C.computePool2DInfo(o.shape, i, u, 1, l), p = new OY(c);
return n.runWebGLProgram(p, [r], o.dtype);
}
var BY = { kernelName: bg, backendName: "webgl", kernelFunc: MY };
function VY(e) {
let { inputs: t, backend: n, attrs: s } = e, { a: r, b: a } = t, { transposeA: o, transposeB: i } = s;
return Hd({ a: r, b: a, transposeA: o, transposeB: i, backend: n });
}
var WY = { kernelName: Na, backendName: "webgl", kernelFunc: VY };
var UY = class {
constructor(e, t, n, s, r, a) {
this.outputShape = [], this.variableNames = ["x", "mean", "variance"], C.assertAndGetBroadcastShape(e, t), C.assertAndGetBroadcastShape(e, n);
let o = "0.0";
s != null && (C.assertAndGetBroadcastShape(e, s), this.variableNames.push("offset"), o = "getOffsetAtOutCoords()");
let i = "1.0";
r != null && (C.assertAndGetBroadcastShape(e, r), this.variableNames.push("scale"), i = "getScaleAtOutCoords()"), this.outputShape = e, this.userCode = `
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${o};
float scale = ${i};
float inv = scale * inversesqrt(variance + float(${a}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
`;
}
};
var GY = class {
constructor(e, t, n, s, r, a) {
this.packedInputs = true, this.packedOutput = true, this.variableNames = ["x", "mean", "variance"], C.assertAndGetBroadcastShape(e, t), C.assertAndGetBroadcastShape(e, n);
let o = "vec4(0.0)";
s != null && (C.assertAndGetBroadcastShape(e, s), this.variableNames.push("offset"), o = "getOffsetAtOutCoords()");
let i = "vec4(1.0)";
r != null && (C.assertAndGetBroadcastShape(e, r), this.variableNames.push("scale"), i = "getScaleAtOutCoords()"), this.outputShape = e, this.userCode = `
void main() {
vec4 offset = ${o};
vec4 scale = ${i};
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
vec4 inv = scale * inversesqrt(variance + vec4(${a}));
setOutput((x - mean) * inv + offset);
}
`;
}
};
var HY = ({ inputs: e, backend: t, attrs: n }) => {
let { x: s, mean: r, variance: a, offset: o, scale: i } = e;
w.assert(r.shape.length === a.shape.length, () => "Batch normalization gradient requires mean and variance to have equal ranks."), w.assert(o == null || r.shape.length === o.shape.length, () => "Batch normalization gradient requires mean and offset to have equal ranks."), w.assert(i == null || r.shape.length === i.shape.length, () => "Batch normalization gradient requires mean and scale to have equal ranks.");
let { varianceEpsilon: u } = n;
u == null && (u = 1e-3);
let l = [s, r, a], c = null;
o != null && (c = o.shape, l.push(o));
let p = null;
i != null && (p = i.shape, l.push(i));
let d = K().getBool("WEBGL_PACK_NORMALIZATION") ? new GY(s.shape, r.shape, a.shape, c, p, u) : new UY(s.shape, r.shape, a.shape, c, p, u);
return t.runWebGLProgram(d, l, l[0].dtype);
};
var qY = { kernelName: Ba, backendName: "webgl", kernelFunc: HY };
var jY = class {
constructor(e) {
this.variableNames = ["source"], this.outputShape = e, this.rank = e.length;
let t = rt(this.rank);
this.customUniforms = [{ name: "start", arrayIndex: this.rank, type: "int" }];
let n = KY(this.rank), s, r = e.map((a, o) => `sourceLoc.${ng[o]} = start[${o}] + coords.${ng[o]};`);
s = `
${t} sourceLoc;
${t} coords = getOutputCoords();
${r.join(`
`)}
`, this.userCode = `
void main() {
${s}
setOutput(getSource(${n}));
}
`;
}
};
var ng = ["x", "y", "z", "w", "u", "v"];
function KY(e) {
if (e === 1)
return "sourceLoc";
if (e <= 6)
return ng.slice(0, e).map((t) => "sourceLoc." + t).join(",");
throw Error(`Slicing for rank ${e} is not yet supported`);
}
var XY = class {
constructor(e) {
this.variableNames = ["source"], this.packedInputs = true, this.packedOutput = true, this.outputShape = e, this.rank = e.length, this.customUniforms = [{ name: "start", arrayIndex: this.rank, type: "int" }];
let t = rt(this.rank), n = ln("coords", this.rank), s = ln("sourceLoc", this.rank), r = this.rank === 1 ? "sourceLoc" : `vec2(${s.slice(-2).join()})`, a = `getChannel(getSource(${s.join()}), ${r})`, o = `
result.x = ${a};
if (++${n[this.rank - 1]} < ${e[this.rank - 1]}) {
++${s[this.rank - 1]};
result.y = ${a};
--${s[this.rank - 1]};
}
`, i = this.rank === 1 ? "" : `
--${n[this.rank - 1]};
if (++${n[this.rank - 2]} < ${e[this.rank - 2]}) {
++${s[this.rank - 2]};
result.z = ${a};
if (++${n[this.rank - 1]} < ${e[this.rank - 1]}) {
++${s[this.rank - 1]};
result.w = ${a};
}
}
`, u = this.rank <= 4 ? `sourceLoc = coords +
${t}(${e.map((l, c) => `start[${c}]`).join()});` : e.map((l, c) => `${s[c]} = ${n[c]} + start[${c}];`).join(`
`);
this.userCode = `
void main() {
${t} coords = getOutputCoords();
${t} sourceLoc;
${u}
vec4 result = vec4(0.);
${o}
${i}
setOutput(result);
}
`;
}
};
function YY(e, t, n, s) {
let r = s.texData.get(e.dataId), a = s.makeTensorInfo(n, e.dtype), o = s.texData.get(a.dataId);
Object.assign(o, r), o.refCount = 1, o.shape = n, o.dtype = e.dtype;
let i = kt.computeFlatOffset(t, w.computeStrides(e.shape));
r.slice && (i += r.slice.flatOffset), o.slice = { flatOffset: i, origDataId: r.slice && r.slice.origDataId || e.dataId };
let u = s.dataRefCount.get(o.slice.origDataId) || 1;
return s.dataRefCount.set(o.slice.origDataId, u + 1), a;
}
function pu(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { begin: a, size: o } = s, [i, u] = kt.parseSliceParams(r, a, o);
if (kt.assertParamsValid(r, i, u), w.sizeFromShape(u) === 0)
return n.makeTensorInfo(u, r.dtype, []);
if (n.shouldExecuteOnCPU([r]) || r.dtype === "string") {
let p = n.texData.get(r.dataId), d = BX(p.values, i, u, r.shape, r.dtype);
return n.makeTensorInfo(u, r.dtype, d);
}
let { isPacked: l } = n.texData.get(r.dataId), c = kt.isSliceContinous(r.shape, i, u);
if (l || !c) {
let p = K().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new XY(u) : new jY(u), d = [i];
return n.runWebGLProgram(p, [r], r.dtype, d);
}
return n.uploadToGPU(r.dataId), YY(r, i, u, n);
}
var QY = { kernelName: Bi, backendName: "webgl", kernelFunc: pu };
var ZY = (e) => {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { blockShape: a, crops: o } = s;
w.assert(r.shape.length <= 4, () => "batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");
let i = a.reduce((y, v) => y * v), u = C.getReshaped(r.shape, a, i), l = C.getPermuted(u.length, a.length), c = C.getReshapedPermuted(r.shape, a, i), p = C.getSliceBeginCoords(o, a.length), d = C.getSliceSize(c, o, a.length), h = [], f = pe({ inputs: { x: r }, backend: n, attrs: { shape: u } }), m = pn({ inputs: { x: f }, backend: n, attrs: { perm: l } }), g = pe({ inputs: { x: m }, backend: n, attrs: { shape: c } }), b = pu({ inputs: { x: g }, backend: n, attrs: { begin: p, size: d } });
return h.push(f), h.push(m), h.push(g), h.forEach((y) => n.disposeIntermediateTensorInfo(y)), b;
};
var JY = { kernelName: pi, backendName: "webgl", kernelFunc: ZY };
function e9(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, weights: a } = t, { size: o } = s, i = n.readSync(r.dataId), u = n.readSync(a.dataId), l = Y1(i, u, a.dtype, a.shape, o);
return n.makeTensorInfo([o], a.dtype, l);
}
var t9 = { kernelName: vg, backendName: "webgl", kernelFunc: e9 };
function n9(e) {
let { inputs: t, backend: n } = e, { s0: s, s1: r } = t, a = n.readSync(s.dataId), o = n.readSync(r.dataId), i = C.assertAndGetBroadcastShape(Array.from(a), Array.from(o));
return n.makeTensorInfo([i.length], "int32", Int32Array.from(i));
}
var s9 = { kernelName: xg, backendName: "webgl", kernelFunc: n9 };
var r9 = "return float(a != b);";
var h2 = jt({ opSnippet: r9, cpuKernelImpl: FX, dtype: "bool" });
var a9 = { kernelName: _i, backendName: "webgl", kernelFunc: h2 };
function nc(e) {
let { inputs: t, backend: n } = e, { input: s } = t, r = n.texData.get(s.dataId);
return Rn({ inputs: { x: r.complexTensorInfos.real }, backend: n });
}
var o9 = { kernelName: cp, backendName: "webgl", kernelFunc: nc };
var i9 = "return float(int(x));";
function u9(e, t) {
let n = new Gs(e.shape, i9), s = t.runWebGLProgram(n, [e], "int32");
return { dataId: s.dataId, shape: s.shape, dtype: s.dtype };
}
function sg(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { dtype: a } = s;
if (a === "complex64") {
if (r.dtype === "complex64")
return Rn({ inputs: { x: r }, backend: n });
let o = $t(r.shape), i = sg({ inputs: { x: r }, backend: n, attrs: { dtype: "float32" } }), u = Fr({ inputs: { real: i, imag: o }, backend: n });
return o.dispose(), n.disposeIntermediateTensorInfo(i), u;
}
if (r.dtype === "complex64") {
let o = nc({ inputs: { input: r }, backend: n }), i = sg({ inputs: { x: o }, backend: n, attrs: { dtype: a } });
return n.disposeIntermediateTensorInfo(o), i;
}
if (!w.hasEncodingLoss(r.dtype, a)) {
let o = Rn({ inputs: { x: r }, backend: n });
return { dataId: o.dataId, shape: o.shape, dtype: a };
}
if (a === "int32")
return u9(r, n);
if (a === "bool") {
let o = n.makeTensorInfo([], "bool", w.getTypedArrayFromDType("bool", 1)), u = h2({ inputs: { a: r, b: o }, backend: n });
return n.disposeIntermediateTensorInfo(o), u;
}
throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${a}`);
}
var l9 = { kernelName: Ta, backendName: "webgl", kernelFunc: sg };
var Cw = "return ceil(x);";
var c9 = Ke({ opSnippet: Cw, packedOpSnippet: Cw, cpuKernelImpl: mX });
var d9 = { kernelName: $a, backendName: "webgl", kernelFunc: c9 };
var p9 = class {
constructor(e) {
this.variableNames = ["A"], this.customUniforms = [{ name: "minVal", type: "float" }, { name: "maxVal", type: "float" }], this.outputShape = e, this.userCode = `
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
setOutput(clamp(value, minVal, maxVal));
}
`;
}
};
var h9 = class {
constructor(e) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.customUniforms = [{ name: "minVal", type: "float" }, { name: "maxVal", type: "float" }], this.outputShape = e, this.userCode = `
void main() {
vec4 value = getAAtOutCoords();
if (any(isnan(value))) {
setOutput(value);
return;
}
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
`;
}
};
function f9(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { clipValueMin: a, clipValueMax: o } = s, i;
K().getBool("WEBGL_PACK_CLIP") ? i = new h9(r.shape) : i = new p9(r.shape);
let u = [[a], [o]];
return n.runWebGLProgram(i, [r], r.dtype, u);
}
var m9 = { kernelName: Nr, backendName: "webgl", kernelFunc: f9 };
var g9 = class {
constructor(e) {
this.variableNames = ["real", "imag"], this.outputShape = e, this.userCode = `
void main() {
float re = abs(getRealAtOutCoords());
float im = abs(getImagAtOutCoords());
float mx = max(re, im);
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput(
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
);
}
`;
}
};
function Nw(e, t) {
return { dataId: t.dataId, dtype: t.dtype, shape: e.shape };
}
function b9(e) {
let { inputs: t, backend: n } = e, { x: s } = t, r = n.texData.get(s.dataId), a = new g9(s.shape), o = [Nw(s, r.complexTensorInfos.real), Nw(s, r.complexTensorInfos.imag)];
return n.runWebGLProgram(a, o, o[0].dtype);
}
var y9 = { kernelName: sp, backendName: "webgl", kernelFunc: b9 };
var v9 = class {
constructor(e) {
this.outputShape = [], this.outputShape = C.computeOutShape(e, 1), this.variableNames = e.map((a, o) => `T${o}`);
let t = new Array(e.length - 1);
t[0] = e[0][1];
for (let a = 1; a < t.length; a++)
t[a] = t[a - 1] + e[a][1];
let n = [`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];
for (let a = 1; a < t.length; a++) {
let o = t[a - 1];
n.push(`else if (yC < ${t[a]}) setOutput(getT${a}(yR, yC-${o}));`);
}
let s = t.length, r = t[t.length - 1];
n.push(`else setOutput(getT${s}(yR, yC-${r}));`), this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
${n.join(`
`)}
}
`;
}
};
var x9 = class {
constructor(e, t) {
this.packedInputs = true, this.packedOutput = true, this.outputShape = [], this.outputShape = C.computeOutShape(e, t);
let n = this.outputShape, s = n.length, r = rt(s), a = ln("coords", s), o = ["x", "y", "z", "w", "u", "v"].slice(0, s);
this.variableNames = e.map((f, m) => `T${m}`);
let i = new Array(e.length - 1);
i[0] = e[0][t];
for (let f = 1; f < i.length; f++)
i[f] = i[f - 1] + e[f][t];
let u = o[t], l = o.slice(-2), c = o.join(), p = `if (${u} < ${i[0]}) {
return getChannel(
getT0(${c}), vec2(${l.join()}));
}`;
for (let f = 1; f < i.length; f++) {
let m = i[f - 1];
p += `
if (${u} < ${i[f]} && ${u} >= ${i[f - 1]}) {
return getChannel(
getT${f}(${rd(o, u, m)}),
vec2(${rd(l, u, m)}));
}`;
}
let d = i.length, h = i[i.length - 1];
p += `
return getChannel(
getT${d}(${rd(o, u, h)}),
vec2(${rd(l, u, h)}));`, this.userCode = `
float getValue(${o.map((f) => "int " + f)}) {
${p}
}
void main() {
${r} coords = getOutputCoords();
vec4 result = vec4(getValue(${a}), 0., 0., 0.);
${a[s - 1]} = ${a[s - 1]} + 1;
if (${a[s - 1]} < ${n[s - 1]}) {
result.g = getValue(${a});
}
${a[s - 2]} = ${a[s - 2]} + 1;
if (${a[s - 2]} < ${n[s - 2]}) {
result.a = getValue(${a});
}
${a[s - 1]} = ${a[s - 1]} - 1;
if (${a[s - 2]} < ${n[s - 2]} &&
${a[s - 1]} < ${n[s - 1]}) {
result.b = getValue(${a});
}
setOutput(result);
}
`;
}
};
function rd(e, t, n) {
let s = e.indexOf(t);
return e.map((a, o) => o === s ? `${a} - ${n}` : a).join();
}
function oh(e) {
let { inputs: t, backend: n } = e, { input: s } = t, r = n.texData.get(s.dataId);
return Rn({ inputs: { x: r.complexTensorInfos.imag }, backend: n });
}
var w9 = { kernelName: ip, backendName: "webgl", kernelFunc: oh };
function jo(e, t, n) {
let s = e[0].dtype;
if (s === "complex64") {
let c = e.map((m) => nc({ inputs: { input: m }, backend: n })), p = e.map((m) => oh({ inputs: { input: m }, backend: n })), d = jo(c, t, n), h = jo(p, t, n), f = Fr({ inputs: { real: d, imag: h }, backend: n });
return c.forEach((m) => n.disposeIntermediateTensorInfo(m)), p.forEach((m) => n.disposeIntermediateTensorInfo(m)), n.disposeIntermediateTensorInfo(d), n.disposeIntermediateTensorInfo(h), f;
}
let r = n.shouldExecuteOnCPU(e);
if (s === "string" && (r = true), r) {
let c = e.map((b) => {
let y = w.sizeFromShape(b.shape.slice(t));
return pe({ inputs: { x: b }, backend: n, attrs: { shape: [-1, y] } });
}), p = c.map((b) => ({ vals: n.readSync(b.dataId), shape: b.shape })), d = C.computeOutShape(c.map((b) => b.shape), 1), h = c[0].shape[0] === 1, f = gX(p, d, s, h), m = C.computeOutShape(e.map((b) => b.shape), t), g = n.makeTensorInfo(m, s, f);
return c.forEach((b) => n.disposeIntermediateTensorInfo(b)), g;
}
if (e.length > K().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")) {
let c = Math.floor(e.length / 2), p = jo(e.slice(0, c), t, n), d = jo(e.slice(c), t, n), h = jo([p, d], t, n);
return n.disposeIntermediateTensorInfo(p), n.disposeIntermediateTensorInfo(d), h;
}
if (K().getBool("WEBGL_PACK_ARRAY_OPERATIONS") && e[0].shape.length > 1) {
let c = new x9(e.map((p) => p.shape), t);
return n.runWebGLProgram(c, e, s);
}
let { tensors2D: a, outShape: o } = k9(e, t, n), i = new v9(a.map((c) => c.shape)), u = n.runWebGLProgram(i, a, s);
a.forEach((c) => n.disposeIntermediateTensorInfo(c));
let l = pe({ inputs: { x: u }, attrs: { shape: o }, backend: n });
return n.disposeIntermediateTensorInfo(u), l;
}
function k9(e, t, n) {
let s = C.computeOutShape(e.map((a) => a.shape), t);
return { tensors2D: e.map((a) => pe({ inputs: { x: a }, attrs: { shape: [-1, w.sizeFromShape(a.shape.slice(t))] }, backend: n })), outShape: s };
}
function f2(e) {
let { inputs: t, backend: n, attrs: s } = e, { axis: r } = s, a = w.parseAxisParam(r, t[0].shape)[0], o = C.computeOutShape(t.map((l) => l.shape), a);
if (w.sizeFromShape(o) === 0)
return n.makeTensorInfo(o, t[0].dtype, []);
let i = t.filter((l) => w.sizeFromShape(l.shape) > 0);
if (i.length === 1)
return Rn({ inputs: { x: i[0] }, backend: n });
let u = i.map((l) => l.shape);
return C.assertParamsConsistent(u, a), jo(i, a, n);
}
var S9 = { kernelName: hi, backendName: "webgl", kernelFunc: f2 };
var m2 = class {
constructor(e, t = false, n = null, s = false, r = false) {
this.variableNames = ["x", "W"], this.outputShape = e.outShape;
let a = e.padInfo.top, o = e.padInfo.left, i = e.strideHeight, u = e.strideWidth, l = e.dilationHeight, c = e.dilationWidth, p = e.filterHeight, d = e.filterWidth, h = Math.floor(e.inChannels / 4) * 4, f = e.inChannels % 4, m = e.dataFormat === "channelsLast", g = m ? 1 : 2, b = m ? 2 : 3, y = m ? 3 : 1, v = "", x = "";
n && (s ? v = `float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${n}
}` : r ? v = `float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${n}
}` : v = `
float activation(float x) {
${n}
}
`, x = "result = activation(result);");
let k = t ? "result += getBiasAtOutCoords();" : "";
t && this.variableNames.push("bias"), s && this.variableNames.push("preluActivationWeights"), r && this.variableNames.push("leakyreluAlpha"), this.userCode = `
${v}
const ivec2 strides = ivec2(${i}, ${u});
const ivec2 pads = ivec2(${a}, ${o});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[${y}];
ivec2 xRCCorner =
ivec2(coords[${g}], coords[${b}]) * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${p}; wR++) {
int xR = xRCorner + wR * ${l};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${d}; wC++) {
int xC = xCCorner + wC * ${c};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${h}; d1 += 4) {
vec4 wValues = vec4(
getW(wR, wC, d1, d2),
getW(wR, wC, d1 + 1, d2),
getW(wR, wC, d1 + 2, d2),
getW(wR, wC, d1 + 3, d2)
);
if (${m}) {
vec4 xValues = vec4(
getX(batch, xR, xC, d1),
getX(batch, xR, xC, d1 + 1),
getX(batch, xR, xC, d1 + 2),
getX(batch, xR, xC, d1 + 3)
);
dotProd += dot(xValues, wValues);
} else {
vec4 xValues = vec4(
getX(batch, d1, xR, xC),
getX(batch, d1 + 1, xR, xC),
getX(batch, d1 + 2, xR, xC),
getX(batch, d1 + 3, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
if (${f === 1}) {
if (${m}) {
dotProd +=
getX(batch, xR, xC, ${h}) *
getW(wR, wC, ${h}, d2);
} else {
dotProd +=
getX(batch, ${h}, xR, xC) *
getW(wR, wC, ${h}, d2);
}
} else if (${f === 2}) {
vec2 wValues = vec2(
getW(wR, wC, ${h}, d2),
getW(wR, wC, ${h} + 1, d2)
);
if (${m}) {
vec2 xValues = vec2(
getX(batch, xR, xC, ${h}),
getX(batch, xR, xC, ${h} + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, ${h}, xR, xC),
getX(batch, ${h} + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
} else if (${f === 3}) {
vec3 wValues = vec3(
getW(wR, wC, ${h}, d2),
getW(wR, wC, ${h} + 1, d2),
getW(wR, wC, ${h} + 2, d2)
);
if (${m}) {
vec3 xValues = vec3(
getX(batch, xR, xC, ${h}),
getX(batch, xR, xC, ${h} + 1),
getX(batch, xR, xC, ${h} + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, ${h}, xR, xC),
getX(batch, ${h} + 1, xR, xC),
getX(batch, ${h} + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
}
}
float result = dotProd;
${k}
${x}
setOutput(result);
}
`;
}
};
var I9 = class {
constructor(e) {
this.variableNames = ["x", "W"], this.outputShape = e.outShape;
let t = e.padInfo.front, n = e.padInfo.top, s = e.padInfo.left, r = e.strideDepth, a = e.strideHeight, o = e.strideWidth, i = e.dilationDepth, u = e.dilationHeight, l = e.dilationWidth, c = e.filterDepth, p = e.filterHeight, d = e.filterWidth, h = Math.floor(e.inChannels / 4) * 4, f = e.inChannels % 4;
this.userCode = `
const ivec3 strides = ivec3(${r}, ${a}, ${o});
const ivec3 pads = ivec3(${t}, ${n}, ${s});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d2 = coords.u;
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xFCorner = xFRCCorner.x;
int xRCorner = xFRCCorner.y;
int xCCorner = xFRCCorner.z;
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0;
for (int wF = 0; wF < ${c}; wF++) {
int xF = xFCorner + wF * ${i};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${p}; wR++) {
int xR = xRCorner + wR * ${u};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${d}; wC++) {
int xC = xCCorner + wC * ${l};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${h}; d1 += 4) {
vec4 xValues = vec4(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3)
);
vec4 wValues = vec4(
getW(wF, wR, wC, d1, d2),
getW(wF, wR, wC, d1 + 1, d2),
getW(wF, wR, wC, d1 + 2, d2),
getW(wF, wR, wC, d1 + 3, d2)
);
dotProd += dot(xValues, wValues);
}
if (${f === 1}) {
dotProd +=
getX(batch, xF, xR, xC, ${h}) *
getW(wF, wR, wC, ${h}, d2);
} else if (${f === 2}) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, ${h}),
getX(batch, xF, xR, xC, ${h} + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, ${h}, d2),
getW(wF, wR, wC, ${h} + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (${f === 3}) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, ${h}),
getX(batch, xF, xR, xC, ${h} + 1),
getX(batch, xF, xR, xC, ${h} + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, ${h}, d2),
getW(wF, wR, wC, ${h} + 1, d2),
getW(wF, wR, wC, ${h} + 2, d2)
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutput(dotProd);
}
`;
}
};
var C9 = class {
constructor(e, t) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.customUniforms = [{ name: "inputShape", type: "ivec4" }, { name: "pad", type: "ivec2" }, { name: "stride", type: "ivec2" }, { name: "dilation", type: "ivec2" }, { name: "inChannels", type: "int" }, { name: "itemsPerBlockRow", type: "int" }, { name: "outWidth", type: "int" }], this.outputShape = e, this.enableShapeUniforms = Sn(this.outputShape.length);
let { dataFormat: n } = t, s = mn(), r = n === "channelsLast", a = r ? 1 : 2, o = r ? 2 : 3, i = this.enableShapeUniforms ? "if(blockIndex < outShape[2] && pos < outShape[1]) {" : `if(blockIndex < ${e[2]} && pos < ${e[1]}) {`, u = "";
for (let l = 0; l <= 1; l++)
for (let c = 0; c <= 1; c++)
u += `
blockIndex = rc.z + ${c};
pos = rc.y + ${l};
${i}
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
if(d0 < inputShape[${a}] && d0 >= 0) {
// Use custom imod instead mod. On Intel GPU, mod may generate
// unexpected value.
// https://github.com/tensorflow/tfjs/issues/5447
offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];
d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /
inChannels);
if(d1 < inputShape[${o}] && d1 >= 0) {
ch = imod(pos, inChannels);
if (${r}) {
innerDims = vec2(d1, ch);
result[${l * 2 + c}] = getChannel(
getA(rc.x, d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${l * 2 + c}] = getChannel(
getA(rc.x, ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;
this.userCode = `
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
${u}
${s.output} = result;
}
`;
}
};
function qd(e, t) {
let n = e.length;
return n >= 3 ? t ? [...e.slice(0, -3), e[n - 3] * e[n - 2], e[n - 1]] : [...e.slice(0, -3), e[n - 3], e[n - 2] * e[n - 1]] : !t && n === 1 && e[0] > 1 ? [e[0], 1] : null;
}
function g2({ x: e, filter: t, convInfo: n, backend: s, bias: r = null, preluActivationWeights: a = null, leakyreluAlpha: o = 0, activation: i = null }) {
let u = e.shape, l = s.texData.get(e.dataId), c = n.inChannels, p = u[0] * u[1] * u[2], d = n.outChannels, h = n.dataFormat === "channelsLast", f = false, m = false, g, b = [];
if (a != null) {
let x = qd(a.shape, h);
x != null && (a = pe({ inputs: { x: a }, backend: s, attrs: { shape: x } }), b.push(a));
}
if (r != null) {
let x = qd(r.shape, h);
x != null && (r = pe({ inputs: { x: r }, backend: s, attrs: { shape: x } }), b.push(r));
}
if (!((p === 1 || d === 1) && c > l2) && l.isPacked && h && l.texture != null && u[2] % 2 !== 0 && w.arraysEqual(l.shape.slice(-3), u.slice(-3))) {
let x = u[0] * u[1] * (u[2] + 1), k = { dataId: e.dataId, shape: [1, x, n.inChannels], dtype: e.dtype }, I = l.shape;
l.shape = l.shape.slice(), l.shape[l.shape.length - 2]++, w.assert(al(l.shape, k.shape), () => `packed reshape ${l.shape} to ${k.shape} isn't free`);
let $ = pe({ inputs: { x: t }, backend: s, attrs: { shape: [1, n.inChannels, n.outChannels] } });
b.push($);
let R = Hd({ a: k, b: $, backend: s, transposeA: f, transposeB: m, bias: r, activation: i, preluActivationWeights: a, leakyreluAlpha: o }), E = s.texData.get(R.dataId);
w.assert(E.isPacked, () => "batchMatMul result is expected to be packed"), l.shape = I, E.shape = n.outShape, g = Rn({ inputs: { x: R }, backend: s }), g.shape = n.outShape, b.push(R);
} else {
let x = n.outHeight * n.outWidth, k = pe({ inputs: { x: e }, backend: s, attrs: { shape: h ? [n.batchSize, x, n.inChannels] : [n.batchSize, n.inChannels, x] } }), I = pe({ inputs: { x: t }, backend: s, attrs: { shape: [1, n.inChannels, n.outChannels] } }), $ = Hd({ a: h ? k : I, b: h ? I : k, transposeA: !h, transposeB: m, backend: s, bias: r, activation: i, preluActivationWeights: a, leakyreluAlpha: o });
g = pe({ inputs: { x: $ }, backend: s, attrs: { shape: n.outShape } }), b.push(k), b.push(I), b.push($);
}
for (let x of b)
s.disposeIntermediateTensorInfo(x);
return g;
}
function b2({ x: e, filter: t, convInfo: n, backend: s, bias: r = null, preluActivationWeights: a = null, leakyreluAlpha: o = 0, activation: i = null }) {
let { filterWidth: u, filterHeight: l, inChannels: c, outWidth: p, outHeight: d, dataFormat: h } = n, f = h === "channelsLast", m = u * l * c, g = d * p, b = [n.batchSize, m, g], y = true, v = false, x = [];
if (a != null) {
let X = qd(a.shape, f);
X != null && (a = pe({ inputs: { x: a }, backend: s, attrs: { shape: X } }), x.push(a));
}
if (r != null) {
let X = qd(r.shape, f);
X != null && (r = pe({ inputs: { x: r }, backend: s, attrs: { shape: X } }), x.push(r));
}
let k = pe({ inputs: { x: t }, backend: s, attrs: { shape: [1, m, w.sizeFromShape(t.shape) / m] } });
x.push(k);
let I = new C9(b, n), $ = [e.shape, [n.padInfo.top, n.padInfo.left], [n.strideHeight, n.strideWidth], [n.dilationHeight, n.dilationWidth], [n.inChannels], [n.filterWidth * n.inChannels], [n.outWidth]], R = s.runWebGLProgram(I, [e], "float32", $), E = pe({ inputs: { x: R }, backend: s, attrs: { shape: b } });
x.push(R), x.push(E);
let P = r != null, A = a != null, D = i === "leakyrelu", T = i ? sh(i, true) : null, L = new u2(f ? E.shape : k.shape, f ? k.shape : E.shape, f ? [n.batchSize, g, n.outChannels] : [n.batchSize, n.outChannels, g], y, v, P, T, A, D), W = f ? [E, k] : [k, E];
if (r && W.push(r), A && W.push(a), D) {
let X = s.makeTensorInfo([], "float32", w.createScalarValue(o, "float32"));
W.push(X), x.push(X);
}
let j = s.runWebGLProgram(L, W, "float32"), Y = pe({ inputs: { x: j }, backend: s, attrs: { shape: n.outShape } });
x.push(j);
for (let X of x)
s.disposeIntermediateTensorInfo(X);
return Y;
}
function N9(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, filter: a } = t, { strides: o, pad: i, dataFormat: u, dilations: l, dimRoundingMode: c } = s, p = C.convertConv2DDataFormat(u), d = C.computeConv2DInfo(r.shape, a.shape, o, l, i, c, false, p), h;
if (d.filterHeight === 1 && d.filterWidth === 1 && d.dilationHeight === 1 && d.dilationWidth === 1 && d.strideHeight === 1 && d.strideWidth === 1 && (d.padInfo.type === "SAME" || d.padInfo.type === "VALID"))
h = g2({ x: r, filter: a, convInfo: d, backend: n });
else if (K().getBool("WEBGL_CONV_IM2COL"))
h = b2({ x: r, filter: a, convInfo: d, backend: n });
else {
let m = new m2(d);
h = n.runWebGLProgram(m, [r, a], "float32");
}
let f = pe({ inputs: { x: h }, backend: n, attrs: { shape: d.outShape } });
return n.disposeIntermediateTensorInfo(h), f;
}
var T9 = { kernelName: _a, backendName: "webgl", kernelFunc: N9 };
var $9 = class {
constructor(e) {
this.variableNames = ["x", "dy"], this.outputShape = e.filterShape;
let t = e.strideHeight, n = e.strideWidth, s = e.padInfo.top, r = e.padInfo.left, a = e.dataFormat === "channelsLast";
this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int d2 = coords.w;
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${s};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${r};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
if (${a}) {
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
} else {
float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`;
}
};
var _9 = class {
constructor(e) {
this.variableNames = ["dy", "W"], this.outputShape = e.inShape;
let t = e.filterHeight, n = e.filterWidth, s = e.strideHeight, r = e.strideWidth, a = e.dataFormat === "channelsLast", o = t - 1 - e.padInfo.top, i = n - 1 - e.padInfo.left, u = a ? 1 : 2, l = a ? 2 : 3, c = a ? 3 : 1;
this.userCode = `
const ivec2 pads = ivec2(${o}, ${i});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[${c}];
ivec2 dyCorner = ivec2(coords[${u}], coords[${l}]) - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${r}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${n} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
if (${a}) {
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
} else {
float xValue = getDy(batch, d2, idyR, idyC);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`;
}
};
var A9 = class {
constructor(e) {
this.variableNames = ["x", "dy"], this.outputShape = e.filterShape;
let t = e.strideDepth, n = e.strideHeight, s = e.strideWidth, r = e.padInfo.front, a = e.padInfo.top, o = e.padInfo.left;
this.userCode = `
void main() {
ivec5 coords = getOutputCoords();
int wF = coords.x;
int wR = coords.y;
int wC = coords.z;
int d1 = coords.w;
int d2 = coords.u;
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yF = 0; yF < ${e.outDepth}; yF++) {
int xF = wF + yF * ${t} - ${r};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${n} - ${a};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${s} - ${o};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`;
}
};
var E9 = class {
constructor(e) {
this.variableNames = ["dy", "W"], this.outputShape = e.inShape;
let t = e.filterDepth, n = e.filterHeight, s = e.filterWidth, r = e.strideDepth, a = e.strideHeight, o = e.strideWidth, i = t - 1 - e.padInfo.front, u = n - 1 - e.padInfo.top, l = s - 1 - e.padInfo.left;
this.userCode = `
const ivec3 pads = ivec3(${i}, ${u}, ${l});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
float dotProd = 0.0;
for (int wF = 0; wF < ${t}; wF++) {
float dyF = float(dyFCorner + wF) / ${r}.0;
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
continue;
}
int idyF = int(dyF);
int wFPerm = ${t} - 1 - wF;
for (int wR = 0; wR < ${n}; wR++) {
float dyR = float(dyRCorner + wR) / ${a}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${n} - 1 - wR;
for (int wC = 0; wC < ${s}; wC++) {
float dyC = float(dyCCorner + wC) / ${o}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${s} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`;
}
};
function R9(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, dy: a } = t, { strides: o, pad: i, dataFormat: u, dimRoundingMode: l, filterShape: c } = s, p = C.convertConv2DDataFormat(u), d = C.computeConv2DInfo(r.shape, c, o, 1, i, l, false, p), h = new $9(d);
return n.runWebGLProgram(h, [r, a], "float32");
}
var D9 = { kernelName: wg, backendName: "webgl", kernelFunc: R9 };
function F9(e) {
let { inputs: t, backend: n, attrs: s } = e, { dy: r, filter: a } = t, { inputShape: o, strides: i, pad: u, dataFormat: l, dimRoundingMode: c } = s, p = C.convertConv2DDataFormat(l), d = C.computeConv2DInfo(o, a.shape, i, 1, u, c, false, p), h = new _9(d);
return n.runWebGLProgram(h, [r, a], "float32");
}
var O9 = { kernelName: Aa, backendName: "webgl", kernelFunc: F9 };
function P9(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, filter: a } = t, { strides: o, pad: i, dilations: u } = s, l = C.computeConv3DInfo(r.shape, a.shape, o, u, i), c = new I9(l);
return n.runWebGLProgram(c, [r, a], "float32");
}
var z9 = { kernelName: rp, backendName: "webgl", kernelFunc: P9 };
function L9(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, dy: a } = t, { strides: o, pad: i, filterShape: u } = s, l = C.computeConv3DInfo(r.shape, u, o, 1, i), c = new A9(l);
return n.runWebGLProgram(c, [r, a], "float32");
}
var M9 = { kernelName: kg, backendName: "webgl", kernelFunc: L9 };
function B9(e) {
let { inputs: t, backend: n, attrs: s } = e, { dy: r, filter: a } = t, { pad: o, strides: i, inputShape: u } = s, l = C.computeConv3DInfo(u, a.shape, i, 1, o), c = new E9(l);
return n.runWebGLProgram(c, [r, a], "float32");
}
var V9 = { kernelName: Sg, backendName: "webgl", kernelFunc: B9 };
var W9 = du + `
return cos(x);
`;
var U9 = Ke({ opSnippet: W9 });
var G9 = { kernelName: Ea, backendName: "webgl", kernelFunc: U9 };
var H9 = `
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`;
var q9 = Ke({ opSnippet: H9 });
var j9 = { kernelName: Ra, backendName: "webgl", kernelFunc: q9 };
var K9 = class {
constructor(e, t, n, s, r) {
this.variableNames = ["Image", "Boxes", "BoxInd"], this.outputShape = [];
let [a, o, i, u] = e, [l] = t, [c, p] = n;
this.outputShape = [l, c, p, u];
let d = s === "bilinear" ? 1 : 0, [h, f] = [`${o - 1}.0`, `${i - 1}.0`], [m, g, b] = c > 1 ? [`${(o - 1) / (c - 1)}`, "(y2-y1) * height_ratio", `y1*${h} + float(y)*(height_scale)`] : ["0.0", "0.0", `0.5 * (y1+y2) * ${h}`], [y, v, x] = p > 1 ? [`${(i - 1) / (p - 1)}`, "(x2-x1) * width_ratio", `x1*${f} + float(x)*(width_scale)`] : ["0.0", "0.0", `0.5 * (x1+x2) * ${f}`];
this.userCode = `
const float height_ratio = float(${m});
const float width_ratio = float(${y});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
if(bInd < 0 || bInd >= ${a}) {
return;
}
float height_scale = ${g};
float width_scale = ${v};
float in_y = ${b};
if( in_y < 0.0 || in_y > ${h} ) {
setOutput(float(${r}));
return;
}
float in_x = ${x};
if( in_x < 0.0 || in_x > ${f} ) {
setOutput(float(${r}));
return;
}
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(${d} == 1) {
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
float top = topLeft + (topRight - topLeft) * fracCR.x;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
float newValue = top + (bottom - top) * fracCR.y;
setOutput(newValue);
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2(floor(
sourceFracIndexCR + vec2(0.5,0.5)));
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
setOutput(newValue);
}
}
`;
}
};
var X9 = (e) => {
let { inputs: t, backend: n, attrs: s } = e, { image: r, boxes: a, boxInd: o } = t, { cropSize: i, method: u, extrapolationValue: l } = s, c = new K9(r.shape, a.shape, i, u, l);
return n.runWebGLProgram(c, [r, a, o], "float32");
};
var Y9 = { kernelName: mi, backendName: "webgl", kernelFunc: X9 };
var Tw = class {
constructor(e, t, n, s) {
this.op = e, this.outputShape = t, this.variableNames = ["x"], this.customUniforms = [{ name: "index", type: "float" }];
let r = this.outputShape.length, a = this.op === "*" ? "1.0" : "0.0", o = n ? a : `getX(${$w(r, "coords", this.op)})`, i = this.outputShape[this.outputShape.length - 1], u = "", l = "";
n ? (u = s ? `end != ${i - 1}` : "end != 0", l = s ? "end + 1" : "end - 1") : (u = s ? `end + pow2 < ${i}` : "end >= pow2", l = s ? "end + pow2" : "end - pow2"), this.userCode = `
void main() {
${rt(r)} coords = getOutputCoords();
int end = ${_w(r, "coords", this.op)};
float val = ${o};
int pow2 = int(pow(2.0, index));
if (${u}) {
int idx = ${l};
${_w(r, "coords", this.op)} = idx;
val ${this.op}= getX(${$w(r, "coords", this.op)});
}
setOutput(val);
}
`;
}
};
function $w(e, t, n) {
if (e === 1)
return `${t}`;
if (e === 2)
return `${t}.x, ${t}.y`;
if (e === 3)
return `${t}.x, ${t}.y, ${t}.z`;
if (e === 4)
return `${t}.x, ${t}.y, ${t}.z, ${t}.w`;
throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`);
}
function _w(e, t, n) {
if (e === 1)
return `${t}`;
if (e === 2)
return `${t}.y`;
if (e === 3)
return `${t}.z`;
if (e === 4)
return `${t}.w`;
throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`);
}
function y2(e, t, n, s, r, a) {
let o = t.shape.length, i = C.getAxesPermutation([s], o), u = t;
i != null && (u = pn({ inputs: { x: t }, backend: n, attrs: { perm: i } }));
let l = C.getInnerMostAxes(1, o)[0];
if (l !== o - 1)
throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length - 1} but got axis=${s}`);
let c = u.shape[l], p = Rn({ inputs: { x: u }, backend: n });
for (let d = 0; d <= Math.ceil(Math.log2(c)) - 1; d++) {
let h = new Tw(e, u.shape, false, a), f = [[d]], m = p;
p = n.runWebGLProgram(h, [p], p.dtype, f), n.disposeIntermediateTensorInfo(m);
}
if (r) {
let d = new Tw(e, u.shape, r, a), h = p;
p = n.runWebGLProgram(d, [p], p.dtype), n.disposeIntermediateTensorInfo(h);
}
if (i != null) {
let d = C.getUndoAxesPermutation(i), h = pn({ inputs: { x: p }, backend: n, attrs: { perm: d } });
return n.disposeIntermediateTensorInfo(p), n.disposeIntermediateTensorInfo(u), h;
}
return p;
}
function Q9(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, exclusive: o, reverse: i } = s;
return y2("*", r, n, a, o, i);
}
var Z9 = { kernelName: fi, backendName: "webgl", kernelFunc: Q9 };
function J9(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, exclusive: o, reverse: i } = s;
return y2("+", r, n, a, o, i);
}
var eQ = { kernelName: Da, backendName: "webgl", kernelFunc: J9 };
function tQ(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, weights: a } = t, { size: o, binaryOutput: i } = s;
if (r.shape.length === 1) {
let u = n.readSync(r.dataId), l = n.readSync(a.dataId), c = Y1(u, l, a.dtype, a.shape, o);
return n.makeTensorInfo([o], a.dtype, c);
} else if (r.shape.length === 2) {
let u = n.bufferSync(r), l = n.bufferSync(a), c = fX(u, l, o, i);
return n.makeTensorInfo(c.shape, a.dtype, c.values);
}
throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`);
}
var nQ = { kernelName: Ig, backendName: "webgl", kernelFunc: tQ };
var sQ = class {
constructor(e, t, n) {
this.variableNames = ["x"], this.outputShape = [], this.outputShape = e, this.blockSize = t, this.dataFormat = n, this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
int in_h = h / ${t};
int offset_h = imod(h, ${t});
int in_w = w / ${t};
int offset_w = imod(w, ${t});
int offset_d = (offset_h * ${t} + offset_w) *
${this.getOutputDepthSize()};
int in_d = d + offset_d;
float result = ${this.getInputSamplingString()};
setOutput(result);
}
`;
}
getHeightCoordString() {
return this.dataFormat === "NHWC" ? "coords[1]" : "coords[2]";
}
getWidthCoordString() {
return this.dataFormat === "NHWC" ? "coords[2]" : "coords[3]";
}
getDepthCoordString() {
return this.dataFormat === "NHWC" ? "coords[3]" : "coords[1]";
}
getOutputDepthSize() {
return this.dataFormat === "NHWC" ? this.outputShape[3] : this.outputShape[1];
}
getInputSamplingString() {
return this.dataFormat === "NHWC" ? "getX(b, in_h, in_w, in_d)" : "getX(b, in_d, in_h, in_w)";
}
};
function rQ(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { blockSize: a, dataFormat: o } = s, i = r.shape[0], u = o === "NHWC" ? r.shape[1] : r.shape[2], l = o === "NHWC" ? r.shape[2] : r.shape[3], c = o === "NHWC" ? r.shape[3] : r.shape[1], p = u * a, d = l * a, h = c / (a * a), f = o === "NHWC" ? [i, p, d, h] : [i, h, p, d], m = new sQ(f, a, o);
return n.runWebGLProgram(m, [r], r.dtype);
}
var aQ = { kernelName: gi, backendName: "webgl", kernelFunc: rQ };
var v2 = class {
constructor(e, t = false, n = null, s = false, r = false) {
this.variableNames = ["x", "W"], this.customUniforms = [{ name: "pads", type: "ivec2" }, { name: "strides", type: "ivec2" }, { name: "dilations", type: "ivec2" }, { name: "inDims", type: "ivec2" }], this.outputShape = e.outShape, this.enableShapeUniforms = Sn(this.outputShape.length);
let a = e.filterHeight, o = e.filterWidth, i = e.outChannels / e.inChannels, u = "", l = "";
n && (s ? u = `float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${n}
}` : r ? u = `float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${n}
}` : u = `
float activation(float x) {
${n}
}
`, l = "result = activation(result);");
let c = t ? "result += getBiasAtOutCoords();" : "";
t && this.variableNames.push("bias"), s && this.variableNames.push("preluActivationWeights"), r && this.variableNames.push("leakyreluAlpha"), this.userCode = `
${u}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${i};
int q = d2 - d1 * ${i};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for (int wR = 0; wR < ${a}; wR++) {
int xR = xRCorner + wR * dilations[0];
if (xR < 0 || xR >= inDims[0]) {
continue;
}
for (int wC = 0; wC < ${o}; wC++) {
int xC = xCCorner + wC * dilations[1];
if (xC < 0 || xC >= inDims[1]) {
continue;
}
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
float result = dotProd;
${c}
${l}
setOutput(result);
}
`;
}
};
var x2 = class {
constructor(e, t = false, n = null, s = false, r = false) {
this.variableNames = ["x", "W"], this.packedInputs = true, this.packedOutput = true, this.customUniforms = [{ name: "pads", type: "ivec2" }, { name: "strides", type: "ivec2" }, { name: "dilations", type: "ivec2" }, { name: "inDims", type: "ivec2" }], this.outputShape = e.outShape, this.enableShapeUniforms = Sn(this.outputShape.length);
let a = e.outChannels / e.inChannels, o = e.padInfo.left, i = e.strideWidth, u = e.dilationWidth, l = e.filterHeight, c = e.filterWidth, p = c, d = `
int xR; int xC; int xCOffset;
vec4 wTexel; vec4 previous; vec4 final;`;
for (let g = 0; g < c; g++)
d += `
vec4 xTexelC${g * 2};
int xTexelC${g * 2}Ready;
vec4 xTexelC${g * 2 + 1};
int xTexelC${g * 2 + 1}Ready;
vec4 xC${g};`;
d += `
for (int r = 0; r < ${l}; r++) {
`;
for (let g = 0; g < c; g++)
d += `
xTexelC${g * 2} = vec4(0.0);
xTexelC${g * 2}Ready = 0;
xTexelC${g * 2 + 1} = vec4(0.0);
xTexelC${g * 2 + 1}Ready = 0;
xC${g} = vec4(0.0);`;
d += `
xR = xRCorner + r * dilations[0];
if (xR >=0 && xR < inDims[0]) {
`;
for (let g = 0; g < (p + 1) / 2; g++) {
let b = g * 2;
if (d += `
xC = xCCorner + ${b * u};
`, i === 1) {
if (b < c && (o % 2 === 1 ? (d += `
xCOffset = xC + 1;
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${b}.zw = vec2(0.0);
}
xTexelC${b}Ready = 1;
}
`, u === 1 && b > 0 ? d += `
xC${b} = vec4(xTexelC${b - 2}.zw, xTexelC${b}.xy);
` : d += `
xCOffset = xC + 1 - 2;
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
previous.zw = vec2(0.0);
}
xC${b} = vec4(previous.zw, xTexelC${b}.xy);
} else {
xC${b} = vec4(0.0, 0.0, xTexelC${b}.xy);
}
`) : d += `
if (xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${b}.zw = vec2(0.0);
}
xTexelC${b}Ready = 1;
}
xC${b} = xTexelC${b};
`, b + 1 < c)) {
let y = o % 2 === 0 ? w.nearestLargerEven(u) : u;
u % 2 === 0 && o % 2 === 1 || u % 2 !== 0 && o % 2 !== 1 ? (d += `
xCOffset = xC + imod(pads[1], 2) + ${y};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b + 1}Ready == 0) {
xTexelC${b + 1} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${b + 1}.zw = vec2(0.0);
}
xTexelC${b + 1}Ready = 1;
}
`, u > 1 && (d += `
xCOffset -= 2;
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xCOffset, d1);
xTexelC${b}Ready = 1;
}
`), d += `
xC${b + 1} = vec4(xTexelC${b}.zw, xTexelC${b + 1}.xy);
`) : y === 1 ? d += `
xC${b + 1} = xTexelC${b};
` : d += `
xCOffset = xC + ${y};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b + 1}Ready == 0) {
xTexelC${b + 1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${b + 1}.zw = vec2(0.0);
}
xTexelC${b + 1}Ready = 1;
}
xC${b + 1} = xTexelC${b + 1};
`;
}
} else
b < c && (o % 2 === 1 ? (d += `
xCOffset = xC + 1 - strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${b}.zw = vec2(0.0);
}
xTexelC${b}Ready = 1;
}
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${b + 1}Ready == 0) {
xTexelC${b + 1} = getX(batch, xR, xC + 1, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xC + 2 >= inDims[1]) {
xTexelC${b + 1}.zw = vec2(0.0);
}
xTexelC${b + 1}Ready = 1;
}
xC${b} = vec4(xTexelC${b}.zw, xTexelC${b + 1}.zw);
`, b + 1 < c && (d += `
final = vec4(0.0);
xCOffset = xC + 1 + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1]) {
final = getX(batch, xR, xCOffset, d1);
}
xC${b + 1} = vec4(xTexelC${b + 1}.xy, final.xy);
`)) : (d += `
if(xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${b}.zw = vec2(0.0);
}
xTexelC${b}Ready = 1;
}
xCOffset = xC + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b + 1}Ready == 0) {
xTexelC${b + 1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${b + 1}.zw = vec2(0.);
}
xTexelC${b + 1}Ready = 1;
}
xC${b} = vec4(
xTexelC${b}.xy, xTexelC${b + 1}.xy);
`, b + 1 < c && (d += `
xC${b + 1} = vec4(xTexelC${b}.zw, xTexelC${b + 1}.zw);
`)));
b < c && (d += `
wTexel = getW(r, ${b}, d1, q);
dotProd += xC${b} * vec4(wTexel.xz, wTexel.xz);
`, b + 1 < c && (d += `
wTexel = getW(r, ${b + 1}, d1, q);
dotProd += xC${b + 1} * vec4(wTexel.xz, wTexel.xz);
`));
}
d += `
}
`, d += `
}
`;
let h = "", f = "";
n && (s ? h = `vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${n}
}` : r ? h = `vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${n}
}` : h = `vec4 activation(vec4 x) {
${n}
}`, f = "result = activation(result);");
let m = t ? "result += getBiasAtOutCoords();" : "";
t && this.variableNames.push("bias"), s && this.variableNames.push("preluActivationWeights"), r && this.variableNames.push("leakyreluAlpha"), this.userCode = `
${h}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${a};
int q = d2 - d1 * ${a};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
vec4 dotProd = vec4(0.000000000000001);
${d}
vec4 result = dotProd - vec4(0.000000000000001);
${m}
${f}
setOutput(result);
}
`;
}
};
function oQ(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, filter: a } = t, { strides: o, pad: i, dilations: u, dimRoundingMode: l } = s, c = u;
c == null && (c = [1, 1]), w.assert(C.eitherStridesOrDilationsAreOne(o, c), () => `Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);
let p = C.computeConv2DInfo(r.shape, a.shape, o, c, i, l, true), d;
K().getBool("WEBGL_PACK_DEPTHWISECONV") && p.strideWidth <= 2 && p.outChannels / p.inChannels === 1 ? d = new x2(p) : d = new v2(p);
let h = [[p.padInfo.top, p.padInfo.left], [p.strideHeight, p.strideWidth], [p.dilationHeight, p.dilationWidth], [p.inHeight, p.inWidth]];
return n.runWebGLProgram(d, [r, a], "float32", h);
}
var iQ = { kernelName: Fa, backendName: "webgl", kernelFunc: oQ };
var uQ = class {
constructor(e) {
this.variableNames = ["x", "dy"], this.outputShape = e.filterShape;
let t = e.strideHeight, n = e.strideWidth, s = e.padInfo.top, r = e.padInfo.left, a = e.outChannels / e.inChannels;
this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
int d2 = d1 * ${a} + dm;
float dotProd = 0.0;
// TO DO: Vec4 over the batch size
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${s};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${r};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
setOutput(dotProd);
}
`;
}
};
var lQ = class {
constructor(e) {
this.variableNames = ["dy", "W"], this.outputShape = e.inShape;
let t = e.filterHeight, n = e.filterWidth, s = e.strideHeight, r = e.strideWidth, a = t - 1 - e.padInfo.top, o = n - 1 - e.padInfo.left, i = e.outChannels / e.inChannels;
this.userCode = `
const ivec2 pads = ivec2(${a}, ${o});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[3];
ivec2 dyCorner = coords.yz - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${r}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${n} - 1 - wC;
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${i}; dm++) {
int d2 = d1 * ${i} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
`;
}
};
function cQ(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, dy: a } = t, { strides: o, dilations: i, pad: u, dimRoundingMode: l, filterShape: c } = s, p = C.computeConv2DInfo(r.shape, c, o, i, u, l, true), d = new uQ(p);
return n.runWebGLProgram(d, [r, a], "float32");
}
var dQ = { kernelName: Cg, backendName: "webgl", kernelFunc: cQ };
function pQ(e) {
let { inputs: t, backend: n, attrs: s } = e, { dy: r, filter: a } = t, { strides: o, dilations: i, pad: u, dimRoundingMode: l, inputShape: c } = s, p = C.computeConv2DInfo(c, a.shape, o, i, u, l, true), d = new lQ(p);
return n.runWebGLProgram(d, [r, a], "float32");
}
var hQ = { kernelName: Ng, backendName: "webgl", kernelFunc: pQ };
var fQ = class {
constructor(e) {
this.variableNames = ["X"], this.outputShape = [e, e], this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
`;
}
};
function mQ(e) {
let { inputs: t, backend: n } = e, { x: s } = t, r = [...s.shape, ...s.shape], a = w.sizeFromShape(s.shape), o = pe({ inputs: { x: s }, backend: n, attrs: { shape: [a] } }), i = new fQ(a), u = n.runWebGLProgram(i, [o], o.dtype), l = pe({ inputs: { x: u }, backend: n, attrs: { shape: r } });
return n.disposeIntermediateTensorInfo(o), n.disposeIntermediateTensorInfo(u), l;
}
var gQ = { kernelName: Tg, backendName: "webgl", kernelFunc: mQ };
var bQ = class {
constructor(e) {
this.variableNames = ["x", "W"], this.outputShape = e.outShape;
let { inHeight: t, inWidth: n, padInfo: s, strideHeight: r, strideWidth: a, filterHeight: o, filterWidth: i, dilationHeight: u, dilationWidth: l } = e, { top: c, left: p } = s;
this.userCode = `
const ivec2 strides = ivec2(${r}, ${a});
const ivec2 pads = ivec2(${c}, ${p});
const float neg_infinity = -3.4e38;
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.w;
ivec2 outTopLeftCorner =
coords.yz * strides - pads;
int hBeg = outTopLeftCorner.x;
int wBeg = outTopLeftCorner.y;
float curVal = neg_infinity;
for (int h = 0; h < ${o}; h++) {
int hIn = hBeg + h * ${u};
if (hIn >= 0 && hIn < ${t}) {
for (int w = 0; w < ${i}; w++) {
int wIn = wBeg + w * ${l};
if (wIn >= 0 && wIn < ${n}) {
float xVal = getX(batch, hIn, wIn, d1);
float wVal = getW(h, w, d1);
float val = xVal + wVal;
if (val > curVal) {
curVal = val;
}
}
}
}
}
float result = curVal;
setOutput(result);
}
`;
}
};
function yQ(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, filter: a } = t, { strides: o, pad: i, dilations: u } = s, l = C.computeDilation2DInfo(r.shape, a.shape, o, i, "NHWC", u), c, p = new bQ(l);
c = n.runWebGLProgram(p, [r, a], "float32");
let d = pe({ inputs: { x: c }, backend: n, attrs: { shape: l.outShape } });
return n.disposeIntermediateTensorInfo(c), d;
}
var vQ = { kernelName: ap, backendName: "webgl", kernelFunc: yQ };
function xQ(e) {
let { inputs: t, backend: n, attrs: s } = e, { equation: r } = s, a = t, { allDims: o, summedDims: i, idDims: u } = C.decodeEinsumEquation(r, a.length);
C.checkEinsumDimSizes(o.length, u, a);
let { path: l, steps: c } = C.getEinsumComputePath(i, u), p = c.length, d = null, h = o.length, f = [];
for (let m = 0; m < p; ++m) {
for (let g of c[m]) {
let { permutationIndices: b, expandDims: y } = C.getEinsumPermutation(h, u[g]), v;
C.isIdentityPermutation(b) ? v = a[g] : (v = pn({ inputs: { x: a[g] }, backend: n, attrs: { perm: b } }), f.push(v));
let x = v.shape.slice();
for (let k = 0; k < y.length; ++k)
x.splice(y[k], 0, 1);
w.arraysEqual(v.shape, x) || (v = pe({ inputs: { x: v }, backend: n, attrs: { shape: x } }), f.push(v)), d === null ? d = v : (d = Dv({ inputs: { a: v, b: d }, backend: n }), f.push(d));
}
m < p - 1 && (l[m] >= 0 && (d = ah({ inputs: { x: d }, backend: n, attrs: { axis: l[m] - (o.length - h), keepDims: false } }), f.push(d)), h--);
}
for (let m of f)
m !== d && n.disposeIntermediateTensorInfo(m);
return d;
}
var wQ = { kernelName: op, backendName: "webgl", kernelFunc: xQ };
var kQ = "return (x >= 0.0) ? x : (exp(x) - 1.0);";
var SQ = `
vec4 result;
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
return result;
`;
var IQ = Ke({ opSnippet: kQ, packedOpSnippet: SQ });
var CQ = { kernelName: Pa, backendName: "webgl", kernelFunc: IQ };
var NQ = "return (b >= 1.0) ? a : a * (b + 1.0);";
var TQ = `
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`;
var $Q = (e) => {
let { inputs: t, backend: n } = e, { dy: s, y: r } = t, a = K().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new tc(TQ, s.shape, r.shape) : new li(NQ, s.shape, r.shape);
return n.runWebGLProgram(a, [s, r], s.dtype);
};
var _Q = { kernelName: $g, backendName: "webgl", kernelFunc: $Q };
var AQ = `
return vec4(equal(a, b));
`;
var EQ = "return float(a == b);";
var RQ = jt({ opSnippet: EQ, packedOpSnippet: AQ, dtype: "bool", cpuKernelImpl: bX });
var DQ = { kernelName: bi, backendName: "webgl", kernelFunc: RQ };
var FQ = `
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ${C.ERF_P};
float a1 = ${C.ERF_A1};
float a2 = ${C.ERF_A2};
float a3 = ${C.ERF_A3};
float a4 = ${C.ERF_A4};
float a5 = ${C.ERF_A5};
float sign = sign(x);
x = abs(x);
float t = 1.0 / (1.0 + p * x);
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
`;
var OQ = Ke({ opSnippet: FQ });
var PQ = { kernelName: yl, backendName: "webgl", kernelFunc: OQ };
var zQ = du + `
return exp(x);
`;
var LQ = `
vec4 result = exp(x);
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`;
var w2 = Ke({ opSnippet: zQ, packedOpSnippet: LQ, cpuKernelImpl: yX, dtype: "float32" });
var MQ = { kernelName: za, backendName: "webgl", kernelFunc: w2 };
function rg(e) {
let { inputs: t, attrs: n, backend: s } = e, { dim: r } = n, { input: a } = t, o = a.shape.length, i = a.shape.slice(), u = r;
return r < 0 && (w.assert(-(o + 1) <= r, () => `Axis must be in the interval [${-(o + 1)}, ${o}]`), u = o + r + 1), i.splice(u, 0, 1), pe({ inputs: { x: a }, backend: s, attrs: { shape: i } });
}
var BQ = { kernelName: yi, backendName: "webgl", kernelFunc: rg };
var Aw = "return exp(x) - 1.0;";
var VQ = Ke({ opSnippet: Aw, packedOpSnippet: Aw, cpuKernelImpl: vX });
var WQ = { kernelName: vi, backendName: "webgl", kernelFunc: VQ };
var Ew = class {
constructor(e, t, n) {
this.variableNames = ["real", "imag"];
let s = t[1];
this.outputShape = t;
let r = n ? `2.0 * ${Math.PI}` : `-2.0 * ${Math.PI}`, a = n ? `${s}.0` : "1.0", o;
if (e === "real")
o = "return real * expR - imag * expI;";
else if (e === "imag")
o = "return real * expI + imag * expR;";
else
throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);
this.userCode = `
const float exponentMultiplier = ${r};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${o}
}
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${s});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < ${s}; i++) {
// x = (-2|2 * PI / N) * index * i;
float x = exponentMultiplierTimesIndexRatio * float(i);
float expR = cos(x);
float expI = sin(x);
float real = getReal(batch, i);
float imag = getImag(batch, i);
result +=
unaryOpComplex(real, expR, imag, expI) / ${a};
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
`;
}
};
function k2(e, t, n) {
let s = n.texData.get(e.dataId), r = w.sizeFromShape(e.shape), a = e.shape[e.shape.length - 1], o = r / a, i = pe({ inputs: { x: e }, backend: n, attrs: { shape: [o, a] } }), u = i.shape, l = new Ew("real", u, t), c = new Ew("imag", u, t), p = [{ dataId: s.complexTensorInfos.real.dataId, dtype: s.complexTensorInfos.real.dtype, shape: u }, { dataId: s.complexTensorInfos.imag.dataId, dtype: s.complexTensorInfos.imag.dtype, shape: u }], d = n.runWebGLProgram(l, p, "float32"), h = n.runWebGLProgram(c, p, "float32"), f = Fr({ inputs: { real: d, imag: h }, backend: n });
n.disposeIntermediateTensorInfo(d), n.disposeIntermediateTensorInfo(h);
let m = pe({ inputs: { x: f }, backend: n, attrs: { shape: e.shape } });
return n.disposeIntermediateTensorInfo(i), n.disposeIntermediateTensorInfo(f), m;
}
function UQ(e) {
let { inputs: t, backend: n } = e, { input: s } = t;
return k2(s, false, n);
}
var GQ = { kernelName: _g, backendName: "webgl", kernelFunc: UQ };
var HQ = class {
constructor(e, t) {
this.outputShape = [], this.customUniforms = [{ name: "value", type: "float" }], this.variableNames = ["x"], this.outputShape = e, this.userCode = `
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
`;
}
};
function sc(e) {
let { backend: t, attrs: n } = e, { shape: s, value: r } = n, { dtype: a } = n;
if (a = a || w.inferDtype(r), a === "string") {
let o = w.getArrayFromDType(a, w.sizeFromShape(s));
return o.fill(r), t.makeTensorInfo(s, a, o);
} else {
let o = new HQ(s, r), i = [[r]];
return t.runWebGLProgram(o, [], a, i);
}
}
var qQ = { kernelName: vl, backendName: "webgl", kernelFunc: sc };
var jQ = class {
constructor(e) {
this.variableNames = ["Image"], this.outputShape = [];
let t = e[2];
this.outputShape = e, this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int coordX = ${t} - x - 1;
float outputValue;
if(coordX >= 0 && coordX < ${t}) {
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
} else {
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
}
setOutput(outputValue);
}
`;
}
};
var KQ = { kernelName: xi, backendName: "webgl", kernelFunc: ({ inputs: e, backend: t }) => {
let { image: n } = e, s = t, r = new jQ(n.shape);
return s.runWebGLProgram(r, [n], n.dtype);
} };
var Rw = "return floor(x);";
var XQ = Ke({ opSnippet: Rw, packedOpSnippet: Rw, cpuKernelImpl: xX });
var YQ = { kernelName: La, backendName: "webgl", kernelFunc: XQ };
var QQ = `
float s = sign(a) * sign(b);
int ia = round(a);
int ib = round(b);
if (ib != 0) {
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
return float(idiv(ia, ib, s));
} else {
return NAN;
}
`;
var ZQ = `
ivec4 ia = round(a);
ivec4 ib = round(b);
bvec4 cond = notEqual(ib, ivec4(0));
ivec4 result = ivec4(0);
vec4 s = sign(a) * sign(b);
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if (cond[0]) {
result[0] = idiv(ia[0], ib[0], s[0]);
}
if (cond[1]) {
result[1] = idiv(ia[1], ib[1], s[1]);
}
if (cond[2]) {
result[2] = idiv(ia[2], ib[2], s[2]);
}
if (cond[3]) {
result[3] = idiv(ia[3], ib[3], s[3]);
}
return vec4(result);
`;
var JQ = jt({ opSnippet: QQ, packedOpSnippet: ZQ, dtype: "int32" });
var eZ = { kernelName: Ma, backendName: "webgl", kernelFunc: JQ };
var tZ = class {
constructor(e) {
this.variableNames = ["A"];
let t = mn(), [n, s] = e;
this.outputShape = e, this.userCode = `
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}.0, ${n}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
setOutput(floor(value * 255.0 + 0.5));
}
`;
}
};
var nZ = class {
constructor(e) {
this.variableNames = ["A"], this.packedInputs = false, this.packedOutput = true;
let t = mn(), [n, s] = e;
this.outputShape = e, this.userCode = `
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec4 result = vec4(0.);
for(int row=0; row<=1; row++) {
for(int col=0; col<=1; col++) {
texC = coords[1] + row;
depth = coords[2] + col;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${s}.0, ${n}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
result[row * 2 + col] = floor(value * 255.0 + 0.5);
}
}
${t.output} = result;
}
`;
}
};
var sZ = { kernelName: xd, backendName: "webgl", kernelFunc: rZ };
var Wo;
function rZ(e) {
let { inputs: t, backend: n, attrs: s } = e, { pixels: r } = t, { numChannels: a } = s, o = typeof HTMLVideoElement != "undefined" && r instanceof HTMLVideoElement, i = typeof HTMLImageElement != "undefined" && r instanceof HTMLImageElement, [u, l] = o ? [r.videoWidth, r.videoHeight] : [r.width, r.height], c = [l, u], p = [l, u, a];
(i || o) && (Wo == null && (Wo = document.createElement("canvas").getContext("2d")), Wo.canvas.width = u, Wo.canvas.height = l, Wo.drawImage(r, 0, 0, u, l), r = Wo.canvas);
let d = n.makeTensorInfo(c, "int32");
n.texData.get(d.dataId).usage = 2, n.gpgpu.uploadPixelDataToTexture(n.getTexture(d.dataId), r);
let h = K().getBool("WEBGL_PACK") ? new nZ(p) : new tZ(p), f = n.runWebGLProgram(h, [d], "int32");
return n.disposeData(d.dataId), f;
}
function aZ(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, filter: a, bias: o, preluActivationWeights: i } = t, { strides: u, pad: l, dataFormat: c, dilations: p, dimRoundingMode: d, activation: h, leakyreluAlpha: f } = s, m = C.convertConv2DDataFormat(c), g = C.computeConv2DInfo(r.shape, a.shape, u, p, l, d, false, m), b, y = [];
if (g.filterHeight === 1 && g.filterWidth === 1 && g.dilationHeight === 1 && g.dilationWidth === 1 && g.strideHeight === 1 && g.strideWidth === 1 && (g.padInfo.type === "SAME" || g.padInfo.type === "VALID"))
b = g2({ x: r, filter: a, convInfo: g, backend: n, bias: o, activation: h, preluActivationWeights: i, leakyreluAlpha: f });
else if (K().getBool("WEBGL_CONV_IM2COL"))
b = b2({ x: r, filter: a, convInfo: g, backend: n, bias: o, activation: h, preluActivationWeights: i, leakyreluAlpha: f });
else {
let x = o != null, k = i != null, I = h === "leakyrelu", $ = h ? sh(h, false) : null, R = new m2(g, x, $, k, I), E = [r, a], P = (A, D) => {
if (D === "NCHW" && A.shape.length === 1 && A.shape[0] !== 1) {
let T = pe({ inputs: { x: A }, backend: n, attrs: { shape: [A.shape[0], 1, 1] } });
return y.push(T), T;
}
return A;
};
if (x && E.push(P(o, c)), k && E.push(P(i, c)), I) {
let A = n.makeTensorInfo([], "float32", w.createScalarValue(f, "float32"));
E.push(A), y.push(A);
}
b = n.runWebGLProgram(R, E, "float32");
}
let v = pe({ inputs: { x: b }, backend: n, attrs: { shape: g.outShape } });
return y.push(b), y.forEach((x) => n.disposeIntermediateTensorInfo(x)), v;
}
var oZ = { kernelName: ia, backendName: "webgl", kernelFunc: aZ };
function iZ(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, filter: a, bias: o, preluActivationWeights: i } = t, { strides: u, pad: l, dilations: c, dimRoundingMode: p, activation: d, leakyreluAlpha: h } = s, f = [], m = c;
m == null && (m = [1, 1]), w.assert(C.eitherStridesOrDilationsAreOne(u, m), () => `Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${u} and dilations '${m}'`);
let g = C.computeConv2DInfo(r.shape, a.shape, u, m, l, p, true), b = K().getBool("WEBGL_PACK_DEPTHWISECONV") && g.strideWidth <= 2 && g.outChannels / g.inChannels === 1, y = d ? sh(d, b) : null, v = [r, a], x = o != null, k = i != null, I = d === "leakyrelu";
if (x && v.push(o), k && v.push(i), I) {
let P = n.makeTensorInfo([], "float32", w.createScalarValue(h, "float32"));
v.push(P), f.push(P);
}
let $;
b ? $ = new x2(g, x, y, k, I) : $ = new v2(g, x, y, k, I);
let R = [[g.padInfo.top, g.padInfo.left], [g.strideHeight, g.strideWidth], [g.dilationHeight, g.dilationWidth], [g.inHeight, g.inWidth]], E = n.runWebGLProgram($, v, "float32", R);
return f.forEach((P) => n.disposeIntermediateTensorInfo(P)), E;
}
var uZ = { kernelName: ua, backendName: "webgl", kernelFunc: iZ };
var lZ = class {
constructor(e, t, n, s) {
this.sliceDim = e, this.strides = t, this.paramsShape = s, this.variableNames = ["x", "indices"], this.outputShape = n;
let r = rt(t.length), a = rt(n.length), o = this.sliceDim > 1 ? "strides[j]" : "strides", i = rt(s.length), u = s.length > 1 ? "paramsShape[j]" : "paramsShape";
this.userCode = `
${r} strides = ${r}(${this.strides});
${i} paramsShape = ${i}(${this.paramsShape});
void main() {
${a} coords = getOutputCoords();
int flattenIndex = 0;
bool out_of_bounds = false;
for (int j = 0; j < ${this.sliceDim}; j++) {
int index = round(getIndices(coords[0], j));
out_of_bounds = out_of_bounds || index < 0;
out_of_bounds = out_of_bounds || index >= ${u};
flattenIndex += index * ${o};
}
setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));
}
`;
}
};
function cZ(e) {
let { inputs: t, backend: n } = e, { params: s, indices: r } = t, a = r.shape, o = a[a.length - 1], i = w.sizeFromShape(s.shape), [u, l, c, p] = C.prepareAndValidate(s, r), d = pe({ inputs: { x: r }, backend: n, attrs: { shape: [l, o] } }), h = pe({ inputs: { x: s }, backend: n, attrs: { shape: [w.sizeFromShape(s.shape) / c, c] } });
if (n.shouldExecuteOnCPU([s, r]) || s.dtype === "string") {
let b = n.readSync(r.dataId), y = n.bufferSync(s), v = wX(b, y, s.dtype, l, o, c, p, s.shape, i);
return n.makeTensorInfo(u, s.dtype, v.values);
}
let f = new lZ(o, p, [l, c], s.shape), m = n.runWebGLProgram(f, [h, d], h.dtype), g = pe({ inputs: { x: m }, backend: n, attrs: { shape: u } });
return n.disposeIntermediateTensorInfo(d), n.disposeIntermediateTensorInfo(h), n.disposeIntermediateTensorInfo(m), g;
}
var dZ = { kernelName: ki, backendName: "webgl", kernelFunc: cZ };
var pZ = class {
constructor(e, t) {
this.variableNames = ["A", "indices"], this.outputShape = t, this.rank = t.length;
let n = rt(this.rank), s = hZ(e, 2);
this.userCode = `
void main() {
${n} resRC = getOutputCoords();
int index = int(getIndices(resRC.x, resRC.z));
float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;
setOutput(inBounds * getA(${s}));
}
`;
}
};
function hZ(e, t) {
let n = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"], s = [];
for (let r = 0; r < e.length; r++)
r === 2 ? s.push("index") : s.push(`${n[r]}`);
return s.join();
}
function S2(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, indices: a } = t, { axis: o, batchDims: i } = s, u = w.parseAxisParam(o, r.shape)[0];
if (K().get("DEBUG")) {
let y = n.readSync(a.dataId), v = r.shape[u];
for (let x = 0; x < y.length; ++x) {
let k = y[x];
w.assert(k <= v - 1 && k >= 0, () => `GatherV2: the index value ${k} is not in [0, ${v - 1}]`);
}
}
let l = C.segment_util.collectGatherOpShapeInfo(r, a, u, i), c = w.sizeFromShape(a.shape), p = [], d = pe({ inputs: { x: r }, backend: n, attrs: { shape: [l.batchSize, l.outerSize, l.dimSize, l.sliceSize] } }), h = pe({ inputs: { x: a }, backend: n, attrs: { shape: [l.batchSize, c / l.batchSize] } });
p.push(d), p.push(h);
let f = [l.batchSize, l.outerSize, c / l.batchSize, l.sliceSize];
if (n.shouldExecuteOnCPU([r, a]) || r.dtype === "string") {
let y = n.bufferSync(h), v = n.bufferSync(d), x = kX(v, y, f);
return p.forEach((k) => n.disposeIntermediateTensorInfo(k)), n.makeTensorInfo(l.outputShape, x.dtype, x.values);
}
let m = new pZ(d.shape, f), g = n.runWebGLProgram(m, [d, h], d.dtype);
p.push(g);
let b = pe({ inputs: { x: g }, backend: n, attrs: { shape: l.outputShape } });
return p.forEach((y) => n.disposeIntermediateTensorInfo(y)), b;
}
var fZ = { kernelName: wi, backendName: "webgl", kernelFunc: S2 };
var mZ = "return float(a > b);";
var gZ = `
return vec4(greaterThan(a, b));
`;
var bZ = jt({ opSnippet: mZ, packedOpSnippet: gZ, cpuKernelImpl: SX, dtype: "bool" });
var yZ = { kernelName: Si, backendName: "webgl", kernelFunc: bZ };
var vZ = "return float(a >= b);";
var xZ = `
return vec4(greaterThanEqual(a, b));
`;
var wZ = jt({ opSnippet: vZ, packedOpSnippet: xZ, dtype: "bool", cpuKernelImpl: IX });
var kZ = { kernelName: Va, backendName: "webgl", kernelFunc: wZ };
function SZ(e) {
let { inputs: t, backend: n } = e, { input: s } = t;
return k2(s, true, n);
}
var IZ = { kernelName: Ag, backendName: "webgl", kernelFunc: SZ };
var CZ = "return float(!isnan(x) && !isinf(x));";
var NZ = Ke({ opSnippet: CZ, dtype: "bool" });
var TZ = { kernelName: xl, backendName: "webgl", kernelFunc: NZ };
var $Z = "return float(isinf(x));";
var _Z = Ke({ opSnippet: $Z, dtype: "bool" });
var AZ = { kernelName: wl, backendName: "webgl", kernelFunc: _Z };
var EZ = "return float(isnan(x));";
var RZ = Ke({ opSnippet: EZ, dtype: "bool" });
var DZ = { kernelName: kl, backendName: "webgl", kernelFunc: RZ };
var FZ = "return float(a < b);";
var OZ = `
return vec4(lessThan(a, b));
`;
var PZ = jt({ opSnippet: FZ, packedOpSnippet: OZ, cpuKernelImpl: CX, dtype: "bool" });
var zZ = { kernelName: Ii, backendName: "webgl", kernelFunc: PZ };
var LZ = "return float(a <= b);";
var MZ = `
return vec4(lessThanEqual(a, b));
`;
var BZ = jt({ opSnippet: LZ, packedOpSnippet: MZ, cpuKernelImpl: NX, dtype: "bool" });
var VZ = { kernelName: Ci, backendName: "webgl", kernelFunc: BZ };
function WZ(e) {
let { backend: t, attrs: n } = e, { start: s, stop: r, num: a } = n, o = TX(s, r, a);
return t.makeTensorInfo([o.length], "float32", o);
}
var UZ = { kernelName: Eg, backendName: "webgl", kernelFunc: WZ };
var GZ = du + `
return x < 0.0 ? 0./0. : log(x);
`;
var HZ = `
vec4 result = log(x);
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);
result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);
result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);
result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);
return result;
`;
var qZ = Ke({ opSnippet: GZ, packedOpSnippet: HZ, cpuKernelImpl: $X });
var jZ = { kernelName: Ga, backendName: "webgl", kernelFunc: qZ };
var KZ = du + `
return log(1.0 + x);
`;
var XZ = Ke({ opSnippet: KZ });
var YZ = { kernelName: Sl, backendName: "webgl", kernelFunc: XZ };
var QZ = "return float(a >= 1.0 && b >= 1.0);";
var ZZ = `
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`;
var JZ = jt({ opSnippet: QZ, packedOpSnippet: ZZ, dtype: "bool" });
var e7 = { kernelName: Ni, backendName: "webgl", kernelFunc: JZ };
var t7 = "return float(!(x >= 1.0));";
var n7 = Ke({ opSnippet: t7 });
var s7 = { kernelName: Ti, backendName: "webgl", kernelFunc: n7 };
var r7 = "return float(a >= 1.0 || b >= 1.0);";
var a7 = `
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`;
var o7 = jt({ opSnippet: r7, packedOpSnippet: a7, dtype: "bool" });
var i7 = { kernelName: Il, backendName: "webgl", kernelFunc: o7 };
var u7 = class {
constructor(e, t, n, s, r) {
this.variableNames = ["x"], this.outputShape = [];
let a = t, o = e[3] - 1;
this.outputShape = e;
let i, u = `float(${n}) + float(${s}) * sum`;
r === 0.5 ? i = `inversesqrt(${u})` : r === 1 ? i = `1.0/(${u})` : i = `exp(log(${u}) * float(-${r}));`, this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
int d = coords[3];
float x = getX(b, r, c, d);
float sum = 0.0;
for (int j = -${a}; j <= ${a}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${o}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
}
float val = x * ${i};
setOutput(val);
}
`;
}
};
var l7 = class {
constructor(e, t, n, s, r) {
this.variableNames = ["x"], this.outputShape = [], this.packedInputs = true, this.packedOutput = true;
let a = t, o = e[3] - 1;
this.outputShape = e;
let i, u = `float(${n}) + float(${s}) * sum`;
r === 0.5 ? i = `inversesqrt(${u})` : r === 1 ? i = `1.0/(${u})` : i = `exp(log(${u}) * float(-${r}));`, this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords.x;
int r = coords.y;
int c = coords.z;
int d = coords.w;
bool hasNextCol = d < ${this.outputShape[3]};
bool hasNextRow = c < ${this.outputShape[2]};
vec4 sum = vec4(0.);
vec4 xFragAtOutputCoords = getX(b, r, c, d);
vec4 xAtOutputCoords = vec4(
getChannel(xFragAtOutputCoords, vec2(c, d)),
hasNextCol ?
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
hasNextRow ?
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
(hasNextRow && hasNextCol) ?
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
);
int firstChannel = d - ${a};
vec2 cache = vec2(0.);
if(firstChannel >= 0){
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
if(hasNextRow){
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
}
}
ivec2 depth = ivec2(d, d + 1);
for (int j = - ${a}; j <= ${a}; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${o}));
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
if(depthInRange || depthPlusOneInRange){
vec4 z = vec4(0.);
vec4 xFragAtCurrentDepth;
z.xz = cache.xy;
if(depthPlusOneInRange && hasNextCol){
xFragAtCurrentDepth = idx.y != d ?
getX(b, r, c, idx.y) : xFragAtOutputCoords;
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
if(hasNextRow){
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
}
}
cache.xy = z.yw;
sum += z * z;
}
}
vec4 result = xAtOutputCoords * ${i};
setOutput(result);
}
`;
}
};
var c7 = (e) => {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { depthRadius: a, bias: o, alpha: i, beta: u } = s, l = K().getBool("WEBGL_PACK_NORMALIZATION") ? new l7(r.shape, a, o, i, u) : new u7(r.shape, a, o, i, u);
return n.runWebGLProgram(l, [r], r.dtype);
};
var d7 = { kernelName: up, backendName: "webgl", kernelFunc: c7 };
var p7 = class {
constructor(e, t, n, s, r) {
this.variableNames = ["inputImage", "outputImage", "dy"], this.outputShape = [], this.outputShape = e, this.depth = e[3], this.depthRadius = t, this.bias = n, this.alpha = s, this.beta = r, this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
float result = 0.0;
for (int d = 0; d < ${this.depth}; ++d) {
int depthBegin = int(max(0.0, float(d - ${t})));
int depthEnd = int(min(float(${this.depth}),
float(d + ${t} + 1)));
const int MIN_DEPTH_BEGIN = 0;
const int MAX_DEPTH_END = ${this.depth};
float norm = 0.0;
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd) {
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
}
else {
break;
}
}
norm = float(${s}) * norm + float(${n});
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd){
float dyi = -2.0 * float(${s})
* float(${r})
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
/ norm;
if (k == d) {
dyi += pow(norm, -1.0 * ${r});
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
}
else {
break;
}
}
}
setOutput(result);
}
`;
}
};
var h7 = (e) => {
let { inputs: t, backend: n, attrs: s } = e, { x: r, y: a, dy: o } = t, { depthRadius: i, bias: u, alpha: l, beta: c } = s, p = new p7(r.shape, i, u, l, c);
return n.runWebGLProgram(p, [r, a, o], r.dtype);
};
var f7 = { kernelName: Rg, backendName: "webgl", kernelFunc: h7 };
function m7(e, t, n, s) {
let r = w.sizeFromShape(t), o = w.sizeFromShape(e.shape) / r, i = pe({ inputs: { x: e }, attrs: { shape: [o, r] }, backend: s }), u = So(i, e.dtype, "max", s), l = pe({ inputs: { x: u }, attrs: { shape: n }, backend: s });
return s.disposeIntermediateTensorInfo(i), s.disposeIntermediateTensorInfo(u), l;
}
function I2(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { reductionIndices: a, keepDims: o } = s, i = r.shape.length, u = w.parseAxisParam(a, r.shape), l = u, c = C.getAxesPermutation(l, i), p = c != null, d = n.shouldExecuteOnCPU([r]), h = r;
if (p) {
if (d) {
let v = n.texData.get(h.dataId).values, x = new Array(i);
for (let $ = 0; $ < x.length; $++)
x[$] = r.shape[c[$]];
let k = Rv(v, r.shape, r.dtype, c, x);
h = n.makeTensorInfo(x, r.dtype);
let I = n.texData.get(h.dataId);
I.values = k;
} else
h = rh(r, c, n);
l = C.getInnerMostAxes(l.length, i);
}
C.assertAxesAreInnerMostDims("max", l, i);
let [f, m] = C.computeOutAndReduceShapes(h.shape, l), g = f;
o && (g = C.expandShapeToKeepDim(f, u));
let b;
if (d) {
let v = n.texData.get(h.dataId).values, x = _X(v, w.sizeFromShape(m), g, r.dtype);
b = n.makeTensorInfo(g, r.dtype);
let k = n.texData.get(b.dataId);
k.values = x;
} else
b = m7(h, m, g, n);
return p && n.disposeIntermediateTensorInfo(h), b;
}
var g7 = { kernelName: Ha, backendName: "webgl", kernelFunc: I2 };
var b7 = s2 + `
return max(a, b);
`;
var y7 = `
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
` + nh + `
return result;
`;
var v7 = jt({ opSnippet: b7, packedOpSnippet: y7, cpuKernelImpl: AX });
var x7 = { kernelName: qa, backendName: "webgl", kernelFunc: v7 };
function w7(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t;
ou(r, "maxPool");
let { filterSize: a, strides: o, pad: i, dimRoundingMode: u } = s, l = 1;
w.assert(C.eitherStridesOrDilationsAreOne(o, l), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${l}'`);
let c = C.computePool2DInfo(r.shape, a, o, l, i, u);
if (c.filterWidth === 1 && c.filterHeight === 1 && w.arraysEqual(c.inShape, c.outShape))
return Rn({ inputs: { x: r }, backend: n });
let p = new ol(c, "max", false);
return n.runWebGLProgram(p, [r], r.dtype);
}
var k7 = { kernelName: ja, backendName: "webgl", kernelFunc: w7 };
function S7(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { filterSize: a, strides: o, pad: i, dataFormat: u, dimRoundingMode: l } = s, c = [1, 1, 1], p = C.computePool3DInfo(r.shape, a, o, c, i, l, u), d = new Fv(p, "max", false);
return n.runWebGLProgram(d, [r], r.dtype);
}
var I7 = { kernelName: lp, backendName: "webgl", kernelFunc: S7 };
var C7 = class {
constructor(e) {
this.variableNames = ["dy", "maxPos"], this.outputShape = e.inShape;
let t = e.strideHeight, n = e.strideWidth, s = e.dilationHeight, r = e.effectiveFilterHeight, a = e.effectiveFilterWidth, o = r - 1 - e.padInfo.top, i = a - 1 - e.padInfo.left, u = r * a - 1;
this.userCode = `
const ivec2 pads = ivec2(${o}, ${i});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${r};
wR += ${s}) {
float dyR = float(dyRCorner + wR) / ${t}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${a}; wC++) {
float dyC = float(dyCCorner + wC) / ${n}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
int maxPosValue = ${u} - int(getMaxPos(b, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${a} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
`;
}
};
var N7 = class {
constructor(e) {
this.variableNames = ["dy", "maxPos"], this.outputShape = e.inShape;
let t = e.strideDepth, n = e.strideHeight, s = e.strideWidth, r = e.dilationDepth, a = e.dilationHeight, o = e.dilationWidth, i = e.effectiveFilterDepth, u = e.effectiveFilterHeight, l = e.effectiveFilterWidth, c = i - 1 - e.padInfo.front, p = u - 1 - e.padInfo.top, d = l - 1 - e.padInfo.left, h = i * u * l - 1;
this.userCode = `
const ivec3 pads = ivec3(${c}, ${p}, ${d});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${i};
wD += ${r}) {
float dyD = float(dyDCorner + wD) / ${t}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${u};
wR += ${a}) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${l};
wC += ${o}) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
int maxPosValue = ${h} -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * ${u} * ${l} +
wR * ${l} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
`;
}
};
function T7(e) {
let { inputs: t, backend: n, attrs: s } = e, { dy: r, input: a } = t, o = a, { filterSize: i, strides: u, pad: l, dimRoundingMode: c } = s, p = [1, 1, 1], d = C.computePool3DInfo(o.shape, i, u, p, l, c), h = new Fv(d, "max", true), f = n.runWebGLProgram(h, [o], o.dtype), m = new N7(d), g = n.runWebGLProgram(m, [r, f], o.dtype);
return n.disposeIntermediateTensorInfo(f), g;
}
var $7 = { kernelName: Fg, backendName: "webgl", kernelFunc: T7 };
function _7(e) {
let { inputs: t, backend: n, attrs: s } = e, { dy: r, input: a, output: o } = t, i = a;
ou([a, o], "maxPoolGrad");
let { filterSize: u, strides: l, pad: c, dimRoundingMode: p } = s, d = C.computePool2DInfo(i.shape, u, l, 1, c, p), h = true, f = new ol(d, "max", h), m = n.runWebGLProgram(f, [i], i.dtype), g = new C7(d), b = n.runWebGLProgram(g, [r, m], i.dtype);
return n.disposeIntermediateTensorInfo(m), b;
}
var A7 = { kernelName: Dg, backendName: "webgl", kernelFunc: _7 };
function E7(e, t, n, s) {
let r = new ol(n, "max", false), a = s.runWebGLProgram(r, [e], "float32");
r = new ol(n, "max", true, true, t);
let o = s.runWebGLProgram(r, [e], "float32");
return [a, o];
}
var R7 = { kernelName: Og, backendName: "webgl", kernelFunc: ({ inputs: e, attrs: t, backend: n }) => {
let { x: s } = e, { filterSize: r, strides: a, pad: o, includeBatchInIndex: i } = t, u = n;
w.assert(s.shape.length === 4, () => `Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);
let l = [1, 1];
w.assert(C.eitherStridesOrDilationsAreOne(a, l), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${l}'`);
let c = C.computePool2DInfo(s.shape, r, a, l, o), [p, d] = E7(s, i, c, u);
return [p, d];
} };
function D7(e, t, n, s) {
let r = w.sizeFromShape(t), o = w.sizeFromShape(e.shape) / r, i = pe({ inputs: { x: e }, attrs: { shape: [o, r] }, backend: s }), u = So(i, "float32", "mean", s), l = pe({ inputs: { x: u }, attrs: { shape: n }, backend: s });
return s.disposeIntermediateTensorInfo(i), s.disposeIntermediateTensorInfo(u), l;
}
var F7 = { kernelName: Ka, backendName: "webgl", kernelFunc: ({ inputs: e, attrs: t, backend: n }) => {
let { x: s } = e, { keepDims: r, axis: a } = t, o = n, i = s.shape.length, u = w.parseAxisParam(a, s.shape), l = u, c = C.getAxesPermutation(l, i), p = c != null, d = o.shouldExecuteOnCPU([s]), h = [], f = s;
if (p) {
if (d) {
let x = o.texData.get(f.dataId).values, k = new Array(i);
for (let R = 0; R < k.length; R++)
k[R] = s.shape[c[R]];
let I = Rv(x, s.shape, s.dtype, c, k);
f = o.makeTensorInfo(k, s.dtype);
let $ = o.texData.get(f.dataId);
$.values = I;
} else
f = rh(s, c, o);
h.push(f), l = C.getInnerMostAxes(l.length, i);
}
C.assertAxesAreInnerMostDims("sum", l, i);
let [m, g] = C.computeOutAndReduceShapes(f.shape, l), b = m;
r && (b = C.expandShapeToKeepDim(m, u));
let y = D7(f, g, b, o);
for (let v of h)
o.disposeIntermediateTensorInfo(v);
return y;
} };
function O7(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, keepDims: o } = s, i = r.shape.length, u = w.parseAxisParam(a, r.shape), l = u, c = C.getAxesPermutation(l, i), p = r;
c != null && (p = pn({ inputs: { x: r }, backend: n, attrs: { perm: c } }), l = C.getInnerMostAxes(l.length, r.shape.length)), C.assertAxesAreInnerMostDims("min", l, i);
let [d, h] = C.computeOutAndReduceShapes(p.shape, l), f = w.sizeFromShape(h), m = pe({ inputs: { x: p }, backend: n, attrs: { shape: [-1, f] } }), g = So(m, m.dtype, "min", n), b;
if (o) {
let y = C.expandShapeToKeepDim(d, u);
b = pe({ inputs: { x: g }, backend: n, attrs: { shape: y } });
} else
b = pe({ inputs: { x: g }, backend: n, attrs: { shape: d } });
return n.disposeIntermediateTensorInfo(m), n.disposeIntermediateTensorInfo(g), c != null && n.disposeIntermediateTensorInfo(p), b;
}
var P7 = { kernelName: Xa, backendName: "webgl", kernelFunc: O7 };
var z7 = s2 + `
return min(a, b);
`;
var L7 = `
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
` + nh + `
return result;
`;
var M7 = jt({ opSnippet: z7, packedOpSnippet: L7, cpuKernelImpl: EX });
var B7 = { kernelName: Ya, backendName: "webgl", kernelFunc: M7 };
var V7 = class {
constructor(e, t, n) {
this.variableNames = ["x"], this.outputShape = t.map((l, c) => l[0] + e[c] + l[1]);
let s = e.length, r = rt(s), a = t.map((l) => l[0]).join(","), o = t.map((l, c) => l[0] + e[c]).join(","), i = ["coords[0]", "coords[1]", "coords[2]", "coords[3]"].slice(0, s), u = n === "reflect" ? 0 : 1;
if (s === 1) {
this.userCode = `
int start = ${a};
int end = ${o};
void main() {
int outC = getOutputCoords();
if (outC < start) {
outC = start * 2 - outC - ${u};
} else if(outC >= end) {
outC = (end - 1) * 2 - outC + ${u};
}
setOutput(getX(outC - start));
}
`;
return;
}
this.userCode = `
${r} start = ${r}(${a});
${r} end = ${r}(${o});
void main() {
${r} outC = getOutputCoords();
for (int i = 0; i < ${s}; i++) {
if (outC[i] < start[i]) {
outC[i] = start[i] * 2 - outC[i] - ${u};
} else if(outC[i] >= end[i]) {
outC[i] = (end[i] - 1) * 2 - outC[i] + ${u};
}
}
${r} coords = outC - start;
setOutput(getX(${i}));
}
`;
}
};
var W7 = class {
constructor(e, t, n) {
this.variableNames = ["x"], this.packedInputs = true, this.packedOutput = true, this.outputShape = t.map((h, f) => h[0] + e[f] + h[1]);
let s = e.length, r = rt(s), a = t.map((h) => h[0]).join(","), o = t.map((h, f) => h[0] + e[f]).join(","), i = ln("rc", s), u = ln("source", s), l = `${i[s - 1]} < ${this.outputShape[s - 1]}`, c = s === 1 ? "source" : `vec2(${u.slice(-2).join()})`, p = n === "reflect" ? 0 : 1, d = "";
if (s === 1) {
let h = `
${r} source = rc;
if (source < start) {
source = start * 2 - source - ${p};
} else if (source >= end) {
source = (end - 1) * 2 - source + ${p};
}
source -= start;
`;
d = `
${r} rc = outputLoc;
${h}
result[0] = getChannel(getX(${u.join()}), ${c});
${i[s - 1]} += 1;
if(${l}) {
${h}
result[1] = getChannel(getX(${u.join()}), ${c});
}
`;
} else {
let h = `
${r} source = rc;
${r} lt = ${r}(lessThan(source, start));
${r} gte = ${r}(greaterThanEqual(source, end));
${r} orig = 1 - (lt + gte);
source = orig * source +
lt * (start * 2 - source - ${p}) +
gte * ((end - 1) * 2 - source + ${p});
source -= start;
`;
d = `
${r} rc = outputLoc;
${h}
result[0] = getChannel(getX(${u.join()}), ${c});
${i[s - 1]} += 1;
if(${l}) {
${h}
result[1] = getChannel(getX(${u.join()}), ${c});
}
rc = outputLoc;
${i[s - 2]} += 1;
if(${i[s - 2]} < ${this.outputShape[s - 2]}) {
${h}
result[2] = getChannel(getX(${u.join()}), ${c});
${i[s - 1]} += 1;
if(${l}) {
${h}
result[3] = getChannel(getX(${u.join()}), ${c});
}
}
`;
}
this.userCode = `
const ${r} start = ${r}(${a});
const ${r} end = ${r}(${o});
void main() {
${r} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${d}
setOutput(result);
}
`;
}
};
var U7 = ({ inputs: e, backend: t, attrs: n }) => {
let { x: s } = e, { paddings: r, mode: a } = n, o = K().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new W7(s.shape, r, a) : new V7(s.shape, r, a);
return t.runWebGLProgram(o, [s], s.dtype);
};
var G7 = { kernelName: Qa, backendName: "webgl", kernelFunc: U7 };
var H7 = `if (b == 0.0) return NAN;
return mod(a, b);`;
var q7 = `
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
` + nh + `
return result;
`;
var j7 = jt({ opSnippet: H7, packedOpSnippet: q7 });
var K7 = { kernelName: Cl, backendName: "webgl", kernelFunc: j7 };
var X7 = class {
constructor(e, t, n) {
this.variableNames = ["probs"], this.customUniforms = [{ name: "seed", type: "float" }], this.outputShape = [e, n], this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
float r = random(seed);
float cdf = 0.0;
for (int i = 0; i < ${t - 1}; i++) {
cdf += getProbs(batch, i);
if (r < cdf) {
setOutput(float(i));
return;
}
}
// If no other event happened, last event happened.
setOutput(float(${t - 1}));
}
`;
}
};
var Y7 = `
if (a == b) {
return 1.0;
};
return a / b;`;
var Q7 = `
// vec4 one = vec4(equal(a, b));
// return one + (vec4(1.0) - one) * a / b;
vec4 result = a / b;
if(a.x == b.x) {
result.x = 1.;
}
if(a.y == b.y) {
result.y = 1.;
}
if(a.z == b.z) {
result.z = 1.;
}
if(a.w == b.w) {
result.w = 1.;
}
return result;
`;
var C2 = jt({ opSnippet: Y7, packedOpSnippet: Q7, checkOutOfBounds: true });
var Z7 = { kernelName: Oa, backendName: "webgl", kernelFunc: C2 };
var Dw = "return a - b;";
var N2 = jt({ opSnippet: Dw, packedOpSnippet: Dw, supportsComplex: true, cpuKernelImpl: KX });
var J7 = { kernelName: fo, backendName: "webgl", kernelFunc: N2 };
function T2(e) {
let { inputs: t, backend: n, attrs: s } = e, { logits: r } = t, { dim: a } = s, o = w.parseAxisParam([a], r.shape), i = I2({ inputs: { x: r }, backend: n, attrs: { reductionIndices: o, keepDims: false } }), u = C.expandShapeToKeepDim(i.shape, o), l = pe({ inputs: { x: i }, backend: n, attrs: { shape: u } }), c = N2({ inputs: { a: r, b: l }, backend: n }), p = w2({ inputs: { x: c }, backend: n }), d = ah({ inputs: { x: p }, backend: n, attrs: { axis: o, keepDims: false } }), h = pe({ inputs: { x: d }, backend: n, attrs: { shape: u } }), f = C2({ inputs: { a: p, b: h }, backend: n });
return n.disposeIntermediateTensorInfo(i), n.disposeIntermediateTensorInfo(l), n.disposeIntermediateTensorInfo(c), n.disposeIntermediateTensorInfo(p), n.disposeIntermediateTensorInfo(d), n.disposeIntermediateTensorInfo(h), f;
}
var eJ = { kernelName: po, backendName: "webgl", kernelFunc: T2 };
function tJ(e) {
let { inputs: t, backend: n, attrs: s } = e, { logits: r } = t, { numSamples: a, seed: o, normalized: i } = s, u = i ? r : T2({ inputs: { logits: r }, backend: n, attrs: { dim: r.shape.length - 1 } }), l = u.shape[0], c = u.shape[1], p = new X7(l, c, a), d = [[o]], h = n.runWebGLProgram(p, [u], "int32", d);
return i || n.disposeIntermediateTensorInfo(u), h;
}
var nJ = { kernelName: Pg, backendName: "webgl", kernelFunc: tJ };
var sJ = ss + `
return -x;
`;
var rJ = `
vec4 result = -x;
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`;
function aJ(e) {
let { inputs: t, backend: n } = e, { x: s } = t;
if (n.shouldExecuteOnCPU([s])) {
let a = n.texData.get(s.dataId), [o, i] = DX(a.values, s.shape, s.dtype);
return n.makeTensorInfo(i, s.dtype, o);
}
let r;
return K().getBool("WEBGL_PACK_UNARY_OPERATIONS") ? r = new ea(s.shape, rJ) : r = new Gs(s.shape, sJ), n.runWebGLProgram(r, [s], s.dtype);
}
var oJ = { kernelName: $i, backendName: "webgl", kernelFunc: aJ };
var iJ = ws.nonMaxSuppressionV3Impl;
function uJ(e) {
C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
let { inputs: t, backend: n, attrs: s } = e, { boxes: r, scores: a } = t, { maxOutputSize: o, iouThreshold: i, scoreThreshold: u } = s, l = n.readSync(r.dataId), c = n.readSync(a.dataId), { selectedIndices: p } = iJ(l, c, o, i, u);
return n.makeTensorInfo([p.length], "int32", new Int32Array(p));
}
var lJ = { kernelName: Ai, backendName: "webgl", kernelFunc: uJ };
var cJ = ws.nonMaxSuppressionV4Impl;
function dJ(e) {
C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
let { inputs: t, backend: n, attrs: s } = e, { boxes: r, scores: a } = t, { maxOutputSize: o, iouThreshold: i, scoreThreshold: u, padToMaxOutputSize: l } = s, c = n.readSync(r.dataId), p = n.readSync(a.dataId), { selectedIndices: d, validOutputs: h } = cJ(c, p, o, i, u, l);
return [n.makeTensorInfo([d.length], "int32", new Int32Array(d)), n.makeTensorInfo([], "int32", new Int32Array([h]))];
}
var pJ = { kernelName: Nl, backendName: "webgl", kernelFunc: dJ };
var hJ = ws.nonMaxSuppressionV5Impl;
function fJ(e) {
C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
let { inputs: t, backend: n, attrs: s } = e, { boxes: r, scores: a } = t, { maxOutputSize: o, iouThreshold: i, scoreThreshold: u, softNmsSigma: l } = s, c = n.readSync(r.dataId), p = n.readSync(a.dataId), d = o, h = i, f = u, m = l, { selectedIndices: g, selectedScores: b } = hJ(c, p, d, h, f, m);
return [n.makeTensorInfo([g.length], "int32", new Int32Array(g)), n.makeTensorInfo([b.length], "float32", new Float32Array(b))];
}
var mJ = { kernelName: Ei, backendName: "webgl", kernelFunc: fJ };
var gJ = class {
constructor(e, t, n, s) {
this.variableNames = ["indices"], this.outputShape = [e, t], this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${s}), float(${n}),
float(index == coords.y)));
}
`;
}
};
var bJ = (e) => {
let { inputs: t, backend: n, attrs: s } = e, { indices: r } = t, { depth: a, onValue: o, offValue: i } = s, u = w.sizeFromShape(r.shape), l = new gJ(u, a, o, i), c = pe({ inputs: { x: r }, backend: n, attrs: { shape: [u] } }), p = n.runWebGLProgram(l, [c], r.dtype);
n.disposeIntermediateTensorInfo(c);
let d = [...r.shape, a], h = pe({ inputs: { x: p }, backend: n, attrs: { shape: d } });
return n.disposeIntermediateTensorInfo(p), h;
};
var yJ = { kernelName: Di, backendName: "webgl", kernelFunc: bJ };
function jd(e) {
let { inputs: t, backend: n } = e, { x: s } = t;
if (s.dtype === "complex64") {
let r = nc({ inputs: { input: s }, backend: n }), a = jd({ inputs: { x: r }, backend: n }), o = oh({ inputs: { input: s }, backend: n }), i = jd({ inputs: { x: o }, backend: n }), u = Fr({ inputs: { real: a, imag: i }, backend: n });
return n.disposeIntermediateTensorInfo(r), n.disposeIntermediateTensorInfo(a), n.disposeIntermediateTensorInfo(o), n.disposeIntermediateTensorInfo(i), u;
} else
return sc({ attrs: { shape: s.shape, dtype: s.dtype, value: s.dtype === "string" ? "" : 0 }, backend: n });
}
var vJ = { kernelName: Xi, backendName: "webgl", kernelFunc: jd };
function $2(e) {
let { inputs: t, backend: n } = e, { x: s } = t;
if (s.dtype === "string")
throw new Error("onesLike is not supported under string dtype");
if (s.dtype === "complex64") {
let r = nc({ inputs: { input: s }, backend: n }), a = $2({ inputs: { x: r }, backend: n }), o = oh({ inputs: { input: s }, backend: n }), i = jd({ inputs: { x: o }, backend: n }), u = Fr({ inputs: { real: a, imag: i }, backend: n });
return n.disposeIntermediateTensorInfo(r), n.disposeIntermediateTensorInfo(a), n.disposeIntermediateTensorInfo(o), n.disposeIntermediateTensorInfo(i), u;
} else
return sc({ attrs: { shape: s.shape, dtype: s.dtype, value: 1 }, backend: n });
}
var xJ = { kernelName: Ri, backendName: "webgl", kernelFunc: $2 };
function wJ(e) {
let { inputs: t, backend: n, attrs: s } = e, { axis: r } = s;
if (t.length === 1)
return rg({ inputs: { input: t[0] }, backend: n, attrs: { dim: r } });
let a = t[0].shape, o = t[0].dtype;
t.forEach((c) => {
w.assertShapesMatch(a, c.shape, "All tensors passed to stack must have matching shapes"), w.assert(o === c.dtype, () => "All tensors passed to stack must have matching dtypes");
});
let i = [], u = t.map((c) => {
let p = rg({ inputs: { input: c }, backend: n, attrs: { dim: r } });
return i.push(p), p;
}), l = f2({ inputs: u, backend: n, attrs: { axis: r } });
return i.forEach((c) => n.disposeIntermediateTensorInfo(c)), l;
}
var kJ = { kernelName: Fi, backendName: "webgl", kernelFunc: wJ };
var SJ = class {
constructor(e, t, n) {
this.variableNames = ["x"], this.customUniforms = [{ name: "value", type: "float" }], this.outputShape = t.map((u, l) => u[0] + e[l] + u[1]);
let s = e.length, r = rt(s), a = t.map((u) => u[0]).join(","), o = t.map((u, l) => u[0] + e[l]).join(","), i = ["coords[0]", "coords[1]", "coords[2]", "coords[3]"].slice(0, s);
if (s === 1) {
this.userCode = `
int start = ${a};
int end = ${o};
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(value);
} else {
setOutput(getX(outC - start));
}
}
`;
return;
}
this.userCode = `
${r} start = ${r}(${a});
${r} end = ${r}(${o});
void main() {
${r} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(value);
} else {
${r} coords = outC - start;
setOutput(getX(${i}));
}
}
`;
}
};
var IJ = class {
constructor(e, t, n) {
this.variableNames = ["x"], this.packedInputs = true, this.packedOutput = true, this.customUniforms = [{ name: "value", type: "float" }], this.outputShape = t.map((f, m) => f[0] + e[m] + f[1]);
let s = e.length, r = rt(s), a = t.map((f) => f[0]).join(","), o = t.map((f, m) => f[0] + e[m]).join(","), i = ln("rc", s), u = ln("source", s), l = `${i[s - 1]} < ${this.outputShape[s - 1]}`, c = s === 1 ? "source" : `vec2(${u.slice(-2).join()})`, p = [`${r} rc = outputLoc;`, `${i[s - 1]} += 1;
if(${l}) {
`, s === 1 ? "" : `}
rc = outputLoc;
${i[s - 2]} += 1;
if(${i[s - 2]} < ${this.outputShape[s - 2]}) {`, s === 1 ? "" : ` ${i[s - 1]} += 1;
if(${l}) {`], d = s === 1 ? "rc < start || rc >= end" : "any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))", h = "";
for (let f = 0, m = s === 1 ? 2 : 4; f < m; f++)
h += `
${p[f]}
if (${d}) {
result[${f}] = float(value);
} else {
${r} source = rc - start;
result[${f}] = getChannel(getX(${u.join()}), ${c});
}
`;
h += s === 1 ? "} " : "}}", this.userCode = `
const ${r} start = ${r}(${a});
const ${r} end = ${r}(${o});
void main() {
${r} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${h}
setOutput(result);
}
`;
}
};
var _2 = (e) => {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { paddings: a, constantValue: o } = s;
if (w.sizeFromShape(r.shape) === 0) {
let l = a.map((c, p) => c[0] + r.shape[p] + c[1]);
return sc({ backend: n, attrs: { shape: l, value: o, dtype: r.dtype } });
}
let i = K().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new IJ(r.shape, a, o) : new SJ(r.shape, a, o), u = [[o]];
return n.runWebGLProgram(i, [r], r.dtype, u);
};
var CJ = { kernelName: Ja, backendName: "webgl", kernelFunc: _2 };
var NJ = `
if(a < 0.0 && floor(b) < b){
return NAN;
}
if (b == 0.0) {
return 1.0;
}
return (round(mod(b, 2.0)) != 1) ?
pow(abs(a), b) : sign(a) * pow(abs(a), b);
`;
var TJ = `
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
vec4 result = multiplier * pow(abs(a), b);
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
bvec4 isExpZero = equal(b, vec4(0.0));
result.r = isExpZero.r ? 1.0 : result.r;
result.g = isExpZero.g ? 1.0 : result.g;
result.b = isExpZero.b ? 1.0 : result.b;
result.a = isExpZero.a ? 1.0 : result.a;
vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
` + nh + `
return result;
`;
var $J = jt({ opSnippet: NJ, packedOpSnippet: TJ });
var _J = { kernelName: eo, backendName: "webgl", kernelFunc: $J };
function AJ(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, keepDims: o } = s, i = r.shape.length, u = [], l = w.parseAxisParam(a, r.shape), c = l, p = C.getAxesPermutation(c, i), d = r;
p != null && (d = pn({ inputs: { x: r }, backend: n, attrs: { perm: p } }), c = C.getInnerMostAxes(c.length, i), u.push(d)), C.assertAxesAreInnerMostDims("prod", c, i);
let h;
if (n.shouldExecuteOnCPU([d])) {
let f = n.texData.get(d.dataId).values, { outVals: m, outShape: g, outDtype: b } = OX(d.shape, d.dtype, f, c);
h = n.makeTensorInfo(g, b, m);
} else {
let [f, m] = C.computeOutAndReduceShapes(d.shape, c), g = w.sizeFromShape(m), b = pe({ inputs: { x: d }, backend: n, attrs: { shape: [-1, g] } }), y = yp(r.dtype), v = So(b, y, "prod", n);
h = pe({ inputs: { x: v }, backend: n, attrs: { shape: f } }), u.push(b), u.push(v);
}
if (o) {
u.push(h);
let f = C.expandShapeToKeepDim(h.shape, l);
h = pe({ inputs: { x: h }, backend: n, attrs: { shape: f } });
}
return u.forEach((f) => n.disposeIntermediateTensorInfo(f)), h;
}
var EJ = { kernelName: no, backendName: "webgl", kernelFunc: AJ };
var A2 = (e) => {
let { backend: t, attrs: n } = e, { start: s, stop: r, step: a, dtype: o } = n, i = PX(s, r, a, o);
return t.makeTensorInfo([i.length], o, i);
};
var RJ = { kernelName: Tl, backendName: "webgl", kernelFunc: A2 };
var DJ = "return 1.0 / x;";
var FJ = Ke({ opSnippet: DJ });
var OJ = { kernelName: $l, backendName: "webgl", kernelFunc: FJ };
var PJ = ss + `
return (x < 0.0) ? 0.0 : x;
`;
var zJ = `
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`;
var LJ = Ke({ opSnippet: PJ, packedOpSnippet: zJ });
var MJ = { kernelName: so, backendName: "webgl", kernelFunc: LJ };
var BJ = ss + `
return (x < 0.0) ? 0.0 : min(6.0, x);
`;
var VJ = `
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`;
var WJ = Ke({ opSnippet: BJ, packedOpSnippet: VJ });
var UJ = { kernelName: ao, backendName: "webgl", kernelFunc: WJ };
var GJ = class {
constructor(e, t, n, s, r) {
this.variableNames = ["A"], this.outputShape = [];
let [a, o, i, u] = e;
this.outputShape = [a, t, n, u];
let l = [s && t > 1 ? o - 1 : o, s && n > 1 ? i - 1 : i], c = [s && t > 1 ? t - 1 : t, s && n > 1 ? n - 1 : n], p;
r ? p = "(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)" : p = "vec2(yRC) * effectiveInputOverOutputRatioRC", this.userCode = `
const vec2 effectiveInputOverOutputRatioRC = vec2(
${l[0] / c[0]},
${l[1] / c[1]});
const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = ${p};
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
float top = topLeft + (topRight - topLeft) * fracRC.y;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
float newValue = top + (bottom - top) * fracRC.x;
setOutput(newValue);
}
`;
}
};
var HJ = class {
constructor(e, t, n, s, r) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.outputShape = [];
let [a, o, i, u] = e;
this.outputShape = [a, t, n, u];
let l = [s && t > 1 ? o - 1 : o, s && n > 1 ? i - 1 : i], c = [s && t > 1 ? t - 1 : t, s && n > 1 ? n - 1 : n], p;
r ? p = "(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)" : p = "vec3(yRC) * effectiveInputOverOutputRatioRC", this.userCode = `
const vec3 effectiveInputOverOutputRatioRC = vec3(
${l[0] / c[0]},
${l[1] / c[1]},
${l[1] / c[1]});
const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,
${i}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
// Fractional source index.
vec3 sourceFracIndexRC = ${p};
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));
ivec3 sourceCeilRC = ivec3(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${u - 1};
bool hasNextRow = coords.z < ${n - 1};
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4(
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 bottomLeft = vec4(
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 topRight = vec4(
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec4 bottomRight = vec4(
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
vec4 newValue = mix(top, bottom, fracRC.x);
setOutput(newValue);
}
`;
}
};
function qJ(e) {
let { inputs: t, backend: n, attrs: s } = e, { images: r } = t, { alignCorners: a, halfPixelCenters: o, size: i } = s, [u, l] = i, c = K().getBool("WEBGL_PACK_IMAGE_OPERATIONS") ? new HJ(r.shape, u, l, a, o) : new GJ(r.shape, u, l, a, o);
return n.runWebGLProgram(c, [r], "float32");
}
var jJ = { kernelName: ro, backendName: "webgl", kernelFunc: qJ };
var KJ = class {
constructor(e, t, n) {
this.variableNames = ["dy"], this.outputShape = [], this.outputShape = t;
let [, s, r] = t, [, a, o] = e, i = [n && a > 1 ? s - 1 : s, n && o > 1 ? r - 1 : r], u = [n && a > 1 ? a - 1 : a, n && o > 1 ? o - 1 : o], l = i[0] / u[0], c = i[1] / u[1], p = 1 / l, d = 1 / c, h = Math.ceil(p) * 2 + 2, f = Math.ceil(d) * 2 + 2;
this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${l});
const float widthScale = float(${c});
const float invHeightScale = float(${p});
const float invWidthScale = float(${d});
const int winHeight = int(${h});
const int winWidth = int(${f});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(startCLerp - float(winWidth / 2));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${a}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${o}) {
continue;
}
float dxR = float(dyR) * heightScale;
int topDxRIndex = int(floor(dxR));
int bottomDxRIndex = int(min(ceil(dxR), ${s - 1}.0));
float dxRLerp = dxR - float(topDxRIndex);
float inverseDxRLerp = 1.0 - dxRLerp;
float dxC = float(dyC) * widthScale;
int leftDxCIndex = int(floor(dxC));
int rightDxCIndex = int(min(ceil(dxC), ${r - 1}.0));
float dxCLerp = dxC - float(leftDxCIndex);
float inverseDxCLerp = 1.0 - dxCLerp;
if (r == topDxRIndex && c == leftDxCIndex) {
// topLeft
accumulator +=
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
}
if (r == topDxRIndex && c == rightDxCIndex) {
// topRight
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
}
if (r == bottomDxRIndex && c == leftDxCIndex) {
// bottomLeft
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
}
if (r == bottomDxRIndex && c == rightDxCIndex) {
// bottomRight
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
}
}
}
// End loop over dy
setOutput(accumulator);
}
`;
}
};
function XJ(e) {
let { inputs: t, backend: n, attrs: s } = e, { images: r, dy: a } = t, { alignCorners: o } = s, i = new KJ(a.shape, r.shape, o);
return n.runWebGLProgram(i, [a], a.dtype);
}
var YJ = { kernelName: Lg, backendName: "webgl", kernelFunc: XJ };
var QJ = class {
constructor(e, t, n, s, r) {
this.variableNames = ["A"], this.outputShape = [];
let [a, o, i, u] = e;
this.outputShape = [a, t, n, u];
let l = [s && t > 1 ? o - 1 : o, s && n > 1 ? i - 1 : i], c = [s && t > 1 ? t - 1 : t, s && n > 1 ? n - 1 : n], p = s ? "0.5" : "0.0", d;
r ? d = "max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))" : d = "vec2(yRC) * effectiveInputOverOutputRatioRC", this.userCode = `
const vec2 effectiveInputOverOutputRatioRC = vec2(
${l[0] / c[0]},
${l[1] / c[1]});
const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = ${d};
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${p})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
}
`;
}
};
var ZJ = class {
constructor(e, t, n, s, r) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.outputShape = [];
let [a, o, i, u] = e;
this.outputShape = [a, t, n, u];
let l = [s && t > 1 ? o - 1 : o, s && n > 1 ? i - 1 : i], c = [s && t > 1 ? t - 1 : t, s && n > 1 ? n - 1 : n], p = s ? "0.5" : "0.0", d;
r ? d = "max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))" : d = "vec3(yRC) * effectiveInputOverOutputRatioRC", this.userCode = `
const vec3 effectiveInputOverOutputRatioRC = vec3(
${l[0] / c[0]},
${l[1] / c[1]},
${l[1] / c[1]});
const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,
${i}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
// Fractional source index.
vec3 sourceFracIndexRC = ${d};
// Compute the coordinators of nearest neighbor point.
ivec3 sourceNearestRC = ivec3(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${p})));
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${u - 1};
bool hasNextRow = coords.z < ${n - 1};
vec4 newValue = vec4(
getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),
hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);
setOutput(newValue);
}
`;
}
};
function JJ(e) {
let { inputs: t, backend: n, attrs: s } = e, { images: r } = t, { alignCorners: a, halfPixelCenters: o, size: i } = s, [u, l] = i, c = K().getBool("WEBGL_PACK_IMAGE_OPERATIONS") ? new ZJ(r.shape, u, l, a, o) : new QJ(r.shape, u, l, a, o);
return n.runWebGLProgram(c, [r], r.dtype);
}
var eee = { kernelName: _l, backendName: "webgl", kernelFunc: JJ };
var tee = class {
constructor(e, t, n) {
this.variableNames = ["dy"], this.outputShape = [], this.outputShape = t;
let [, s, r] = t, [, a, o] = e, i = [n && a > 1 ? s - 1 : s, n && o > 1 ? r - 1 : r], u = [n && a > 1 ? a - 1 : a, n && o > 1 ? o - 1 : o], l = i[0] / u[0], c = i[1] / u[1], p = 1 / l, d = 1 / c, h = Math.ceil(p) * 2 + 2, f = Math.ceil(d) * 2 + 2;
this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${l});
const float widthScale = float(${c});
const float invHeightScale = float(${p});
const float invWidthScale = float(${d});
const int winHeight = int(${h});
const int winWidth = int(${f});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${a}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${o}) {
continue;
}
float sourceFracRow =
float(${i[0]}) *
(float(dyR) / float(${u[0]}));
float sourceFracCol =
float(${i[1]}) *
(float(dyC) / float(${u[1]}));
int sourceNearestRow = int(min(
float(int(${s}) - 1),
${n} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
int sourceNearestCol = int(min(
float(int(${r}) - 1),
${n} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
}
`;
}
};
function nee(e) {
let { inputs: t, backend: n, attrs: s } = e, { images: r, dy: a } = t, { alignCorners: o } = s, i = new tee(a.shape, r.shape, o);
return n.runWebGLProgram(i, [a], a.dtype);
}
var see = { kernelName: zg, backendName: "webgl", kernelFunc: nee };
var ree = class {
constructor(e, t) {
this.variableNames = ["x"];
let n = e.length;
if (n > 4)
throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);
if (this.outputShape = e, n === 1) {
this.userCode = `
void main() {
int coord = getOutputCoords();
setOutput(getX(${e[0]} - coord - 1));
}
`;
return;
}
let s = (o) => t.indexOf(o) !== -1 && e[o] !== 1 ? `${e[o]} - coords[${o}] - 1` : `coords[${o}]`, r = e.map((o, i) => s(i)).join(","), a = rt(n);
this.userCode = `
void main() {
${a} coords = getOutputCoords();
setOutput(getX(${r}));
}
`;
}
};
var aee = class {
constructor(e, t) {
this.variableNames = ["x"], this.packedInputs = true, this.packedOutput = true;
let n = e.length;
if (n > 4)
throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);
this.outputShape = e;
let s = ln("rc", n), r = `${s[n - 1]} + 1 < ${this.outputShape[n - 1]}`, a = `${s[n - 2]} + 1 < ${this.outputShape[n - 2]}`, o = rt(n);
n === 1 ? this.userCode = `
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = getChannel(getX(${e[0]} - rc - 1),
${e[0]} - rc - 1);
if(${r}){
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
${e[0]} - (rc + 1) - 1);
}
setOutput(result);
}
` : this.userCode = `
void main() {
${o} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${i(s.slice())};
if(${r}){
result.g = ${u(s.slice())};
}
if(${a}) {
result.b = ${l(s.slice())};
if(${r}) {
result.a = ${c(s.slice())};
}
}
setOutput(result);
}
`;
function i(h) {
return p(h);
}
function u(h) {
return h[n - 1] = "(" + h[n - 1] + " + 1)", p(h);
}
function l(h) {
return h[n - 2] = "(" + h[n - 2] + " + 1)", p(h);
}
function c(h) {
return h[n - 1] = "(" + h[n - 1] + " + 1)", h[n - 2] = "(" + h[n - 2] + " + 1)", p(h);
}
function p(h) {
let f = e.map((b, y) => d(y, h)), m = f.join(","), g = f.slice(-2).join(",");
return `getChannel(getX(${m}), vec2(${g}))`;
}
function d(h, f) {
return t.indexOf(h) !== -1 && e[h] !== 1 ? `${e[h]} - ${f[h]} - 1` : `${f[h]}`;
}
}
};
function oee(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { dims: a } = s, o = r.shape.length, i = w.parseAxisParam(a, r.shape);
if (o === 0)
return Rn({ inputs: { x: r }, backend: n });
let u = K().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new aee(r.shape, i) : new ree(r.shape, i);
return n.runWebGLProgram(u, [r], r.dtype);
}
var iee = { kernelName: Pi, backendName: "webgl", kernelFunc: oee };
var uee = class {
constructor(e, t) {
this.variableNames = ["Image"], this.outputShape = [], this.customUniforms = [{ name: "params", type: "vec4" }];
let n = e[1], s = e[2];
this.outputShape = e;
let r = "";
typeof t == "number" ? r = `float outputValue = ${t.toFixed(2)};` : r = `
vec3 fill = vec3(${t.join(",")});
float outputValue = fill[coords[3]];`, this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int y = coords[1];
float coordXFloat = (float(x) - params[0]) * params[3] -
(float(y) - params[1]) * params[2];
float coordYFloat = (float(x) - params[0]) * params[2] +
(float(y) - params[1]) * params[3];
int coordX = int(round(coordXFloat + params[0]));
int coordY = int(round(coordYFloat + params[1]));
${r}
if(coordX >= 0 && coordX < ${s} && coordY >= 0 && coordY < ${n}) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
`;
}
};
var lee = { kernelName: Yi, backendName: "webgl", kernelFunc: ({ inputs: e, attrs: t, backend: n }) => {
let { image: s } = e, { radians: r, fillValue: a, center: o } = t, i = n, u = new uee(s.shape, a), [l, c] = C.getImageCenter(o, s.shape[1], s.shape[2]), p = [[l, c, Math.sin(r), Math.cos(r)]];
return i.runWebGLProgram(u, [s], s.dtype, p);
} };
var cee = `
// OpenGL ES does not support round function.
// The algorithm is based on banker's rounding.
float base = floor(x);
if ((x - base) < 0.5) {
return floor(x);
} else if ((x - base) > 0.5) {
return ceil(x);
} else {
if (mod(base, 2.0) == 0.0) {
return base;
} else {
return base + 1.0;
}
}
`;
var dee = Ke({ opSnippet: cee });
var pee = { kernelName: zi, backendName: "webgl", kernelFunc: dee };
var hee = "return inversesqrt(x);";
var fee = Ke({ opSnippet: hee, cpuKernelImpl: zX });
var mee = { kernelName: oo, backendName: "webgl", kernelFunc: fee };
var E2 = class {
constructor(e, t, n, s, r, a, o = true) {
this.variableNames = ["updates", "indices", "defaultValue"], this.outputShape = a;
let i = rt(r.length), u = rt(a.length), l = "";
n === 1 ? l = "i" : n === 2 && (l = "i, j");
let c = `getIndices(${l})`, p = "";
s === 1 ? p = "i" : s === 2 && (p = "i, coords[1]");
let d = `getUpdates(${p})`, h = t > 1 ? "strides[j]" : "strides";
this.userCode = `
${i} strides = ${i}(${r});
void main() {
${u} coords = getOutputCoords();
float sum = 0.0;
bool found = false;
for (int i = 0; i < ${e}; i++) {
int flattenedIndex = 0;
for (int j = 0; j < ${t}; j++) {
int index = round(${c});
flattenedIndex += index * ${h};
}
if (flattenedIndex == coords[0]) {
sum += ${d};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
`;
}
};
function gee(e) {
let { inputs: t, backend: n, attrs: s } = e, { indices: r, updates: a } = t, { shape: o } = s, { sliceRank: i, numUpdates: u, sliceSize: l, strides: c, outputSize: p } = C.calculateShapes(a, r, o), d = [p / l, l];
if (p === 0)
return n.makeTensorInfo(o, r.dtype);
let h = pe({ inputs: { x: r }, backend: n, attrs: { shape: [u, i] } }), f = pe({ inputs: { x: a }, backend: n, attrs: { shape: [u, l] } }), m = n.makeTensorInfo([], "float32", new Float32Array([0])), g = new E2(u, i, h.shape.length, f.shape.length, c, d), b = n.runWebGLProgram(g, [f, h, m], f.dtype), y = pe({ inputs: { x: b }, backend: n, attrs: { shape: o } });
return n.disposeIntermediateTensorInfo(h), n.disposeIntermediateTensorInfo(f), n.disposeIntermediateTensorInfo(b), n.disposeIntermediateTensorInfo(m), y;
}
var bee = { kernelName: Li, backendName: "webgl", kernelFunc: gee };
var yee = class {
constructor(e, t, n, s) {
this.variableNames = ["sortedSequence", "values"], this.customUniforms = [{ name: "numInputs", type: "int" }], this.outputShape = [e, n];
let r = "while (left < right) {", a = `for (int i = 0; i < ${Math.ceil(Math.log2(t + 1))}; ++i) { if (left >= right) break;`, o = K().getNumber("WEBGL_VERSION") === 2 ? r : a, i = s === "left" ? "<" : "<=";
this.userCode = `
int findBound(int batch, float value) {
int left = 0;
int right = numInputs;
int mid;
${o}
mid = (left + right) / 2;
if (getSortedSequence(batch, mid) ${i} value) {
left = mid + 1;
} else {
right = mid;
}
}
return right;
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int valueIndex = coords[1];
float value = getValues(batch, valueIndex);
setOutput(float(findBound(batch, value)));
}
`;
}
};
function vee(e) {
let { inputs: t, backend: n, attrs: s } = e, { sortedSequence: r, values: a } = t, { side: o } = s, i = new yee(r.shape[0], r.shape[1], a.shape[1], o), u = [[r.shape[1]]];
return n.runWebGLProgram(i, [r, a], "int32", u);
}
var xee = { kernelName: Mg, backendName: "webgl", kernelFunc: vee };
var wee = class {
constructor(e, t, n) {
this.variableNames = ["c", "a", "b"], this.outputShape = t;
let s, r;
if (n > 4)
throw Error(`Where for rank ${n} is not yet supported`);
if (n === 1)
r = "resRC", s = "resRC";
else {
let o = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"], i = [], u = [];
for (let l = 0; l < t.length; l++)
u.push(`${o[l]}`), l < e && i.push(`${o[l]}`);
s = i.join(), r = u.join();
}
let a = rt(n);
this.userCode = `
void main() {
${a} resRC = getOutputCoords();
float cVal = getC(${s});
if (cVal >= 1.0) {
setOutput(getA(${r}));
} else {
setOutput(getB(${r}));
}
}
`;
}
};
function kee(e) {
let { inputs: t, backend: n } = e, { condition: s, t: r, e: a } = t, o = new wee(s.shape.length, r.shape, r.shape.length);
return n.runWebGLProgram(o, [s, r, a], cn(r.dtype, a.dtype));
}
var See = { kernelName: Mi, backendName: "webgl", kernelFunc: kee };
var Iee = `
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ${C.SELU_SCALEALPHA};
float scale = ${C.SELU_SCALE};
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`;
var Cee = Ke({ opSnippet: Iee });
var Nee = { kernelName: Al, backendName: "webgl", kernelFunc: Cee };
var Tee = du + `
return 1.0 / (1.0 + exp(-1.0 * x));
`;
var $ee = `
vec4 result = 1.0 / (1.0 + exp(-1.0 * x));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`;
var _ee = Ke({ opSnippet: Tee, packedOpSnippet: $ee, cpuKernelImpl: MX });
var Aee = { kernelName: uo, backendName: "webgl", kernelFunc: _ee };
var Eee = `
if (isnan(x)) { return 0.0; }
return sign(x);
`;
var Ree = Ke({ opSnippet: Eee });
var Dee = { kernelName: El, backendName: "webgl", kernelFunc: Ree };
var Fee = du + `
return sin(x);
`;
var Oee = Ke({ opSnippet: Fee });
var Pee = { kernelName: io, backendName: "webgl", kernelFunc: Oee };
var zee = `
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`;
var Lee = Ke({ opSnippet: zee });
var Mee = { kernelName: Vi, backendName: "webgl", kernelFunc: Lee };
var Bee = `
float epsilon = 1.1920928955078125e-7;
float threshold = log(epsilon) + 2.0;
bool too_large = x > -threshold;
bool too_small = x < threshold;
float result;
float exp_x = exp(x);
if (too_large){
result = x;
}
else if (too_small){
result = exp_x;
}
else{
result = log(exp_x + 1.0);
}
return result;
`;
var Vee = Ke({ opSnippet: Bee });
var Wee = { kernelName: Rl, backendName: "webgl", kernelFunc: Vee };
var Uee = (e) => {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { blockShape: a, paddings: o } = s;
w.assert(r.shape.length <= 4, () => "spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");
let i = a.reduce((b, y) => b * y), u = [[0, 0]];
u.push(...o);
for (let b = 1 + a.length; b < r.shape.length; ++b)
u.push([0, 0]);
let l = [], c = _2({ inputs: { x: r }, backend: n, attrs: { paddings: u, constantValue: 0 } }), p = C.getReshaped(c.shape, a, i, false), d = C.getPermuted(p.length, a.length, false), h = C.getReshapedPermuted(c.shape, a, i, false), f = pe({ inputs: { x: c }, backend: n, attrs: { shape: p } }), m = pn({ inputs: { x: f }, backend: n, attrs: { perm: d } }), g = pe({ inputs: { x: m }, backend: n, attrs: { shape: h } });
return l.push(c), l.push(f), l.push(m), l.forEach((b) => n.disposeIntermediateTensorInfo(b)), g;
};
var Gee = { kernelName: Wi, backendName: "webgl", kernelFunc: Uee };
function Hee(e) {
let { inputs: t, backend: n } = e, { indices: s, values: r, denseShape: a, defaultValue: o } = t;
if (a.shape.length !== 1)
throw new Error(`Dense shape must be a vector, saw:
${a.shape}`);
if (s.shape.length !== 2)
throw new Error(`Indices must be a matrix, saw:
${s.shape}`);
if (r.shape.length !== 1)
throw new Error(`Values must be a vector, saw:
${r.shape}`);
if (o.shape.length !== 0)
throw new Error(`Default value must be a scalar, saw:
${o.shape}`);
let i = n.readSync(s.dataId), u = n.readSync(r.dataId), l = n.readSync(a.dataId), c = n.readSync(o.dataId)[0], [p, d, h, f, m] = VX(i, s.shape, s.dtype, u, r.dtype, l, c);
return [n.makeTensorInfo(d, s.dtype, p), n.makeTensorInfo([d[0]], r.dtype, h), n.makeTensorInfo([f.length], "bool", new Uint8Array(f.map((g) => Number(g)))), n.makeTensorInfo([m.length], s.dtype, new Int32Array(m))];
}
var qee = { kernelName: dp, backendName: "webgl", kernelFunc: Hee };
function jee(e) {
let { inputs: t, backend: n } = e, { inputIndices: s, inputShape: r, newShape: a } = t;
if (s.shape.length !== 2)
throw new Error(`Input indices should be a matrix but received shape ${s.shape}`);
if (r.shape.length !== 1)
throw new Error(`Input shape should be a vector but received shape ${r.shape}`);
if (a.shape.length !== 1)
throw new Error(`Target shape should be a vector but received shape ${a.shape}`);
let o = Array.from(n.readSync(r.dataId)), i = n.readSync(s.dataId), u = Array.from(n.readSync(a.dataId)), [l, c, p] = WX(i, s.shape, s.dtype, o, u);
return [n.makeTensorInfo(c, s.dtype, l), n.makeTensorInfo([p.length], a.dtype, new Int32Array(p))];
}
var Kee = { kernelName: Dl, backendName: "webgl", kernelFunc: jee };
function Xee(e) {
let { inputs: t, backend: n } = e, { data: s, indices: r, segmentIds: a } = t;
if (s.shape.length < 1)
throw new Error("Data should be at least 1 dimensional but received scalar");
if (r.shape.length !== 1)
throw new Error(`Indices should be a vector but received shape
${r.shape}`);
if (a.shape.length !== 1)
throw new Error(`Segment ids should be a vector but received shape
${a.shape}`);
let o = n.readSync(s.dataId), i = n.readSync(r.dataId), u = n.readSync(a.dataId), [l, c] = Z1(o, s.shape, s.dtype, i, u, true);
return n.makeTensorInfo(c, s.dtype, l);
}
var Yee = { kernelName: pp, backendName: "webgl", kernelFunc: Xee };
function Qee(e) {
let { inputs: t, backend: n } = e, { data: s, indices: r, segmentIds: a } = t;
if (s.shape.length < 1)
throw new Error("Data should be at least 1 dimensional but received scalar");
if (r.shape.length !== 1)
throw new Error(`Indices should be a vector but received shape
${r.shape}`);
if (a.shape.length !== 1)
throw new Error(`Segment ids should be a vector but received shape
${a.shape}`);
let o = n.readSync(s.dataId), i = n.readSync(r.dataId), u = n.readSync(a.dataId), [l, c] = Z1(o, s.shape, s.dtype, i, u);
return n.makeTensorInfo(c, s.dtype, l);
}
var Zee = { kernelName: hp, backendName: "webgl", kernelFunc: Qee };
function Jee(e) {
let { inputs: t, backend: n, attrs: s } = e, { sparseIndices: r, sparseValues: a, defaultValue: o } = t, { outputShape: i } = s, { sliceRank: u, numUpdates: l, sliceSize: c, strides: p, outputSize: d } = C.calculateShapes(a, r, i), h = false;
if (a.dtype === "string") {
let b = n.bufferSync(r), y = n.bufferSync(a), v = w.decodeString(n.readSync(o.dataId)[0]), x = LX(b, y, i, d, c, l, u, p, v, h);
return n.makeTensorInfo(i, x.dtype, x.values);
}
let f = new E2(l, u, r.shape.length, a.shape.length, p, [d, 1], h), m = n.runWebGLProgram(f, [a, r, o], a.dtype), g = pe({ inputs: { x: m }, backend: n, attrs: { shape: i } });
return n.disposeIntermediateTensorInfo(m), g;
}
var ete = { kernelName: fp, backendName: "webgl", kernelFunc: Jee };
function tte(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { numOrSizeSplits: a, axis: o } = s, i = w.parseAxisParam(o, r.shape)[0], u = C.prepareSplitSize(r, a, i), l = r.shape.length, c = new Array(l).fill(0), p = r.shape.slice();
return u.map((d) => {
let h = [...p];
h[i] = d;
let f = pu({ inputs: { x: r }, backend: n, attrs: { begin: c, size: h } });
return c[i] += d, f;
});
}
var nte = { kernelName: Ui, backendName: "webgl", kernelFunc: tte };
var Fw = "return sqrt(x);";
var ste = Ke({ opSnippet: Fw, packedOpSnippet: Fw, cpuKernelImpl: UX });
var rte = { kernelName: lo, backendName: "webgl", kernelFunc: ste };
var ate = "return x * x;";
var ote = Ke({ opSnippet: ate });
var ite = { kernelName: Fl, backendName: "webgl", kernelFunc: ote };
var Ow = "return (a - b) * (a - b);";
var ute = jt({ opSnippet: Ow, packedOpSnippet: Ow });
var lte = { kernelName: ho, backendName: "webgl", kernelFunc: ute };
function cte({ inputs: e, attrs: t, backend: n }) {
let { x: s } = e, r = ss + `
return x > 0.0 ? 1.0 : float(${t.alpha});
`, a = new Gs(s.shape, r);
return n.runWebGLProgram(a, [s], s.dtype);
}
var dte = { kernelName: go, backendName: "webgl", kernelFunc: cte };
var pte = class {
constructor(e, t, n) {
this.variableNames = ["x"], this.outputShape = n;
let s = n.length, r = rt(n.length), a = rt(n.length), o = "";
if (s === 1)
o = "coords * strides + begin";
else {
let i = 0;
o = n.map((u, l) => (i++, n.length === 1 ? `coords * strides[${l}] + begin[${l}]` : `coords[${i - 1}] * strides[${l}] + begin[${l}]`)).join(",");
}
this.userCode = `
${r} begin = ${r}(${e});
${r} strides = ${r}(${t});
void main() {
${a} coords = getOutputCoords();
setOutput(getX(${o}));
}
`;
}
};
function hte(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { begin: a, end: o, strides: i, beginMask: u, endMask: l, ellipsisMask: c, newAxisMask: p, shrinkAxisMask: d } = s, { finalShapeSparse: h, finalShape: f, isIdentity: m, sliceDim0: g, isSimpleSlice: b, begin: y, end: v, strides: x } = kt.sliceInfo(r.shape, a, o, i, u, l, c, p, d), k;
if (m)
k = pe({ inputs: { x: r }, backend: n, attrs: { shape: f } });
else if (g || b) {
w.assert(r.shape.length >= 1, () => `Input must have rank at least 1, got: ${r.shape.length}`);
let $ = kt.computeOutShape(y, v, x), R = pu({ inputs: { x: r }, backend: n, attrs: { begin: y, size: $ } });
k = pe({ inputs: { x: R }, backend: n, attrs: { shape: f } }), n.disposeIntermediateTensorInfo(R);
} else if (n.shouldExecuteOnCPU([r])) {
let R = n.readSync(r.dataId), E = Ae(r.shape, r.dtype, R), P = GX(h, E, x, y);
k = n.makeTensorInfo(f, r.dtype, P.values);
} else {
let R = new pte(y, x, h);
k = n.runWebGLProgram(R, [r], r.dtype);
}
let I = pe({ inputs: { x: k }, backend: n, attrs: { shape: f } });
return n.disposeIntermediateTensorInfo(k), I;
}
var fte = { kernelName: Gi, backendName: "webgl", kernelFunc: hte };
function mte(e) {
let { inputs: t, backend: n, attrs: s } = e, { separator: r, nGramWidths: a, leftPad: o, rightPad: i, padWidth: u, preserveShortSequences: l } = s, { data: c, dataSplits: p } = t, d = n.readSync(c.dataId), h = n.readSync(p.dataId), [f, m] = HX(d, h, r, a, o, i, u, l);
return [n.makeTensorInfo([f.length], "string", f), n.makeTensorInfo(p.shape, "int32", m)];
}
var gte = { kernelName: mp, backendName: "webgl", kernelFunc: mte };
function bte(e) {
let { inputs: t, backend: n, attrs: s } = e, { skipEmpty: r } = s, { input: a, delimiter: o } = t;
if (a.dtype !== "string")
throw new Error("Input must be of datatype string");
if (a.shape.length !== 1)
throw new Error(`Input must be a vector, got shape: ${a.shape}`);
if (o.shape.length !== 0)
throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);
let i = n.readSync(a.dataId), u = n.readSync(o.dataId)[0], [l, c, p] = qX(i, u, r), d = c.length;
return [n.makeTensorInfo([d, 2], "int32", l), n.makeTensorInfo([d], "string", c), n.makeTensorInfo([2], "int32", new Int32Array(p))];
}
var yte = { kernelName: Bg, backendName: "webgl", kernelFunc: bte };
function vte(e) {
let { inputs: t, backend: n, attrs: s } = e, { numBuckets: r } = s, { input: a } = t;
if (a.dtype !== "string")
throw new Error("Input must be of datatype string");
if (r <= 0)
throw new Error("Number of buckets must be at least 1");
let o = n.readSync(a.dataId), i = jX(o, r);
return n.makeTensorInfo(a.shape, "int32", i);
}
var xte = { kernelName: Vg, backendName: "webgl", kernelFunc: vte };
var wte = "return tan(x);";
var kte = Ke({ opSnippet: wte });
var Ste = { kernelName: Hi, backendName: "webgl", kernelFunc: kte };
var Ite = `
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`;
var Cte = Ke({ opSnippet: Ite });
var Nte = { kernelName: mo, backendName: "webgl", kernelFunc: Cte };
var Tte = class {
constructor(e, t) {
this.variableNames = ["A"];
let n = new Array(e.length);
for (let a = 0; a < n.length; a++)
n[a] = e[a] * t[a];
this.outputShape = n, this.rank = n.length;
let s = rt(this.rank), r = $te(e);
this.userCode = `
void main() {
${s} resRC = getOutputCoords();
setOutput(getA(${r}));
}
`;
}
};
function $te(e) {
let t = e.length;
if (t > 5)
throw Error(`Tile for rank ${t} is not yet supported`);
if (t === 1)
return `imod(resRC, ${e[0]})`;
let n = ["resRC.x", "resRC.y", "resRC.z", "resRC.w", "resRC.u"], s = [];
for (let r = 0; r < e.length; r++)
s.push(`imod(${n[r]}, ${e[r]})`);
return s.join();
}
function R2(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { reps: a } = s;
if (r.dtype === "string" || r.shape.length > 5) {
let u = n.readSync(r.dataId), l = r.dtype === "string" ? u.map((d) => w.decodeString(d)) : u, c = Ae(r.shape, r.dtype, l), p = XX(c, a);
return n.makeTensorInfo(p.shape, p.dtype, p.values);
}
let o = new Tte(r.shape, a);
return n.runWebGLProgram(o, [r], r.dtype);
}
var _te = { kernelName: Tr, backendName: "webgl", kernelFunc: R2 };
var Ate = class {
constructor(e) {
this.variableNames = ["x", "indices"], this.customUniforms = [{ name: "n", type: "int" }, { name: "firstPass", type: "int" }, { name: "negativeInf", type: "float" }, { name: "dir", type: "int" }, { name: "inc", type: "int" }], this.outputShape = e, this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int elemIdx = coords[1];
// We compare elements pair-wise within a group of size 2 * inc.
// The comparing rule for each group alternates between ascending
// and descending. Within each group, we compare each pair at
// positions i and i+inc. To decide whether an element at position i
// is x0 or x1, we mod it by 2 * inc, if the result is smaller than
// inc, it is in the first half of the group, we denote it as x0,
// otherwise we denote it as x1.
// For example, as shown in the Bitonic top K paper referenced above,
// Figure5(a) shows that element[1] is in the
// second half of the group when group size is 2, but it is in the
// first half of the group when group size is 4.
bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;
int i = isFirstInPair ? elemIdx : elemIdx - inc;
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));
float x0 = i0 < n ? getX(batch, i0) : negativeInf;
float x1 = i1 < n ? getX(batch, i1) : negativeInf;
// Denotes which direction indices are in (ascending or descending).
bool reverse = imod(elemIdx, 2 * dir) >= dir;
bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
if (reverse == isGreater) { // Elements in opposite order of direction
int iTemp = i0;
i0 = i1;
i1 = iTemp;
}
if (isFirstInPair) {
setOutput(float(i0));
} else {
setOutput(float(i1));
}
}
`;
}
};
var Ete = class {
constructor(e) {
this.variableNames = ["x", "indices"], this.customUniforms = [{ name: "n", type: "int" }, { name: "firstPass", type: "int" }, { name: "k", type: "int" }], this.outputShape = e, this.userCode = `
void main() {
// Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...
ivec2 coords = getOutputCoords();
int batch = coords[0];
int elemIdx = coords[1];
// The output size is half of the previous size.
// If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),
// we only need to output the indices at positions |, the indices at
// positions _ can be thrown away, see Figure5(b) After Phase 2
// (Merge phase) in the Bitonic Top K paper referenced above.
// For example, the paper shows we only need to output the orange bars.
// The output sequence should look like this | | | | | | | |.
// Because the sequence is halved, to map the output index back
// to the previous sequence to find the corresponding value,
// we need to double the index. When we double the index,
// we basically interpolate a position, so 2i looks like
// | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position
// of each 2k positions by - elemIdx % k. E.g. for output at
// index 4,5,6,7, we want to get the corresponding element at
// original index 8,9,10,11, for output at index 8,9,10,11,
// we want to get the corresponding element at original index
// 16,17,18,19, so on and so forth.
int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));
float x0 = getX(batch, i0);
float x1 = i1 < n ? getX(batch, i1) : x0;
setOutput(x0 >= x1 ? float(i0) : float(i1));
}
`;
}
};
function Hr(e, t) {
t !== null && e.disposeIntermediateTensorInfo(t);
}
function Pw(e) {
let t = 1;
for (; t < e; )
t *= 2;
return t;
}
function Rte(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { k: a, sorted: o } = s, i = K().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"), u = K().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"), l = r.shape, c = l[l.length - 1];
if (n.shouldExecuteOnCPU([r]) || c < i || a > u) {
let P = n.readSync(r.dataId), [A, D] = YX(P, l, r.dtype, a, o);
return [n.makeTensorInfo(A.shape, A.dtype, A.values), n.makeTensorInfo(D.shape, D.dtype, D.values)];
}
if (a === 0)
return l[l.length - 1] = 0, [n.makeTensorInfo(l, r.dtype, []), n.makeTensorInfo(l, "int32", [])];
if (c === 1)
return [r, sc({ attrs: { shape: l, dtype: "int32", value: 0 }, backend: n })];
let p = n.texData.get(r.dataId), d = p !== null && p.isPacked, h = d ? n.unpackTensor(r) : r, m = w.sizeFromShape(l) / c, g = pe({ inputs: { x: h }, attrs: { shape: [m, c] }, backend: n });
d && Hr(n, h);
let b = Pw(a), y = Pw(c), v = null, x = () => v === null ? [g, g] : [g, v], k = (P, A, D) => {
let T = x(), L = new Ate(D), j = [[c], [v === null ? 1 : 0], [Number.NEGATIVE_INFINITY], [P], [A]], Y = v;
v = n.runWebGLProgram(L, T, "int32", j), Hr(n, Y);
};
for (let P = 1; P < b; P *= 2) {
let A = P * 2;
for (let D = P; D >= 1; D /= 2)
k(A, D, [m, y]);
}
for (let P = y; P > b; P /= 2) {
let A = x(), D = new Ete([m, P / 2]), L = [[c], [v === null ? 1 : 0], [b]], W = v;
v = n.runWebGLProgram(D, A, "int32", L), Hr(n, W);
let j = b / 2, Y = j * 2;
for (let X = j; X >= 1; X /= 2)
k(Y, X, v.shape);
}
let I = v;
v = pu({ inputs: { x: v }, backend: n, attrs: { begin: 0, size: [m, a] } }), Hr(n, I);
let $ = S2({ inputs: { x: g, indices: v }, backend: n, attrs: { axis: 1, batchDims: 1 } });
Hr(n, g);
let R = l.slice(0, -1);
R.push(a), I = v, v = pe({ inputs: { x: v }, attrs: { shape: R }, backend: n }), Hr(n, I);
let E = $;
return $ = pe({ inputs: { x: $ }, attrs: { shape: R }, backend: n }), Hr(n, E), [$, v];
}
var Dte = { kernelName: qi, backendName: "webgl", kernelFunc: Rte };
var Fte = class {
constructor(e, t, n, s, r, a) {
this.variableNames = ["Image", "Transforms"], this.outputShape = a;
let o = n === "nearest" ? 1 : 2, i;
switch (s) {
case "constant":
i = 1;
break;
case "reflect":
i = 2;
break;
case "wrap":
i = 3;
break;
case "nearest":
i = 4;
break;
default:
i = 1;
break;
}
this.userCode = `
float mapCoord(float outCoord, float len) {
float inCoord = outCoord;
if(${i} == 2) {
if (inCoord < 0.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz2 = 2.0 * len;
if (inCoord < sz2) {
inCoord = sz2 * float(int(float(-inCoord / sz2))) +
inCoord;
}
inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
}
} else if (inCoord > len - 1.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz2 = 2.0 * len;
inCoord -= sz2 * float(int(float(inCoord / sz2)));
if (inCoord >= len) {
inCoord = sz2 - inCoord - 1.0;
}
}
}
return clamp(inCoord, 0.0, len - 1.0);
} else if (${i} == 3) {
if (inCoord < 0.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz = len - 1.0;
inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
}
} else if (inCoord > len - 1.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz = len - 1.0;
inCoord -= len * float(int(float(inCoord / sz)));
}
}
return clamp(inCoord, 0.0, len - 1.0);
} else if (${i} == 4) {
return clamp(outCoord, 0.0, len - 1.0);
} else {
return outCoord;
}
}
float readWithFillValue(int batch, int coordY, int coordX,
int channel) {
float outputValue;
if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {
outputValue = getImage(batch, coordY, coordX, channel);
} else {
outputValue = float(${r});
}
return outputValue;
}
void main() {
ivec4 coords = getOutputCoords();
float outputValue;
int batch = coords[0];
int x = coords[2];
int y = coords[1];
int channel = coords[3];
float xf = float(x);
float yf = float(y);
float a1 = getTransforms(batch, 0);
float a2 = getTransforms(batch, 1);
float a3 = getTransforms(batch, 2);
float b1 = getTransforms(batch, 3);
float b2 = getTransforms(batch, 4);
float b3 = getTransforms(batch, 5);
float c1 = getTransforms(batch, 6);
float c2 = getTransforms(batch, 7);
float projection = c1 * xf + c2 * yf + 1.0;
if (projection == 0.0) {
outputValue = float(${r});
} else {
float inX = (a1 * xf + a2 * yf + a3) / projection;
float inY = (b1 * xf + b2 * yf + b3) / projection;
float mapX = mapCoord(inX, float(${t}));
float mapY = mapCoord(inY, float(${e}));
if (${o} == 1) {
int coordY = int(round(mapY));
int coordX = int(round(mapX));
outputValue = readWithFillValue(batch, coordY, coordX,
channel);
} else {
float yFloor = floor(mapY);
float xFloor = floor(mapX);
float yCeil = yFloor + 1.0;
float xCeil = xFloor + 1.0;
float valueYFloor = (xCeil - mapX) *
readWithFillValue(batch, int(yFloor), int(xFloor), channel) +
(mapX - xFloor) *
readWithFillValue(batch, int(yFloor), int(xCeil), channel);
float valueYCeil = (xCeil - mapX) *
readWithFillValue(batch, int(yCeil), int(xFloor), channel) +
(mapX - xFloor) *
readWithFillValue(batch, int(yCeil), int(xCeil), channel);
outputValue = (yCeil - mapY) * valueYFloor +
(mapY - yFloor) * valueYCeil;
}
}
setOutput(outputValue);
}
`;
}
};
function Ote(e) {
let { inputs: t, backend: n, attrs: s } = e, { image: r, transforms: a } = t, { interpolation: o, fillMode: i, fillValue: u, outputShape: l } = s, [c, p, d, h] = r.shape, [f, m] = l != null ? l : [p, d], g = [c, f, m, h], b = new Fte(p, d, o, i, u, g);
return n.runWebGLProgram(b, [r, a], "float32");
}
var Pte = { kernelName: ji, backendName: "webgl", kernelFunc: Ote };
function zte(e) {
let { inputs: t, attrs: n, backend: s } = e, { axis: r } = n, { x: a } = t;
ou(a, "unique"), console.warn("WARNING: ", "UI might be locked temporarily as data is being downloaded");
let o = s.readSync(a.dataId), { outputValues: i, outputShape: u, indices: l } = QX(o, r, a.shape, a.dtype);
return [s.makeTensorInfo(u, a.dtype, i), s.makeTensorInfo([l.length], "int32", l)];
}
var Lte = { kernelName: Wg, backendName: "webgl", kernelFunc: zte };
function Mte(e) {
let { inputs: t, backend: n, attrs: s } = e, { value: r } = t, { axis: a } = s;
a < 0 && (a += r.shape.length);
let o = r, i = o.shape.length, u = r.shape[a], l = new Array(i - 1), c = 0;
for (let m = 0; m < i; m++)
m !== a && (l[c++] = o.shape[m]);
let p = [], d = new Array(i).fill(0), h = o.shape.slice();
h[a] = 1;
let f = new Array(u);
for (let m = 0; m < f.length; m++) {
d[a] = m;
let g = pu({ inputs: { x: o }, backend: n, attrs: { begin: d, size: h } }), b = pe({ inputs: { x: g }, backend: n, attrs: { shape: l } });
f[m] = b, p.push(g);
}
return p.forEach((m) => n.disposeIntermediateTensorInfo(m)), f;
}
var Bte = { kernelName: Ki, backendName: "webgl", kernelFunc: Mte };
var Vte = class {
constructor(e, t) {
this.variableNames = ["x", "segmentIds"];
let n = e.windowSize, s = e.batchSize, r = e.inSize, a = e.numSegments, o = a * Math.ceil(r / n);
this.outputShape = [s, o];
let i = "0.0", u = "sumValue", l = Math.floor(n / 4) * 4, c = n % 4, p = `
sumValue += dot(values, segFilter);
`, d = "";
r % n > 0 && (d = `
if (inIdx < 0 || inIdx >= ${r}) {
return initializationValue;
}
`);
let h = "";
r % n > 0 && (h = `
if (inIdx < 0 || inIdx >= ${r}) {
return -1.0;
}
`), this.userCode = `
const float initializationValue = ${i};
float getValue(int batch, int inIdx) {
${d}
return getX(batch, inIdx);
}
float getSegmentIdAtIndex(int inIdx) {
${h}
return getSegmentIds(inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
${a})) * float(${n}));
int currentSeg = int(mod(float(outIdx), float(${a})));
float sumValue = 0.0;
for (int i = 0; i < ${l}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
);
${p}
}
int inIdx = inOffset + ${l};
if (${c === 1}) {
vec4 values = vec4(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
0,
0,
0
);
${p}
} else if (${c === 2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
0,
0
);
${p}
} else if (${c === 3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
0
);
${p}
}
setOutput(${u});
}
`;
}
};
function Wte(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, segmentIds: a } = t, { numSegments: o } = s, i = r.shape.length, u = [], l = 0, c = C.getAxesPermutation([l], i), p = r;
c != null && (p = pn({ inputs: { x: r }, backend: n, attrs: { perm: c } }), u.push(p), l = C.getInnerMostAxes(1, i)[0]);
let d = C.segment_util.computeOutShape(p.shape, l, o), h = w.sizeFromShape([p.shape[l]]), f = pe({ inputs: { x: p }, backend: n, attrs: { shape: [-1, h] } });
u.push(f);
let m = yp(r.dtype), g = (x, k, I, $, R) => {
let E = x.shape[0], P = x.shape[1], A = C.segment_util.segOpComputeOptimalWindowSize(P, R), D = { windowSize: A, inSize: P, batchSize: E, numSegments: R }, T = new Vte(D, k), L = n.compileAndRun(T, [x, I], $);
if (u.push(L), L.shape[1] === R)
return L;
let W = A2({ backend: n, attrs: { start: 0, stop: R, step: 1, dtype: "float32" } }), j = R2({ inputs: { x: W }, backend: n, attrs: { reps: [P / A] } });
return u.push(W), u.push(j), g(L, k, j, $, R);
}, b = g(f, "unsortedSegmentSum", a, m, o), y = pe({ inputs: { x: b }, backend: n, attrs: { shape: d } }), v = y;
if (c != null) {
u.push(y);
let x = C.getUndoAxesPermutation(c);
v = pn({ inputs: { x: v }, backend: n, attrs: { perm: x } });
}
return u.forEach((x) => n.disposeIntermediateTensorInfo(x)), v;
}
var Ute = { kernelName: gp, backendName: "webgl", kernelFunc: Wte };
var Gte = [H8, j8, Y8, J8, tY, rY, oY, uY, pY, fY, bY, xY, SY, TY, AY, RY, FY, LY, BY, WY, qY, JY, t9, s9, l9, d9, m9, N8, y9, S9, T9, D9, O9, z9, M9, V9, G9, j9, Y9, Z9, eQ, nQ, aQ, iQ, dQ, hQ, gQ, vQ, wQ, CQ, _Q, DQ, PQ, MQ, BQ, WQ, GQ, qQ, KQ, YQ, eZ, sZ, oZ, uZ, dZ, fZ, yZ, kZ, C8, IZ, w9, TZ, AZ, DZ, $8, zZ, VZ, UZ, jZ, YZ, e7, s7, i7, d7, f7, g7, x7, k7, I7, $7, A7, R7, F7, P7, B7, G7, K7, nJ, D8, oJ, lJ, pJ, mJ, a9, yJ, xJ, kJ, CJ, _J, A8, EJ, RJ, o9, Z7, OJ, MJ, UJ, O8, jJ, YJ, eee, see, iee, lee, pee, mee, bee, xee, See, Nee, Aee, Dee, Pee, Mee, QY, eJ, Wee, Gee, qee, Kee, Yee, Zee, ete, nte, rte, ite, lte, dte, fte, gte, yte, xte, J7, W8, Ste, Nte, _te, Dte, Pte, U8, Lte, Bte, Ute, vJ];
for (let e of Gte)
Ol(e);
var Or = K();
Or.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE", () => 15);
Or.registerFlag("WEBGPU_CPU_FORWARD", () => true);
Or.registerFlag("WEBGPU_MATMUL_WORK_PER_THREAD", () => 4);
Or.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE", () => false);
Or.registerFlag("WEBGPU_USE_LOW_POWER_GPU", () => false);
Or.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD", () => 1e3);
Or.registerFlag("WEBGPU_USE_PROFILE_TOOL", () => false);
Or.registerFlag("WEBGPU_USE_IMPORT", () => false);
var Hte = "return a + b;";
var qte = "return areal * breal - aimag * bimag;";
var jte = "return areal * bimag + aimag * breal;";
var Kte = "return a / b;";
var Xte = "return a * b;";
var Yte = "return (a - b) * (a - b);";
var Qte = "return a - b;";
var Zte = "return f32(a == b);";
var Jte = "return vec4<f32>(a == b);";
var ene = "return f32(a > b);";
var tne = "return vec4<f32>(a > b);";
var nne = "return f32(a >= b);";
var sne = "return vec4<f32>(a >= b);";
var rne = "return f32(a < b);";
var ane = "return vec4<f32>(a < b);";
var one = "return f32(a <= b);";
var ine = "return vec4<f32>(a <= b);";
var une = "return f32(f32(a) >= 1.0 && f32(b) >= 1.0);";
var lne = `return (vec4<f32>(a >= vec4<f32>(1.0)) *
vec4<f32>(b >= vec4<f32>(1.0)));`;
var cne = `
if (isnan(a)) { return a; }
if (isnan(b)) { return b; }
`;
var D2 = `
if (isNaN.r) {
resultTemp.r = uniforms.NAN;
}
if (isNaN.g) {
resultTemp.g = uniforms.NAN;
}
if (isNaN.b) {
resultTemp.b = uniforms.NAN;
}
if (isNaN.a) {
resultTemp.a = uniforms.NAN;
}
`;
var dne = `
let s = sign(a) * sign(b);
let ia = i32(round(a));
let ib = i32(round(b));
return f32(idiv(ia, ib, s));
`;
var pne = `
let ia = vec4<i32>(round(a));
let ib = vec4<i32>(round(b));
let cond = ib != vec4<i32>(0);
var resultTemp = vec4<i32>(0);
let s = sign(a) * sign(b);
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if (cond[0]) {
resultTemp[0] = idiv(ia[0], ib[0], s[0]);
}
if (cond[1]) {
resultTemp[1] = idiv(ia[1], ib[1], s[1]);
}
if (cond[2]) {
resultTemp[2] = idiv(ia[2], ib[2], s[2]);
}
if (cond[3]) {
resultTemp[3] = idiv(ia[3], ib[3], s[3]);
}
return vec4<f32>(resultTemp);
`;
var hne = "return f32(a != b);";
var fne = "return vec4<f32>(a != b);";
var mne = `
if(a < 0.0 && floor(b) < b) {
return uniforms.NAN;
}
if (b == 0.0) {
return 1.0;
}
if (round(abs(b) % 2.0) != 1.0) {
return pow(abs(a), b);
}
return sign(a) * pow(abs(a), b);
`;
var gne = `
let isModRound1Bool = vec4<i32>(round(abs(b) % vec4<f32>(2.0))) == vec4<i32>(1);
let isModRound1 = vec4<f32>(isModRound1Bool);
let multiplier = sign(a) * isModRound1 + (vec4<f32>(1.0) - isModRound1);
var resultTemp = multiplier * pow(abs(a), b);
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
let isExpZero = b == vec4<f32>(0.0);
if (isExpZero.r) {
resultTemp.r = 1.0;
}
if (isExpZero.g) {
resultTemp.g = 1.0;
}
if (isExpZero.b) {
resultTemp.b = 1.0;
}
if (isExpZero.a) {
resultTemp.a = 1.0;
}
let isNaN = a < vec4<f32>(0.0) & floor(b) < b;
${D2}
return resultTemp;
`;
var bne = "if (a < 0.0) { return b * a; } return a;";
var yne = `
let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
return (aLessThanZero * (b * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
`;
function zw(e, t) {
let n = t ? D2 : cne;
return t ? `
var resultTemp = vec4<f32>(${e}(a, b));
let isNaN = isnanVec4(a) | isnanVec4(b);
` + n + `
return resultTemp;
` : n + `
return ${e}(a, b);
`;
}
function rc(e, t) {
switch (e) {
case 0:
return Xte;
case 1:
return Hte;
case 2:
return Qte;
case 3:
return Kte;
case 4:
return t ? Jte : Zte;
case 5:
return t ? tne : ene;
case 6:
return t ? sne : nne;
case 7:
return t ? ane : rne;
case 8:
return t ? ine : one;
case 9:
return t ? lne : une;
case 10:
return t ? fne : hne;
case 11:
return Yte;
case 12:
return t ? pne : dne;
case 14:
return t ? yne : bne;
case 15:
return zw("max", t);
case 16:
return zw("min", t);
case 13:
return t ? gne : mne;
case 17:
return qte;
case 18:
return jte;
default:
throw new Error(`BinaryType ${e} is not implemented!`);
}
}
var vne = "return abs(a);";
var xne = "return ceil(a);";
var wne = "return cos(a);";
var kne = `
let e2x = exp(-a);
return (e2x + 1.0 / e2x) / 2.0;
`;
var Sne = "return exp(a) - 1.0;";
var Ine = "if (a >= 0.0) { return a; } return (exp(a) - 1.0);";
var Cne = `
var resFloat = exp(a) - vec4<f32>(1.0);
if (a.r >= 0.0) {
resFloat.r = a.r;
}
if (a.g >= 0.0) {
resFloat.g = a.g;
}
if (a.b >= 0.0) {
resFloat.b = a.b;
}
if (a.a >= 0.0) {
resFloat.a = a.a;
}
return resFloat;
`;
var Nne = "return exp(a);";
var Tne = "return floor(a);";
var $ne = "return a;";
var _ne = `if (a < 0.0) { return 1.0/0.0; }
return log(a);`;
var Ane = "return f32(!(a >= 1.0));";
var Ene = "return -a;";
var Rne = "if (a < 0.0) { return uniforms.alpha * a; } return a;";
var Dne = `
let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
return (aLessThanZero * (uniforms.alpha * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
`;
var Fne = "return select(a, 0.0, a < 0.0);";
var One = "return clamp(a, 0.0, 6.0);";
var Pne = "return clamp(a, vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<f32>(6.0, 6.0, 6.0, 6.0));";
var zne = `
return select(a, vec4<f32>(0.0), a < vec4<f32>(0.0));
`;
var Lne = "return 1.0/sqrt(a);";
var Mne = "return 1.0 / (1.0 + exp(-1.0 * a));";
var Bne = "return sin(a);";
var Vne = `
let e2x = exp(a);
return (e2x - 1.0 / e2x) / 2.0;
`;
var Wne = "return sqrt(a);";
var Une = "return a * a;";
var Gne = `
let e2x = exp(-2.0 * abs(a));
return sign(a) * (1.0 - e2x) / (1.0 + e2x);
`;
var Hne = "return f32(i32((a)));";
function jr(e, t) {
switch (e) {
case 0:
return vne;
case 2:
return wne;
case 3:
return kne;
case 1:
return xne;
case 4:
return t ? Cne : Ine;
case 5:
return Nne;
case 6:
return Sne;
case 7:
return Tne;
case 8:
return $ne;
case 9:
return _ne;
case 10:
return Ane;
case 11:
return Ene;
case 14:
return t ? Dne : Rne;
case 12:
return t ? zne : Fne;
case 13:
return t ? Pne : One;
case 15:
return Lne;
case 18:
return Mne;
case 16:
return Bne;
case 17:
return Vne;
case 19:
return Wne;
case 20:
return Une;
case 21:
return Gne;
case 22:
return Hne;
default:
throw new Error(`BinaryType ${e} is not implemented!`);
}
}
function Io(e, t = false) {
if (e === null)
return null;
if (e === "linear")
return jr(8);
if (e === "relu")
return jr(12, t);
if (e === "elu")
return jr(4, t);
if (e === "relu6")
return jr(13, t);
if (e === "prelu")
return rc(14, t);
if (e === "sigmoid")
return jr(18, t);
if (e === "leakyrelu")
return jr(14, t);
throw new Error(`Activation ${e} has not been implemented for the WebGPU backend.`);
}
var F2 = {};
Ee(F2, { ArrayBufferToTypedArray: () => P2, GPUBytesPerElement: () => md, computeDispatch: () => _e, computeWorkGroupSizeForConv2d: () => Ov, computeWorkGroupSizeForMatMul: () => O2, computeWorkPerThreadForConv2d: () => Pv, flatDispatchLayout: () => Ve, isWebGPUSupported: () => zv, tilesFitEvenlyIntoShape: () => qne });
var ra = (e) => {
let t = 1;
for (let n = 0; n < e.length; n++)
t *= e[n];
return t;
};
function qne(e, t) {
if (e.length !== t.length)
throw new Error(`Cannot compute whether rank ${e.length} tiles fit evenly into rank ${t.length} shape - ranks must match.`);
return t.every((n, s) => n % e[s] === 0);
}
function _e(e, t, n = [1, 1, 1], s = [1, 1, 1]) {
let [r, a, o] = [Math.ceil(ra(e.x.map((i) => t[i])) / (n[0] * s[0])), e.y ? Math.ceil(ra(e.y.map((i) => t[i])) / (n[1] * s[1])) : 1, e.z ? Math.ceil(ra(e.z.map((i) => t[i])) / (n[2] * s[2])) : 1];
return [r, a, o];
}
function Ov(e, t, n = false) {
if (n)
return [8, 8, 1];
let s = ra(e.x.map((a) => t[a])), r = ra(e.y.map((a) => t[a]));
return s <= 4 ? [4, 16, 1] : r <= 4 ? [16, 4, 1] : [16, 16, 1];
}
function O2(e, t, n) {
return e === 1 ? [32, 1, 1] : n === 1 ? [1, 32, 1] : [8, 8, 1];
}
function Pv(e, t, n = false) {
if (n)
return [4, 4, 1];
let s = ra(e.x.map((a) => t[a])), r = ra(e.y.map((a) => t[a]));
return s <= 4 ? [1, 2, 1] : r <= 4 ? [2, 1, 1] : [2, 2, 1];
}
function Ve(e) {
return { x: e.map((t, n) => n) };
}
function md(e) {
if (e === "float32" || e === "int32" || e === "bool" || e === "string")
return 4;
if (e === "complex64")
return 8;
throw new Error(`Unknown dtype ${e}`);
}
function P2(e, t) {
if (t === "float32")
return new Float32Array(e);
if (t === "int32")
return new Int32Array(e);
if (t === "bool" || t === "string")
return Uint8Array.from(new Int32Array(e));
throw new Error(`Unknown dtype ${t}`);
}
function zv() {
return (typeof window != "undefined" || typeof WorkerGlobalScope != "undefined") && !!navigator.gpu;
}
var jne = (e, t) => e ? `
mm_Asub[inputRow][inputCol] = mm_readA(
t * TileInner + inputRow,
globalRowStart / ${t} + inputCol, globalId);
` : `
mm_Asub[inputRow][inputCol] = mm_readA(
globalRow + innerRow,
t * TileInner / ${t} + inputCol, globalId);
`;
var Kne = (e, t) => e ? `
let ACached0 = mm_Asub[k * InnerElementSize][localRow];
let ACached1 = mm_Asub[k * InnerElementSize + 1][localRow];
let ACached2 = mm_Asub[k * InnerElementSize + 2][localRow];
${t === 3 ? "" : "let ACached3 = mm_Asub[k * InnerElementSize + 3][localRow];"}
for (var i = 0; i < RowPerThread; i = i + 1) {
acc[i] = BCached[0] * ACached0[i] + acc[i];
acc[i] = BCached[1] * ACached1[i] + acc[i];
acc[i] = BCached[2] * ACached2[i] + acc[i];
${t === 3 ? "" : "acc[i] = BCached[3] * ACached3[i] + acc[i];"}
}` : `
for (var i = 0; i < RowPerThread; i = i + 1) {
let ACached = mm_Asub[tileRow + i][k];
acc[i] = BCached[0] * ACached.x + acc[i];
acc[i] = BCached[1] * ACached.y + acc[i];
acc[i] = BCached[2] * ACached.z + acc[i];
${t === 3 ? "" : "acc[i] = BCached[3] * ACached.w + acc[i];"}
}`;
function z2(e, t, n, s, r = 4, a = false) {
let o = a ? t : s, i = a ? s : t, u = a ? e[1] : r;
return w.assert((a && t === n || s % 4 === 0 || s % 3 === 0) && e[0] === 4 && (r === 3 || r === 4), () => `tileInner ${s} must be divisible by 4|3. ColPerThread ${e[0]} must be 4.
innerElementSize ${r} must be 3|4.`), `
var<workgroup> mm_Asub : array<array<vec${u}<f32>, ${o / u}>, ${i}>;
var<workgroup> mm_Bsub : array<array<vec4<f32>, ${n / e[0]}>, ${s}>;
let RowPerThread = ${e[1]};
let ColPerThread = ${e[0]};
let InnerElementSize = ${r};
let TileInner = ${s};
@stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)
fn main(@builtin(local_invocation_id) LocalId : vec3<u32>,
@builtin(global_invocation_id) GlobalId : vec3<u32>,
@builtin(num_workgroups) NumWorkgroups: vec3<u32>,
@builtin(workgroup_id) workgroupId: vec3<u32>) {
localId = LocalId;
globalId = GlobalId;
numWorkgroups = NumWorkgroups;
let localRow = i32(localId.y);
let tileRow = ${t === 1 ? "0" : "localRow * RowPerThread"};
let tileCol = i32(localId.x);
let globalRow = ${t === 1 ? "0" : "i32(globalId.y) * RowPerThread"};
let globalCol = i32(globalId.x);
let globalRowStart = i32(workgroupId.y) * ${t};
let numTiles = (uniforms.dimInner - 1) / TileInner + 1;
var acc: array<vec4<f32>, RowPerThread>;
var BCached : array<vec4<f32>, 4>;
// Loop over shared dimension.
let RowPerThreadB = TileInner / i32(workGroupSizeY);
let tileRowB = localRow * RowPerThreadB;
for (var t = 0; t < numTiles; t = t + 1) {
// Load one tile of A into local memory.
for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) {
let inputRow = tileRow + innerRow;
let inputCol = tileCol;
${jne(a, u)}
}
// Load one tile of B into local memory.
for (var innerRow = 0; innerRow < RowPerThreadB; innerRow = innerRow + 1) {
let inputRow = tileRowB + innerRow;
let inputCol = tileCol;
mm_Bsub[inputRow][inputCol] = mm_readB(t * TileInner + inputRow, globalCol, globalId);
}
workgroupBarrier();
// Compute acc values for a single thread.
for (var k = 0; k < TileInner / InnerElementSize; k = k + 1) {
BCached[0] = mm_Bsub[k * InnerElementSize][tileCol];
BCached[1] = mm_Bsub[k * InnerElementSize + 1][tileCol];
BCached[2] = mm_Bsub[k * InnerElementSize + 2][tileCol];
${r === 3 ? "" : "BCached[3] = mm_Bsub[k * InnerElementSize + 3][tileCol];"}
${Kne(a, r)}
}
workgroupBarrier();
}
for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) {
mm_write(globalRow + innerRow,
globalCol,
acc[innerRow], globalId);
}
}`;
}
var Xne = class {
constructor(e, t, n, s, r = false, a = null, o = null, i = null) {
this.variableNames = ["A", "B"], this.uniforms = "dimAOuter : i32, dimBOuter : i32, dimInner : i32,", this.workGroupSize = [8, 8, 1], this.isVec4 = true, this.outputShape = t, this.dispatchLayout = { x: [2], y: [1], z: [0] }, t[1] === 1 && !r ? this.elementsPerThread = [4, 1, 1] : this.elementsPerThread = [4, 4, 1], this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize, this.elementsPerThread);
let u = a != null, l = i != null;
u && this.variableNames.push("bias"), l && this.variableNames.push("preluActivationWeights"), this.tileAOuter = t[1] === 1 && !r ? 1 : this.workGroupSize[1] * this.elementsPerThread[1], this.tileBOuter = this.workGroupSize[0] * this.elementsPerThread[0], this.tileInner = this.tileBOuter, this.aShape = e, this.addBias = u, this.activation = o, this.hasPreluActivationWeights = l, this.batchAEqualOne = n, this.batchBEqualOne = s, this.transposeA = r;
let c = r ? e[1] : e[2];
this.fitAOuter = t[1] % this.tileAOuter === 0, this.fitBOuter = t[2] % this.tileBOuter === 0, this.fitInner = c % this.tileInner === 0, this.shaderKey = `matMulPackedVec4_${this.activation}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.elementsPerThread}_${this.batchAEqualOne}_${this.batchBEqualOne}_${this.transposeA}`;
}
getUserCode() {
let e = this.fitAOuter && this.fitInner ? "return A[batch * batchASize + row * uniforms.aShape[2] / 4 + col]" : `if (coordsInBounds2D(vec2<i32>(row, col * 4), vec2<i32>(uniforms.aShape[1], uniforms.aShape[2]))) {
return A[batch * batchASize + row * uniforms.aShape[2] / 4 + col];
}
return vec4<f32>(0.0)`, t = this.fitInner && this.fitBOuter ? "return B[batch * batchBSize + row * uniforms.dimBOuter / 4 + col]" : `if(coordsInBounds2D(vec2<i32>(row, col * 4), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
return B[batch * batchBSize + row * uniforms.dimBOuter / 4 + col];
}
return vec4<f32>(0.0)`, n = "", s = "";
if (this.activation) {
let o = Io(this.activation, this.isVec4);
this.hasPreluActivationWeights ? n = `fn activation(a : vec4<f32>, outCoord : vec3<i32>) -> vec4<f32> {
let b = getPreluActivationWeightsByOutputCoords(outCoord);
${o}
}` : n = `
fn activation(a : vec4<f32>, outCoord : vec3<i32>) -> vec4<f32> {
${o}
}`, s = "value = activation(value, outCoord);";
}
let r = this.addBias ? "value = value + getBiasByOutputCoords(outCoord);" : "";
return `
${n}
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> vec4<f32> {
${this.batchAEqualOne ? `
let batchASize = 0;
let batch = 0;
` : `
let batchASize = uniforms.aShape[1] * uniforms.aShape[2] / 4;
let batch = i32(globalId.z);
`}
${e};
}
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> vec4<f32> {
${this.batchBEqualOne ? `
let batchBSize = 0;
let batch = 0;
` : `
let batchBSize = uniforms.bShape[1] * uniforms.bShape[2] / 4;
let batch = i32(globalId.z);
`}
${t};
}
fn mm_write(row : i32, col : i32, valueIn : vec4<f32>, globalId : vec3<u32>) {
if (row < uniforms.dimAOuter && col * 4 < uniforms.dimBOuter)
{
var value = valueIn;
let batch = i32(globalId.z);
let outCoord = vec3<i32>(batch, row, col * 4);
${r}
${s}
setOutputAtCoords(outCoord[0], outCoord[1], outCoord[2], value);
}
}
${z2(this.elementsPerThread, this.tileAOuter, this.tileBOuter, this.tileInner, 4, this.transposeA)}
`;
}
};
function Yne(e, t) {
if (Math.max(...e) > 3)
throw new Error("Cannot symbolically compute strides for rank > 4 tensor.");
let n = e.length, s = e.map((a) => `${t}[${a}]`), r = new Array(n - 1);
r[n - 2] = s[n - 1];
for (let a = n - 3; a >= 0; --a)
r[a] = `(${r[a + 1]} * ${s[a + 1]})`;
return r;
}
var Lw = (e, t, n, s, r, a = false) => {
let o = { dtype: r.dtype, shape: r.shape }, i = Qne(s, o, t, a), u = e.createShaderModule({ code: i, label: t.constructor.name });
return e.createComputePipeline({ layout: n, compute: { module: u, entryPoint: "main" }, label: t.constructor.name });
};
function Wt(e) {
if (e <= 1)
return "i32";
if (e === 2)
return "vec2<i32>";
if (e === 3)
return "vec3<i32>";
if (e === 4)
return "vec4<i32>";
if (e === 5)
return "vec5";
if (e === 6)
return "vec6";
throw Error(`GPU for rank ${e} is not yet supported`);
}
function hr(e) {
if (e === 0)
return "x";
if (e === 1)
return "y";
if (e === 2)
return "z";
if (e === 3)
return "w";
if (e === 4)
return "u";
if (e === 5)
return "v";
throw Error(`Index ${e} is not yet supported`);
}
function Ue() {
return `
${ac()}
let index = getGlobalIndex();
`;
}
function ac() {
return `
${Lv()}
fn main(@builtin(local_invocation_id) LocalId : vec3<u32>,
@builtin(global_invocation_id) GlobalId : vec3<u32>,
@builtin(num_workgroups) NumWorkgroups: vec3<u32>) {
localId = LocalId;
globalId = GlobalId;
numWorkgroups = NumWorkgroups;
`;
}
function Lv() {
return `
@stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)
`;
}
function Qne(e, t, n, s = false) {
let r = [];
if (r.push(`
let workGroupSizeX = ${n.workGroupSize[0]}u;
let workGroupSizeY = ${n.workGroupSize[1]}u;
let workGroupSizeZ = ${n.workGroupSize[2]}u;
var<private> localId: vec3<u32>;
var<private> globalId: vec3<u32>;
var<private> numWorkgroups: vec3<u32>;
// Only used when the y/z dimension of workgroup size is 1.
fn getGlobalIndex() -> i32 {
${L2(n) ? " return i32(globalId.x);" : ` let localInvocationIndex = localId.z * workGroupSizeX * workGroupSizeY +
localId.y * workGroupSizeX + localId.x;
let workGroupID = (globalId - localId)/vec3<u32>(
workGroupSizeX, workGroupSizeY, workGroupSizeZ);
return i32((workGroupID.z * numWorkgroups.x * numWorkgroups.y +
workGroupID.y * numWorkgroups.x + workGroupID.x) *
(workGroupSizeX * workGroupSizeY * workGroupSizeZ) +
localInvocationIndex);
`}
}
`), s === true)
return r.push(`
struct Uniform {
size : i32,
numChannels : i32,
outShapeStrides : vec2<i32>,
dispatchSize : vec3<u32>,
};
@group(0) @binding(0) var<storage, write> result: array<${gd(t.dtype, n.isVec4)}>;
@group(0) @binding(2) var<uniform> uniforms: Uniform;
`), [Bw, r.join(`
`), Vw(t.shape), n.getUserCode()].join(`
`);
let a = false, o = false, i = "struct Uniforms { NAN : f32, ";
n.variableNames.forEach((m, g) => {
let b = Wt(e[g].shape.length);
(b === "vec5" || b === "vec6") && (o = true), (a || o) && (i += "@align(16) "), a = o, i += `${m.charAt(0).toLowerCase() + m.slice(1)}Shape : ${b}, `;
});
let u = Wt(t.shape.length);
o = u === "vec5" || u === "vec6", (a || o) && (i += "@align(16) "), a = o, i += `outShape : ${u}, `;
let l = t.shape.length - 1, c = Wt(l);
o = c === "vec5" || c === "vec6", (a || o) && (i += "@align(16) "), a = o, i += `
outShapeStrides: ${c}, `, n.size && (a && (i += "@align(16) "), a = false, i += "size : i32, "), n.uniforms && (a && (i += "@align(16) "), i += n.uniforms), i += "};", r.push(i), n.atomic ? r.push(`
@group(0) @binding(0) var<storage, read_write> result: array<atomic<i32>>;
`) : r.push(`
@group(0) @binding(0) var<storage, write> result: array<${gd(t.dtype, n.isVec4)}>;
`), n.variableNames.forEach((m, g) => {
r.push(`
@group(0) @binding(${1 + g}) var<storage, read> ${m}: array<${n.variableTypes ? n.variableTypes[g] : gd(e[g].dtype, n.isVec4)}>;
`);
}), i !== "" && r.push(`
@group(0) @binding(${1 + n.variableNames.length}) var<uniform> uniforms: Uniforms;
`);
let [p, d] = tse(t.shape, n.dispatchLayout), h = [Bw, r.join(`
`), Vw(t.shape), p, nse(t.shape.length)];
if (n.atomic || h.push(sse(t.shape, t.dtype, n.isVec4)), d === t.shape.length) {
let m = e.map((g, b) => ese(g, t.shape, n.variableTypes ? n.variableTypes[b] === "vec4<f32>" : n.isVec4, n.dispatchLayout.x.length === t.shape.length)).join(`
`);
h.push(m);
}
return h.push(n.getUserCode()), h.join(`
`);
}
function Mw(e, t, n = [], s = "", r = "") {
let a = L2(e) ? "flatDispatch" : "";
return e.shaderKey + "_" + (e.workGroupSize ? e.workGroupSize.join(",") : "") + t.map((i) => i.length).join(",") + n.join(",") + e.variableNames.join(",") + s + r + a;
}
var Bw = `
struct vec5 {x: i32, y: i32, z: i32, w: i32, u: i32};
struct vec6 {x: i32, y: i32, z: i32, w: i32, u: i32, v: i32};
// Checks whether coordinates lie within the bounds of the shape.
fn coordsInBounds2D(coord : vec2<i32>, shape : vec2<i32>) -> bool {
return all(coord >= vec2<i32>(0)) && all(coord < shape);
}
fn coordsInBounds3D(coord : vec3<i32>, shape : vec3<i32>) -> bool {
return all(coord >= vec3<i32>(0)) && all(coord < shape);
}
fn coordsInBounds4D(coord : vec4<i32>, shape : vec4<i32>) -> bool {
return all(coord >= vec4<i32>(0)) && all(coord < shape);
}
fn getIndexFromCoords1D(coord : i32, shape : i32) -> i32 {
return coord;
}
fn getIndexFromCoords2D(coords : vec2<i32>, shape : vec2<i32>) -> i32 {
return dot(coords, vec2<i32>(shape.y, 1));
}
fn getIndexFromCoords3D(coords : vec3<i32>, shape : vec3<i32>) -> i32 {
return dot(coords, vec3<i32>(shape.y * shape.z, shape.z, 1));
}
fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {
return dot(coords, vec4<i32>(
shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));
}
fn getIndexFromCoords5D(coords : vec5, shape : vec5) -> i32 {
let shapeStrides: vec5 = vec5(shape.y * shape.z * shape.w * shape.u, shape.z * shape.w * shape.u, shape.w * shape.u, shape.u, 1);
return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u;
}
fn getIndexFromCoords6D(coords : vec6, shape : vec6) -> i32 {
let shapeStrides: vec6 = vec6(shape.y * shape.z * shape.w * shape.u * shape.v, shape.z * shape.w * shape.u * shape.v, shape.w * shape.u * shape.v, shape.u * shape.v, shape.v, 1);
return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u + coords.v*shapeStrides.v;
}
fn idiv(a: i32, b: i32, sign: f32) -> i32 {
var res: i32 = a / b;
let mod: i32 = a % b;
if (sign < 0. && mod != 0) {
res = res - 1;
}
return res;
}
// NaN defination in IEEE 754-1985 is :
// - sign = either 0 or 1.
// - biased exponent = all 1 bits.
// - fraction = anything except all 0 bits (since all 0 bits represents infinity).
// https://en.wikipedia.org/wiki/IEEE_754-1985#Representation_of_non-numbers
fn isnan(val: f32) -> bool {
let floatToUint: u32 = bitcast<u32>(val);
return (floatToUint & 0x7fffffffu) > 0x7f800000u;
}
fn isnanVec4(val : vec4<f32>) -> vec4<bool> {
return vec4<bool>(isnan(val[0]), isnan(val[1]), isnan(val[2]), isnan(val[3]));
}
`;
function Vw(e) {
let t = e.length;
if (t <= 1)
return "fn getCoordsFromIndex(index : i32) -> i32 { return index; }";
let n = w.computeStrides(e), s = Wt(t), r = [];
for (let o = 0; o < t; o++)
r.push(`d${o}`);
if (n.length === 1)
return ` fn getCoordsFromIndex(index : i32) -> vec2<i32> {
let d0 = index / uniforms.outShapeStrides; let d1 = index - d0 * uniforms.outShapeStrides;
return vec2<i32>(d0, d1);
}`;
let a;
return a = "var index2 = index;" + n.map((o, i) => {
let u = `let ${r[i]} = index2 / uniforms.outShapeStrides.${hr(i)}`, l = i === n.length - 1 ? `let ${r[i + 1]} = index2 - ${r[i]} * uniforms.outShapeStrides.${hr(i)}` : `index2 = index2 - ${r[i]} * uniforms.outShapeStrides.${hr(i)}`;
return `${u}; ${l};`;
}).join(""), `
fn getCoordsFromIndex(index : i32) -> ${s} {
${a}
return ${s}(${r.join(",")});
}
`;
}
function Zne(e, t) {
let n = e.name, s = e.shape.length, r = Wt(s), a = "get" + n.charAt(0).toUpperCase() + n.slice(1), o = ["d0", "d1", "d2", "d3", "d4", "d5"].slice(0, s), i = o.map((c) => `${c} : i32`).join(", ");
if (s < 1)
return t ? `
fn ${a}() -> vec4<f32> {
return vec4<f32>(${n}[0]);
}
` : `
fn ${a}() ->f32 {
return f32(${n}[0]);
}
`;
let u = `uniforms.${n.charAt(0).toLowerCase() + n.slice(1)}Shape`, l = `${s}D`;
return s === 0 && (l = "1D"), t ? `
fn ${a}(${i}) -> vec4<f32> {
return vec4<f32>(${n}[getIndexFromCoords${l}(${r}(${o.join(",")}),
${u}) / 4]);
}
` : `
fn ${a}(${i}) -> f32 {
return f32(${n}[getIndexFromCoords${l}(${r}(${o.join(",")}),
${u})]);
}
`;
}
function Jne(e, t, n, s) {
let r = e.name, a = r.charAt(0).toUpperCase() + r.slice(1), o = "get" + a + "ByOutput", i = e.shape.length, u = t.length, l = Wt(u);
if (w.arraysEqual(e.shape, t) && s)
return n ? `
fn ${o}Index(globalIndex : i32) -> vec4<f32> {
return vec4<f32>(${r}[globalIndex]);
}
fn ${o}Coords(coords : ${l}) -> vec4<f32> {
return vec4<f32>(${r}[${u > 1 ? "getOutputIndexFromCoords(coords)" : "coords"} / 4]);
}
` : `
fn ${o}Index(globalIndex : i32) -> f32 {
return f32(${r}[globalIndex]);
}
fn ${o}Coords(coords : ${l}) -> f32 {
return f32(${r}[${u > 1 ? "getOutputIndexFromCoords(coords)" : "coords"}]);
}
`;
let c = C.getBroadcastDims(e.shape, t), p = u - i, d = "";
if (i === 0)
return n ? `
fn ${o}Index(globalIndex : i32) -> vec4<f32> {
return get${a}();
}
fn ${o}Coords(coords : ${l}) -> vec4<f32> {
return get${a}();
}
` : `
fn ${o}Index(globalIndex : i32) -> f32{
return get${a}();
}
fn ${o}Coords(coords : ${l}) -> f32{
return get${a}();
}
`;
u < 2 && c.length >= 1 ? d = "coords = 0;" : d = c.map((g) => `coords.${hr(g + p)} = 0;`).join(`
`);
let h = "";
if (u < 2 && i > 0)
h = "coords";
else if (u > 1) {
let g = Wt(i), b = e.shape.map((y, v) => `coords.${hr(v + p)}`).join(", ");
h = `${g}(${b})`;
} else
h = "coords";
let f = `uniforms.${r.charAt(0).toLowerCase() + r.slice(1)}Shape`, m = `${i}D`;
return n ? `
fn ${o}Index(globalIndex : i32) -> vec4<f32> {
var coords = getCoordsFromIndex(globalIndex);
${d}
return ${r}[getIndexFromCoords${m}(${h}, ${f}) / 4];
}
fn ${o}Coords(coordsIn : ${l}) -> vec4<f32> {
var coords = coordsIn;
${d}
return ${r}[getIndexFromCoords${m}(${h}, ${f}) / 4];
}
` : `
fn ${o}Index(globalIndex : i32) -> f32 {
var coords = getCoordsFromIndex(globalIndex);
${d}
return f32(${r}[getIndexFromCoords${m}(${h}, ${f})]);
}
fn ${o}Coords(coordsIn : ${l}) -> f32 {
var coords = coordsIn;
${d}
return f32(${r}[getIndexFromCoords${m}(${h}, ${f})]);
}
`;
}
function ese(e, t, n, s) {
let r = Zne(e, n);
return e.shape.length <= t.length && (r += Jne(e, t, n, s)), r;
}
function tse(e, t) {
let { x: n, y: s = [], z: r = [] } = t, a = e.length;
if (n.length === a)
return [`fn getOutputCoords() -> ${Wt(a)}{
let globalIndex = getGlobalIndex();
return getCoordsFromIndex(globalIndex);
}
`, a];
let o = "", i = [n, s, r], u = 0;
for (let d = 0; d < i.length; d++) {
let h = i[d];
if (h.length !== 0)
if (u += h.length, h.length === 1)
o += `let d${h[0]} = i32(globalId[${d}]);`;
else {
let f = Yne(h, "uniforms.outShape");
o += `var index${d} = i32(globalId[${d}]);`;
for (let m = 0; m < f.length; m++)
o += `let d${h[m]} = index${d} / ${f[m]};`, m === f.length - 1 ? o += `let d${h[m + 1]} = index${d} - d${h[m]} * ${f[m]};` : o += `index${d} = index${d} - d${h[m]} * ${f[m]};`;
}
}
let l = [];
for (let d = 0; d < u; d++)
l.push(`d${d}`);
let c = Wt(u), p = `fn getOutputCoords() -> ${c} {
${o}
`;
return l.length === 0 ? p += `return ${c}(0); }` : p += `return ${c}(${l.join(",")}); }`, [p, u];
}
function nse(e) {
let t = "";
switch (e) {
case 0:
case 1:
t += `
fn getOutputIndexFromCoords(coords : i32) -> i32 {
return coords;
}
`;
break;
case 2:
t += `
fn getOutputIndexFromCoords(coords : vec2<i32>) -> i32 {
return dot(coords, vec2<i32>(uniforms.outShapeStrides, 1));
}
`;
break;
case 3:
t += `
fn getOutputIndexFromCoords(coords : vec3<i32>) -> i32 {
return dot(coords, vec3<i32>(uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, 1));
}
`;
break;
case 4:
t += `
fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
return dot(coords, vec4<i32>(
uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, uniforms.outShapeStrides.z, 1));
}
`;
break;
case 5:
t += `
fn getOutputIndexFromCoords(coords : vec5) -> i32 {
return coords.x * uniforms.outShapeStrides.x +
coords.y * uniforms.outShapeStrides.y +
coords.z * uniforms.outShapeStrides.z +
coords.w * uniforms.outShapeStrides.w +
coords.u;
}
`;
break;
case 6:
t += `
fn getOutputIndexFromCoords(coords : vec6) -> i32 {
return coords.x * uniforms.outShapeStrides.x +
coords.y * uniforms.outShapeStrides.y +
coords.z * uniforms.outShapeStrides.z +
coords.w * uniforms.outShapeStrides.w +
coords.u * uniforms.outShapeStrides.u +
coords.v;
}
`;
break;
default:
w.assert(false, () => `Unsupported ${e}D shape`);
break;
}
return t;
}
function L2(e) {
return e.dispatch[1] === 1 && e.dispatch[2] === 1;
}
function gd(e, t) {
return e === "float32" ? t ? "vec4<f32>" : "f32" : e === "int32" || e === "bool" ? t ? "vec4<i32>" : "i32" : e;
}
function sse(e, t, n) {
let s = e.length, r = gd(t, n), a;
if (n ? a = `fn setOutputAtIndex(flatIndex : i32, value : vec4<f32>) {
result[flatIndex] = ${r}(value);
}
fn setOutputAtIndexI32(flatIndex : i32, value : vec4<i32>) {
result[flatIndex] = ${r}(value);
}` : a = `fn setOutputAtIndex(flatIndex : i32, value : f32) {
result[flatIndex] = ${r}(value);
}
fn setOutputAtIndexI32(flatIndex : i32, value : i32) {
result[flatIndex] = ${r}(value);
}`, s >= 2) {
let o = ["d0", "d1", "d2", "d3", "d4", "d5"].slice(0, s), i = Wt(s);
n ? a += `
fn setOutputAtCoords(${o.map((u) => `${u} : i32`).join(", ")}, value : vec4<f32>) {
let flatIndex = getOutputIndexFromCoords(${i}(${o.join(", ")}));
setOutputAtIndex(flatIndex / 4, value);
}
fn setOutputAtCoordsI32(${o.map((u) => `${u} : i32`).join(", ")}, value : vec4<i32>) {
let flatIndex = getOutputIndexFromCoords(${i}(${o.join(", ")}));
setOutputAtIndexI32(flatIndex / 4, value);
}
` : a += `
fn setOutputAtCoords(${o.map((u) => `${u} : i32`).join(", ")}, value : f32) {
let flatIndex = getOutputIndexFromCoords(${i}(${o.join(", ")}));
setOutputAtIndex(flatIndex, value);
}
fn setOutputAtCoordsI32(${o.map((u) => `${u} : i32`).join(", ")}, value : i32) {
let flatIndex = getOutputIndexFromCoords(${i}(${o.join(", ")}));
setOutputAtIndexI32(flatIndex, value);
}
`;
}
return a;
}
var rse = (e) => e ? `
mm_Asub[inputRow][inputCol] = mm_readA(
t * TileInner + inputRow,
globalRowStart + inputCol, globalId);
` : `
mm_Asub[inputRow][inputCol] = mm_readA(
globalRowStart + inputRow,
t * TileInner + inputCol, globalId);
`;
var ase = (e) => e ? "let ACached = mm_Asub[k][tileRow + innerRow];" : "let ACached = mm_Asub[tileRow + innerRow][k];";
function Mv(e, t, n = false, s = 32) {
let r = e[1] * t[1], a = e[0] * t[0], o = n ? r : s, i = n ? s : r;
w.assert(i % t[1] === 0 && o % t[0] === 0 && s % t[1] === 0, () => `tileAHight ${i} must be divisible by workGroupSize[1]${t[1]}, tileAWidth ${o} must be divisible by workGroupSize[0]${t[0]}, tileInner ${s} must be divisible by workGroupSize[1]${t[1]}`);
let u = i / t[1], l = o / t[0], c = s / t[1];
return `
var<workgroup> mm_Asub : array<array<f32, ${o}>, ${i}>;
var<workgroup> mm_Bsub : array<array<f32, ${a}>, ${s}>;
let RowPerThread = ${e[1]};
let ColPerThread = ${e[0]};
let TileInner = ${s};
@stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)
fn main(@builtin(local_invocation_id) LocalId : vec3<u32>,
@builtin(global_invocation_id) GlobalId : vec3<u32>,
@builtin(num_workgroups) NumWorkgroups: vec3<u32>,
@builtin(workgroup_id) workgroupId: vec3<u32>) {
localId = LocalId;
globalId = GlobalId;
numWorkgroups = NumWorkgroups;
let tileRow = i32(localId.y) * RowPerThread;
let tileCol = i32(localId.x) * ColPerThread;
let globalRow = i32(globalId.y) * RowPerThread;
let globalCol = i32(globalId.x) * ColPerThread;
let globalRowStart = i32(workgroupId.y) * ${r};
let numTiles = (uniforms.dimInner - 1) / TileInner + 1;
var acc : array<array<f32, ColPerThread>, RowPerThread>;
// Without this initialization strange values show up in acc.
for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) {
for (var innerCol = 0; innerCol < ColPerThread; innerCol = innerCol + 1) {
acc[innerRow][innerCol] = 0.0;
}
}
let tileRowA = i32(localId.y) * ${u};
let tileColA = i32(localId.x) * ${l};
let tileRowB = i32(localId.y) * ${c};
// Loop over shared dimension.
for (var t = 0; t < numTiles; t = t + 1) {
// Load one tile of A into local memory.
for (var innerRow = 0; innerRow < ${u}; innerRow = innerRow + 1) {
for (var innerCol = 0; innerCol < ${l}; innerCol = innerCol + 1) {
let inputRow = tileRowA + innerRow;
let inputCol = tileColA + innerCol;
${rse(n)}
}
}
// Load one tile of B into local memory.
for (var innerRow = 0; innerRow < ${c}; innerRow = innerRow + 1) {
for (var innerCol = 0; innerCol < ColPerThread; innerCol = innerCol + 1) {
let inputRow = tileRowB + innerRow;
let inputCol = tileCol + innerCol;
mm_Bsub[inputRow][inputCol] = mm_readB(
t * ${s} + inputRow,
globalCol + innerCol, globalId);
}
}
workgroupBarrier();
// Compute acc values for a single thread.
var BCached : array<f32, ColPerThread>;
for (var k = 0; k < TileInner; k = k + 1) {
for (var inner = 0; inner < ColPerThread; inner = inner + 1) {
BCached[inner] = mm_Bsub[k][tileCol + inner];
}
for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) {
${ase(n)}
for (var innerCol = 0; innerCol < ColPerThread; innerCol = innerCol + 1) {
acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];
}
}
}
workgroupBarrier();
}
for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) {
for (var innerCol = 0; innerCol < ColPerThread; innerCol = innerCol + 1) {
mm_write(globalRow + innerRow,
globalCol + innerCol,
acc[innerRow][innerCol], globalId);
}
}
}
`;
}
var ose = (e) => e ? `
mm_readA(colA, globalRow, globalId),
mm_readA(colA + 1, globalRow, globalId),
mm_readA(colA + 2, globalRow, globalId),
mm_readA(colA + 3, globalRow, globalId)
` : `
mm_readA(globalRow, colA, globalId),
mm_readA(globalRow, colA + 1, globalId),
mm_readA(globalRow, colA + 2, globalId),
mm_readA(globalRow, colA + 3, globalId)
`;
function ise(e, t = false) {
return w.assert(e[1] === 1 && e[2] === 1, () => `A linear work group size is required. But got ${e}.`), `
let TileSize = ${e[0] * 4};
var<workgroup> mm_Asub : array<vec4<f32>, ${e[0]}>;
${ac()}
let tileCol = i32(localId.x);
let globalCol = i32(globalId.x);
let globalRow = i32(globalId.y);
let numTiles = (uniforms.dimInner - 1) / TileSize + 1;
// Without this initialization strange values show up in acc.
var acc = 0.0;
// Loop over shared dimension.
for (var t = 0; t < numTiles; t = t + 1) {
// Load one tile of A into local memory.
let colA = t * TileSize + tileCol * 4;
mm_Asub[tileCol] = vec4<f32>(${ose(t)});
workgroupBarrier();
// Compute acc values for a single thread.
for (var k = 0; k < TileSize / 4; k = k + 1) {
let rowB = t * TileSize + k * 4;
let BCached = vec4<f32>(mm_readB(rowB, globalCol, globalId),
mm_readB(rowB + 1, globalCol, globalId),
mm_readB(rowB + 2, globalCol, globalId),
mm_readB(rowB + 3, globalCol, globalId));
let ACached = mm_Asub[k];
acc = acc + dot(ACached, BCached);
}
workgroupBarrier();
}
mm_write(globalRow, globalCol, acc, globalId);
}
`;
}
var use = class {
constructor(e, t, n, s, r, a = false, o = false, i = null, u = null, l = null) {
this.variableNames = ["A", "B"], this.uniforms = "dimAOuter : i32, dimBOuter : i32, dimInner : i32,", this.workGroupSize = [16, 16, 1], this.outputShape = t, this.dispatchLayout = { x: [2], y: [1], z: [0] };
let c = a ? e[1] : e[2];
this.workGroupSize = O2(t[1], c, t[2]), (t[1] === 1 || t[2] === 1) && (n = 1), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize, [n, n, 1]), w.arraysEqual(this.dispatch, [1, 1, 1]) && (n = 1, this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize, [n, n, 1]));
let p = i != null, d = l != null;
p && this.variableNames.push("bias"), d && this.variableNames.push("preluActivationWeights"), this.workPerThread = n, this.transposeA = a, this.transposeB = o, this.addBias = p, this.activation = u, this.hasPreluActivationWeights = d, this.batchAEqualOne = s, this.batchBEqualOne = r, [this.fitAOuter, this.fitBOuter, this.fitInner] = this.getShapeFit(t[1], t[2], c), this.shaderKey = `matMulPacked_${this.workPerThread}_${a}_${o}_${this.activation}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.outputShape[1] > 1}_${this.batchAEqualOne}_${this.batchBEqualOne}`;
}
getShapeFit(e, t, n) {
let s = this.workGroupSize[1] * this.workPerThread, r = this.workGroupSize[0] * this.workPerThread;
this.tileInner = 32, this.outputShape[1] === 1 && (this.tileInner = this.workGroupSize[0] * 4);
let a = e % s === 0, o = t % r === 0, i = n % this.tileInner === 0;
return [a, o, i];
}
getUserCode() {
let e = this.fitAOuter && this.fitInner ? "return A[batch * batchASize + row * uniforms.aShape[2] + col];" : `
if(row < uniforms.aShape[1] && col < uniforms.aShape[2]) {
return A[batch * batchASize + row * uniforms.aShape[2] + col];
}
return 0.0;
`, t;
this.transposeB === false ? t = "return B[batch * batchBSize + row * uniforms.dimBOuter + col];" : t = "return B[batch * batchBSize + col * uniforms.dimInner + row];";
let n = "", s = "";
if (this.activation) {
let o = Io(this.activation, false);
this.hasPreluActivationWeights ? n = `fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
let b = getPreluActivationWeightsByOutputCoords(outCoord);
${o}
}` : n = `
fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
${o}
}
`, s = "value = activation(value, outCoord);";
}
let r = this.addBias ? "value = value + getBiasByOutputCoords(outCoord);" : "";
return `
${n}
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
${this.batchAEqualOne ? `
let batch = 0;
let batchASize = 0;
` : `
let batch = i32(globalId.z);
let batchASize = uniforms.aShape[1] * uniforms.aShape[2];
`}
${e}
}
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
${this.batchBEqualOne ? `
let batch = 0;
let batchBSize = 0;
` : `
let batch = i32(globalId.z);
let batchBSize = uniforms.bShape[1] * uniforms.bShape[2];
`}
${t}
}
fn mm_write(row : i32, col : i32, valueIn : f32, globalId : vec3<u32>) {
${this.fitAOuter && this.fitBOuter ? "" : "if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)"}
{
var value = valueIn;
let batch = i32(globalId.z);
let outCoord = vec3<i32>(batch, row, col);
${r}
${s}
setOutputAtCoords(batch, row, col, value);
}
}
${this.outputShape[1] > 1 ? Mv([this.workPerThread, this.workPerThread, 1], this.workGroupSize, this.transposeA, this.tileInner) : ise(this.workGroupSize, this.transposeA)}
`;
}
};
function lse() {
return `
var<workgroup> sumValues : array<f32, workGroupSizeX>;
${ac()}
let coords = getOutputCoords();
let batch = coords[0];
let row = coords[1];
let col = coords[2];
var sum = 0.0;
let Length = uniforms.dimInner;
for (var k = i32(localId.x); k < Length; k = k + i32(workGroupSizeX)) {
let dataA = mm_readA(batch, row, k);
let dataB = mm_readB(batch, k, col);
sum = sum + dataA * dataB;
}
sumValues[localId.x] = sum;
workgroupBarrier();
for(var currentSize = workGroupSizeX / 2u; currentSize > 1u;
currentSize = currentSize / 2u) {
if (localId.x < currentSize)
{
sumValues[localId.x] = sumValues[localId.x] + sumValues[localId.x + currentSize];
}
workgroupBarrier();
}
if (localId.x == 0u) {
sum = sumValues[0] + sumValues[1];
mm_write(batch, row, col, sum);
}
}
`;
}
var cse = class {
constructor(e, t, n, s = false, r = false, a = null, o = null, i = null) {
this.variableNames = ["A", "B"], this.uniforms = "dimAOuter : i32, dimBOuter : i32, dimInner : i32,", this.workGroupSize = [256, 1, 1], this.outputShape = e, this.dispatchLayout = { x: [], y: [1, 2], z: [0] }, this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize);
let u = a != null, l = i != null;
u && this.variableNames.push("bias"), l && this.variableNames.push("preluActivationWeights"), this.transposeA = s, this.transposeB = r, this.addBias = u, this.activation = o, this.hasPreluActivationWeights = l, this.batchAEqualOne = t, this.batchBEqualOne = n, this.shaderKey = `matMulReduce_${this.activation}_${s}_${r}_${this.batchAEqualOne}_${this.batchBEqualOne}`;
}
getUserCode() {
let e;
this.transposeA === false ? e = "return f32(A[batch * batchASize + row * uniforms.dimInner + col]);" : e = "return f32(A[batch * batchASize + col * uniforms.dimAOuter + row]);";
let t;
this.transposeB === false ? t = "return f32(B[batch * batchBSize + row * uniforms.dimBOuter + col]);" : t = "return f32(B[batch * batchBSize + col * uniforms.dimInner + row]);";
let n = "", s = "";
if (this.activation) {
let o = Io(this.activation, false);
this.hasPreluActivationWeights ? n = `fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
let b = getPreluActivationWeightsByOutputCoords(outCoord);
${o}
}` : n = `
fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
${o}
}
`, s = "value = activation(value, outCoord);";
}
let r = this.addBias ? "value = value + getBiasByOutputCoords(outCoord);" : "";
return `
${n}
fn mm_readA(batchIn: i32, row : i32, col : i32) -> f32 {
${this.batchAEqualOne ? `
let batchASize = 0;
let batch = 0;
` : `
let batchASize = uniforms.aShape[1] * uniforms.aShape[2];
let batch = batchIn;
`}
${e}
}
fn mm_readB(batchIn: i32, row : i32, col : i32) -> f32 {
${this.batchBEqualOne ? `
let batch = 0;
let batchBSize = 0;
` : `
let batch = batchIn;
let batchBSize = uniforms.bShape[1] * uniforms.bShape[2];
`}
${t}
}
fn mm_write(batch: i32, row : i32, col : i32, valueIn : f32) {
var value = valueIn;
let outCoord = vec3<i32>(batch, row, col);
${r}
${s}
setOutputAtCoords(batch, row, col, value);
}
${lse()}
`;
}
};
function dse(e) {
let t = e[1] / 2, n = e[0], s = t > n ? t : n;
return `
var<workgroup> mm_Asub1 : array<array<f32, ${s}>, ${t}>;
var<workgroup> mm_Bsub1 : array<array<f32, ${n}>, ${s}>;
var<workgroup> mm_Asub2 : array<array<f32, ${s}>, ${t}>;
var<workgroup> mm_Bsub2 : array<array<f32, ${n}>, ${s}>;
// If the output size is small for matrix multiplication, avoid to use vec4
// and handle some elements per thread to optimally utilize the ALU.
// Introduces two shared memory buffers, some logical threads could handle
// arithmetic operations and others handle IO operations between barrier api,
// makes ALUs and load/store units work simultaneously, could improves
// the performance.
${ac()}
let tileRow = i32(localId.y);
let tileCol = i32(localId.x);
let globalRow = i32(globalId.y);
let globalCol = i32(globalId.x);
// uniforms.dimInner should be greater than 0.
let numTiles = (uniforms.dimInner - 1) / ${s} + 1;
var acc = 0.0;
var globalColA = tileCol;
var globalRowB = tileRow;
for (var t = 0; t < numTiles; t = t + 1) {
if (t == 0) {
if (tileRow < ${t}) {
// Load one tile of A and B into local memory.
// globalRow is always greater than or equal tileRow.
mm_Asub1[tileRow][tileCol] =
mm_readA((globalRow - tileRow) / 2 + tileRow, globalColA, globalId);
globalColA = globalColA + ${s};
mm_Bsub1[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
globalRowB = globalRowB + ${s};
}
} else {
if (tileRow < ${t}) {
// Load one tile of A and B into local memory.
// globalRow is always greater than or equal tileRow.
mm_Asub1[tileRow][tileCol] =
mm_readA((globalRow - tileRow) / 2 + tileRow, globalColA, globalId);
globalColA = globalColA + ${s};
mm_Bsub1[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
globalRowB = globalRowB + ${s};
} else {
// Compute acc values for a single thread.
for (var k = 0; k < ${s}; k = k + 1) {
let subRow = tileRow - ${t};
if (subRow < 0) {
continue;
}
acc = acc + mm_Asub2[subRow][k] * mm_Bsub2[k][tileCol];
}
}
}
workgroupBarrier();
if (t != 0) {
t = t + 1;
}
if (t < numTiles) {
if (tileRow < ${t}) {
// Load one tile of A and B into local memory.
// globalRow is always greater than or equal tileRow.
mm_Asub2[tileRow][tileCol] =
mm_readA((globalRow - tileRow) / 2 + tileRow, globalColA, globalId);
globalColA = globalColA + ${s};
mm_Bsub2[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
globalRowB = globalRowB + ${s};
} else {
// Compute acc values for a single thread.
for (var k = 0; k < ${s}; k = k + 1) {
let subRow = tileRow - ${t};
if (subRow < 0) {
continue;
}
acc = acc + mm_Asub1[subRow][k] * mm_Bsub1[k][tileCol];
}
}
}
workgroupBarrier();
}
let writeCol = (globalRow - tileRow) / 2 + tileRow - ${t};
if (tileRow >= ${t} && writeCol >= 0) {
mm_write(writeCol, globalCol, acc, globalId);
}
}
`;
}
var pse = class {
constructor(e, t, n, s = null, r = null, a = null) {
this.variableNames = ["A", "B"], this.uniforms = "dimAOuter : i32, dimBOuter : i32, dimInner : i32,", this.workGroupSize = [8, 16, 1], w.assert(e[1] <= 16 || t[2] <= 16, () => "This program can be only used when A width or B Height are small"), this.outputShape = n, this.dispatchLayout = { x: [2], y: [1], z: [0] }, this.dispatch = [Math.ceil(n[2] / this.workGroupSize[0]), Math.ceil(n[1] * 2 / this.workGroupSize[1]), n[0]];
let o = s != null;
o && this.variableNames.push("bias");
let i = a != null;
i && this.variableNames.push("preluActivationWeights"), this.addBias = o, this.activation = r, this.hasPreluActivationWeights = i, this.batchAEqualOne = e[0] === 1, this.batchBEqualOne = t[0] === 1, this.shaderKey = `matMulSmallOutputSize_${this.activation}_${this.batchAEqualOne}_${this.batchBEqualOne}`;
}
getUserCode() {
let e = `if (coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimAOuter, uniforms.dimInner))) {
return A[batch * batchASize + row * uniforms.dimInner + col];
}
return 0.0;`, t = `if (coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
return B[batch * batchBSize + row * uniforms.dimBOuter + col];
}
return 0.0;`, n = "", s = "";
if (this.activation) {
let o = Io(this.activation, false);
this.hasPreluActivationWeights ? n = `fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
let b = getPreluActivationWeightsByOutputCoords(outCoord);
${o}
}` : n = `fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
${o}
}`, s = "value = activation(value, outCoord);";
}
let r = this.addBias ? "value = value + getBiasByOutputCoords(outCoord);" : "";
return `
${n}
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
${this.batchAEqualOne ? `
let batch = 0;
let batchASize = 0;
` : `
let batchASize = uniforms.aShape[1] * uniforms.aShape[2];
let batch = i32(globalId.z);
`}
${e}
}
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
${this.batchBEqualOne ? `
let batch = 0;
let batchBSize = 0;
` : `
let batch = i32(globalId.z);
let batchBSize = uniforms.bShape[1] * uniforms.bShape[2];
`}
${t}
}
fn mm_write(row : i32, col : i32, valueIn : f32, globalId : vec3<u32>) {
if (coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimAOuter, uniforms.dimBOuter))) {
let batch = i32(globalId.z);
let outCoord = vec3<i32>(batch, row, col);
var value = valueIn;
${r}
${s}
setOutputAtCoords(batch, row, col, value);
}
}
${dse(this.workGroupSize)}
`;
}
};
function Le(e) {
let { inputs: t, attrs: n } = e, { x: s } = t, { shape: r } = n, a = w.sizeFromShape(s.shape), o = w.inferFromImplicitShape(r, a), i = w.sizeFromShape(o);
return w.assert(a === i, () => `The new shape (${o}) has ${i} elements and the old shape (${s.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`), e.backend.incRef(s.dataId), { dataId: s.dataId, shape: o, dtype: s.dtype };
}
var hse = { kernelName: Oi, backendName: "webgpu", kernelFunc: Le };
function Bv({ a: e, b: t, transposeA: n, transposeB: s, backend: r, bias: a = null, preluActivationWeights: o = null, leakyreluAlpha: i = 0, activation: u = null }) {
let l = e.shape.length, c = t.shape.length, p = n ? e.shape[l - 2] : e.shape[l - 1], d = s ? t.shape[c - 1] : t.shape[c - 2], h = n ? e.shape[l - 1] : e.shape[l - 2], f = s ? t.shape[c - 2] : t.shape[c - 1], m = e.shape.slice(0, -2), g = t.shape.slice(0, -2), b = w.sizeFromShape(m), y = w.sizeFromShape(g), x = Qi.assertAndGetBroadcastShape(e.shape.slice(0, -2), t.shape.slice(0, -2)).concat([h, f]);
w.assert(p === d, () => `Error in matMul: inner shapes (${p}) and (${d}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${s} must match.`);
let k = n ? [b, p, h] : [b, h, p], I = s ? [y, f, d] : [y, d, f], $ = Le({ inputs: { x: e }, backend: r, attrs: { shape: k } }), R = Le({ inputs: { x: t }, backend: r, attrs: { shape: I } }), E = [$, R], P = Math.max(b, y), A = b === 1, D = y === 1, T = (p % 4 === 0 && !n || h % 4 === 0 && n) && f % 4 === 0 && !s, L;
h * f <= 32 ? L = new cse([P, h, f], A, D, n, s, a, u, o) : !n && !s && (h <= 16 && (f <= 512 || d >= 2 * f) || f <= 16 && (h <= 512 || p >= 2 * h)) ? L = new pse(k, I, [P, h, f], a, u, o) : T ? L = new Xne(k, [P, h, f], A, D, n, a, u, o) : L = new use(k, [P, h, f], K().get("WEBGPU_MATMUL_WORK_PER_THREAD"), A, D, n, s, a, u, o);
let W = [$, R];
a && W.push(a), o && W.push(o);
let j = [{ type: "int32", data: [h] }, { type: "int32", data: [f] }, { type: "int32", data: [p] }];
u === "leakyrelu" && (j.push({ type: "float32", data: [i] }), L.uniforms += " alpha : f32,");
let Y = r.runWebGPUProgram(L, W, e.dtype, j), X = Le({ inputs: { x: Y }, backend: r, attrs: { shape: x } });
E.push(Y);
for (let Z of E)
r.disposeData(Z.dataId);
return X;
}
function fse(e) {
let { inputs: t, backend: n, attrs: s } = e, { a: r, b: a, bias: o, preluActivationWeights: i } = t, { transposeA: u, transposeB: l, activation: c, leakyreluAlpha: p } = s;
return Bv({ a: r, b: a, transposeA: u, transposeB: l, backend: n, bias: o, preluActivationWeights: i, leakyreluAlpha: p, activation: c });
}
var mse = { kernelName: oa, backendName: "webgpu", kernelFunc: fse };
var Ww = class {
constructor(e, t, n) {
this.variableNames = ["AReal", "AImag", "BReal", "BImag"], this.workGroupSize = [128, 1, 1], this.size = true, this.outputShape = C.assertAndGetBroadcastShape(t, n), this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.shaderKey = `binaryOpComplex_${e}`, this.op = e;
}
getUserCode() {
return `
fn binaryOpComplex(
areal : f32, aimag : f32, breal : f32, bimag : f32) -> f32 {
${rc(this.op, false)}
}
${Ue()}
if(index < uniforms.size) {
let areal = getARealByOutputIndex(index);
let aimag = getAImagByOutputIndex(index);
let breal = getBRealByOutputIndex(index);
let bimag = getBImagByOutputIndex(index);
setOutputAtIndex(index, binaryOpComplex(areal, aimag, breal, bimag));
}
}
`;
}
};
var gse = class {
constructor(e, t, n, s) {
this.variableNames = ["A", "B"], this.size = true;
let r = 256;
this.workGroupSize = [r, 1, 1], this.outputShape = C.assertAndGetBroadcastShape(t, n), this.dispatchLayout = Ve(this.outputShape), this.lastDimensionSize = s ? n[0] : t[0], this.lastDimensionSize < 256 ? this.workPerThread = 1 : this.lastDimensionSize < 512 ? this.workPerThread = 2 : this.workPerThread = 4, this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize, [this.workPerThread, 1, 1]), this.useSharedMemoryWithB = s, this.op = e, this.shaderKey = `binaryShared_${e}_${this.lastDimensionSize}_${this.useSharedMemoryWithB}`;
}
getUserCode() {
let e = this.lastDimensionSize > 1 ? `coords[${this.outputShape.length - 1}]` : "0", t = this.useSharedMemoryWithB ? `let a = getAByOutputCoords(coords);
let b = sharedBuf[${e}];` : `let a = sharedBuf[${e}];
let b = getBByOutputCoords(coords);`;
return `
fn binaryOperation(a : f32, b : f32) -> f32 {
${rc(this.op, false)}
}
var<workgroup> sharedBuf : array<f32, ${this.lastDimensionSize}>;
${Ue()}
// Fill in the shared memory buffer. Here we need a loop to make sure
// that all data in A|B are uploaded when |sharedMemorySize| is larger
// than work group size.
for(var localIndex = i32(localId.x); localIndex < ${this.lastDimensionSize}; localIndex = localIndex + ${this.workGroupSize[0]}) {
sharedBuf[localIndex] = f32(${this.useSharedMemoryWithB ? "B" : "A"}[localIndex]);
}
workgroupBarrier();
for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
let flatIndex = index * ${this.workPerThread} + i;
if(flatIndex < uniforms.size) {
let coords = getCoordsFromIndex(flatIndex);
${t}
setOutputAtIndex(flatIndex, binaryOperation(a, b));
}
}
}
`;
}
};
var bse = class {
constructor(e, t, n) {
this.variableNames = ["A", "B"], this.workPerThread = 4, this.isVec4 = true, this.size = true;
let s = 128;
this.workGroupSize = [s, 1, 1], this.outputShape = C.assertAndGetBroadcastShape(t, n), this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize, [this.workPerThread, 1, 1]), this.op = e, this.shaderKey = `binaryVec4_${e}`;
}
getUserCode() {
return `
fn binaryOperation(a : vec4<f32>, b : vec4<f32>) -> vec4<f32> {
${rc(this.op, this.isVec4)}
}
${Ue()}
if (index < uniforms.size) {
let a = getAByOutputIndex(index);
let b = getBByOutputIndex(index);
setOutputAtIndex(index, binaryOperation(a, b));
}
}
`;
}
};
var M2 = class {
constructor(e, t, n) {
this.variableNames = ["A", "B"], this.size = true;
let s = 128;
this.workGroupSize = [s, 1, 1], this.outputShape = C.assertAndGetBroadcastShape(t, n), this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.shaderKey = `binary_${e}`, this.op = e;
}
getUserCode() {
return `
fn binaryOperation(a : f32, b : f32) -> f32 {
${rc(this.op, false)}
}
${Ue()}
if (index < uniforms.size) {
let a = getAByOutputIndex(index);
let b = getBByOutputIndex(index);
setOutputAtIndex(index, binaryOperation(a, b));
}
}
`;
}
};
function Uw(e, t, n) {
if (w.arraysEqual(t, n) && w.sizeFromShape(t) % 4 === 0)
return new bse(e, t, n);
let r = t.length === 1 && n.length > 1 && t[0] < 1024, a = n.length === 1 && t.length > 1 && n[0] < 1024;
return r || a ? new gse(e, t, n, a) : new M2(e, t, n);
}
function Un(e) {
let { inputs: t } = e, { x: n } = t;
return e.backend.incRef(n.dataId), { dataId: n.dataId, shape: n.shape, dtype: n.dtype };
}
var yse = { kernelName: Wa, backendName: "webgpu", kernelFunc: Un };
function hu(e) {
let { inputs: t, backend: n } = e, { real: s, imag: r } = t, a = n.makeTensorInfo(s.shape, "complex64"), o = n.tensorMap.get(a.dataId), i = Un({ inputs: { x: s }, backend: n }), u = Un({ inputs: { x: r }, backend: n });
return o.complexTensorInfos = { real: i, imag: u }, a;
}
var vse = { kernelName: np, backendName: "webgpu", kernelFunc: hu };
var oc = class {
constructor(e, t) {
this.variableNames = ["A"], this.size = true;
let n = 128;
this.workGroupSize = [n, 1, 1], this.outputShape = e, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.op = t, this.shaderKey = `unary_${t}`;
}
getUserCode() {
return `
fn unaryOperation(a : f32) -> f32 {
${jr(this.op, false)}
}
${Ue()}
if (index < uniforms.size) {
let a = getAByOutputIndex(index);
setOutputAtIndex(index, unaryOperation(a));
}
}
`;
}
};
function Kt({ opType: e, cpuKernelImpl: t, dtype: n }) {
return ({ inputs: s, backend: r }) => {
let { x: a } = s, o = r, i = n || a.dtype;
if (o.shouldExecuteOnCPU([a]) && t != null) {
let l = o.tensorMap.get(a.dataId), c = t(l.values, i);
return o.makeTensorInfo(a.shape, i, c);
}
let u = new oc(a.shape, e);
return o.runWebGPUProgram(u, [a], i);
};
}
function gn({ opSnippet: e, cpuKernelImpl: t, supportsComplex: n = false, dtype: s }) {
return ({ inputs: r, backend: a }) => {
let { a: o, b: i } = r, u = a;
if (n && o.dtype === "complex64") {
let p = u.tensorMap.get(o.dataId), d = u.tensorMap.get(i.dataId), h, f;
if (e !== 0)
[h, f] = [[p.complexTensorInfos.real, d.complexTensorInfos.real], [p.complexTensorInfos.imag, d.complexTensorInfos.imag]].map((g) => {
let [b, y] = g, v = { dataId: b.dataId, dtype: b.dtype, shape: o.shape }, x = { dataId: y.dataId, dtype: y.dtype, shape: i.shape }, k = Uw(e, o.shape, i.shape);
return u.runWebGPUProgram(k, [v, x], cn(b.dtype, y.dtype));
});
else {
let g = new Ww(17, o.shape, i.shape), b = new Ww(18, o.shape, i.shape), y = [{ dataId: p.complexTensorInfos.real.dataId, dtype: p.complexTensorInfos.real.dtype, shape: o.shape }, { dataId: p.complexTensorInfos.imag.dataId, dtype: p.complexTensorInfos.imag.dtype, shape: o.shape }, { dataId: d.complexTensorInfos.real.dataId, dtype: d.complexTensorInfos.real.dtype, shape: i.shape }, { dataId: d.complexTensorInfos.imag.dataId, dtype: d.complexTensorInfos.imag.dtype, shape: i.shape }];
h = u.runWebGPUProgram(g, y, "float32"), f = u.runWebGPUProgram(b, y, "float32");
}
let m = hu({ inputs: { real: h, imag: f }, backend: u });
return u.disposeData(h.dataId), u.disposeData(f.dataId), m;
}
let l = s || cn(o.dtype, i.dtype);
if ((o.dtype === "string" || i.dtype === "string" || u.shouldExecuteOnCPU([o, i])) && t != null) {
let p = u.tensorMap.get(o.dataId).values, d = u.tensorMap.get(i.dataId).values, h = o.dtype === "string" ? C.fromUint8ToStringArray(p) : p, f = o.dtype === "string" ? C.fromUint8ToStringArray(d) : d, [m, g] = t(o.shape, i.shape, h, f, l);
return u.makeTensorInfo(g, l, m);
}
let c = Uw(e, o.shape, i.shape);
return u.runWebGPUProgram(c, [o, i], l);
};
}
var { addImpl: xse, ceilImpl: wse, concatImpl: kse, equalImpl: Sse, expImpl: Ise, expm1Impl: Cse, floorImpl: Nse, gatherNdImpl: Tse, gatherV2Impl: $se, greaterEqualImpl: _se, greaterImpl: Ase, lessEqualImpl: Ese, lessImpl: Rse, logImpl: Dse, maxImpl: Fse, maximumImpl: Ose, minimumImpl: Pse, multiplyImpl: zse, negImpl: Lse, notEqualImpl: Mse, prodImpl: Bse, rangeImpl: Vse, rsqrtImpl: Wse, scatterImpl: Use, simpleAbsImpl: Gse, sliceImpl: Hse, stridedSliceImpl: qse, stringNGramsImpl: jse, subImpl: Kse, tileImpl: Xse, topKImpl: Yse, transposeImpl: Qse, uniqueImpl: Lhe } = cv;
var Zse = Kt({ opType: 0, cpuKernelImpl: Gse });
var Jse = { kernelName: di, backendName: "webgpu", kernelFunc: Zse };
var ere = gn({ opSnippet: 1, cpuKernelImpl: xse, supportsComplex: true });
var tre = { kernelName: Cr, backendName: "webgpu", kernelFunc: ere };
var nre = class {
constructor(e) {
this.workPerThread = 4, this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = e[0], this.variableNames = e.map((t, n) => `T${n}`), this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize, [this.workPerThread, 1, 1]), this.shaderKey = "addN";
}
getUserCode() {
let e = [];
this.variableNames.forEach((s) => {
e.push(`let v${s} = get${s}ByOutputCoords(coords);`);
});
let t = this.variableNames.map((s) => `v${s}`).join(" + ");
return `
${Ue()}
for (var i = 0; i < ${this.workPerThread}; i = i + 1) {
let flatIndex = index * ${this.workPerThread} + i;
if (flatIndex < uniforms.size) {
let coords = getCoordsFromIndex(flatIndex);
${e.join(`
`)}
setOutputAtIndex(flatIndex, ${t});
}
}
}
`;
}
};
function sre(e) {
let { inputs: t, backend: n } = e, s = t;
if (s.length === 1)
return Un({ inputs: { x: s[0] }, backend: n });
let r = s.map((i) => i.dtype).reduce((i, u) => cn(i, u)), a = s.map((i) => i.shape), o = new nre(a);
return n.runWebGPUProgram(o, s, r);
}
var rre = { kernelName: Sa, backendName: "webgpu", kernelFunc: sre };
var B2 = class {
constructor(e, t, n) {
this.workGroupSize = [64, 1, 1], this.variableNames = ["x"], this.uniforms = "infinityValue : f32,", this.size = true;
let s = [t];
C.assertAxesAreInnerMostDims("arg" + n.charAt(0).toUpperCase() + n.slice(1), s, e.length), this.op = n === "min" ? "<" : ">";
let [r] = C.computeOutAndReduceShapes(e, s);
this.outputShape = r.length === 0 ? [1] : r, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, [1, 1, 1]), this.inputShape = e, this.shaderKey = `argMinMax${this.op}`;
}
getUserCode() {
let e = `
var<workgroup> xBestIndices : array<i32, ${this.workGroupSize[0]}>;
var<workgroup> xBestValues : array<f32, ${this.workGroupSize[0]}>;
`, t = () => this.inputShape.length === 1 ? "uniforms.xShape" : `uniforms.xShape.${hr(this.inputShape.length - 1)}`, n = () => {
let r = "";
if (this.outputShape.length === 1)
this.inputShape.length !== 1 && (r += "outputCoords,");
else
for (let a = 0; a < this.outputShape.length; a++)
r += `outputCoords.${hr(a)},`;
return r;
};
return `
fn DIV_CEIL(a : u32, b : u32) -> u32 {
return ((a - 1u) / b + 1u);
}
${e}
${Ue()}
let outputIndex = index / i32(workGroupSizeX);
let reduceLength = ${t()};
var bestIndex = i32(localId.x);
var bestValue = uniforms.infinityValue;
let outputCoords = getCoordsFromIndex(outputIndex);
for (var k = i32(localId.x); k < reduceLength && outputIndex < uniforms.size;
k = k + i32(workGroupSizeX)) {
let candidate = getX(${n()} k);
if (!isnan(candidate) && candidate ${this.op} bestValue) {
bestValue = candidate;
bestIndex = k;
}
}
xBestValues[localId.x] = bestValue;
xBestIndices[localId.x] = bestIndex;
workgroupBarrier();
var reduceSize = min(u32(reduceLength), workGroupSizeX);
for (var currentSize = reduceSize / 2u; reduceSize > 1u;
currentSize = reduceSize / 2u) {
let interval = DIV_CEIL(reduceSize, 2u);
if (localId.x < currentSize) {
let candidate = xBestValues[localId.x + interval];
if (candidate ${this.op} bestValue) {
bestValue = candidate;
xBestValues[localId.x] = bestValue;
xBestIndices[localId.x] = xBestIndices[localId.x + interval];
}
}
reduceSize = interval;
workgroupBarrier();
}
if (localId.x == 0u && outputIndex < uniforms.size) {
setOutputAtIndexI32(outputIndex, xBestIndices[localId.x]);
}
}
`;
}
};
var are = class {
constructor(e, t) {
this.variableNames = ["A"], this.workGroupSize = [16, 16, 1];
let n = new Array(e.length);
for (let s = 0; s < n.length; s++)
n[s] = e[t[s]];
this.outputShape = n, this.dispatchLayout = { x: [0], y: [1] }, this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize, [1, 1, 1]), this.shaderKey = "transposeShared";
}
getUserCode() {
return `
let TILE_DIM = ${this.workGroupSize[0]};
var<workgroup> tile : array<array<f32, ${this.workGroupSize[0] + 1}>, ${this.workGroupSize[0]}>;
${Lv()}
fn main(@builtin(local_invocation_id) localId : vec3<u32>,
@builtin(workgroup_id) workgroupId : vec3<u32>) {
var x = i32(workgroupId.x) * TILE_DIM + i32(localId.x);
var y = i32(workgroupId.y) * TILE_DIM + i32(localId.y);
let width = uniforms.outShape[0];
let height = uniforms.outShape[1];
if (x < width && y < height) {
tile[localId.y][localId.x] = A[y * width + x];
}
workgroupBarrier();
x = i32(workgroupId.y) * TILE_DIM + i32(localId.x);
y = i32(workgroupId.x) * TILE_DIM + i32(localId.y);
if (x < height && y < width) {
setOutputAtIndex((y * height + x), tile[localId.x]
[localId.y]);
}
}
`;
}
};
var ore = class {
constructor(e, t) {
this.variableNames = ["A"], this.workPerThread = 4, this.workGroupSize = [64, 1, 1], this.size = true;
let n = new Array(e.length);
for (let s = 0; s < n.length; s++)
n[s] = e[t[s]];
this.outputShape = n, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize, [this.workPerThread, 1, 1]), this.newDim = t, this.shaderKey = `transpose_${t}`;
}
getUserCode() {
let e = Wt(this.outputShape.length), t = ire(this.newDim);
return `
${Ue()}
for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
let flatIndex = index * ${this.workPerThread} + i;
if(flatIndex < uniforms.size) {
let resRC = getCoordsFromIndex(flatIndex);
setOutputAtIndex(flatIndex, A[getIndexFromCoords${this.outputShape.length}D(
${e}(${t}), uniforms.aShape)]);
}
}
}
`;
}
};
function ire(e) {
let t = e.length;
if (t > 6)
throw Error(`Transpose for rank ${t} is not yet supported`);
let n = new Array(t);
for (let s = 0; s < e.length; s++)
n[e[s]] = `resRC.${hr(s)}`;
return n.join();
}
function Ks(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { perm: a } = s, o = n, i = r.shape.length, u = new Array(i);
for (let c = 0; c < u.length; c++)
u[c] = r.shape[a[c]];
if (n.shouldExecuteOnCPU([r])) {
let p = o.tensorMap.get(r.dataId).values, d = Qse(p, r.shape, r.dtype, a, u);
return n.makeTensorInfo(u, r.dtype, d);
}
if (r.shape.length === 2 && w.arraysEqual(a, [1, 0])) {
let c = new are(r.shape, a);
return o.runWebGPUProgram(c, [r], r.dtype);
}
let l = new ore(r.shape, a);
return o.runWebGPUProgram(l, [r], r.dtype);
}
var ure = { kernelName: Hs, backendName: "webgpu", kernelFunc: Ks };
function lre(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a } = s, o = w.parseAxisParam(a, r.shape), i = C.getAxesPermutation(o, r.shape.length), u = r, l = [];
i != null && (u = Ks({ inputs: { x: r }, backend: n, attrs: { perm: i } }), l.push(u), o = C.getInnerMostAxes(o.length, u.shape.length)), C.assertAxesAreInnerMostDims("argMax", [o[0]], u.shape.length);
let c = new B2(u.shape, o[0], "max"), p = [{ type: "float32", data: [Number.NEGATIVE_INFINITY] }], d = n.runWebGPUProgram(c, [u], "int32", p);
return l.forEach((h) => n.disposeData(h.dataId)), d;
}
var cre = { kernelName: Ia, backendName: "webgpu", kernelFunc: lre };
function dre(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a } = s, o = w.parseAxisParam(a, r.shape), i = C.getAxesPermutation(o, r.shape.length), u = r, l = [];
i != null && (u = Ks({ inputs: { x: r }, backend: n, attrs: { perm: i } }), l.push(u), o = C.getInnerMostAxes(o.length, u.shape.length)), C.assertAxesAreInnerMostDims("argMin", [o[0]], u.shape.length);
let c = new B2(u.shape, o[0], "min"), p = [{ type: "float32", data: [Number.POSITIVE_INFINITY] }], d = n.runWebGPUProgram(c, [u], "int32", p);
return l.forEach((h) => n.disposeData(h.dataId)), d;
}
var pre = { kernelName: pl, backendName: "webgpu", kernelFunc: dre };
var V2 = class {
constructor(e, t) {
this.variableNames = ["x"], this.uniforms = "stride : vec2<i32>, pad : vec2<i32>, dilation : vec2<i32>, convDims : vec2<i32>, filterDims : vec2<i32>,", this.workGroupSize = [128, 1, 1], this.size = true, this.outputShape = e.outShape, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.shaderKey = `pool2D_${t}`, this.poolType = t;
}
getUserCode() {
let e = "resultValue = max(value, resultValue);";
this.poolType === "avg" && (e = "resultValue = resultValue + value; count = count + 1.0;");
let t = "resultValue";
return this.poolType === "avg" && (t = "resultValue / count"), `
${Ue()}
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let batch = coords[0];
let xRCCorner = vec2<i32>(coords.yz) * uniforms.stride - uniforms.pad;
let xRCorner = xRCCorner.x;
let xCCorner = xRCCorner.y;
var resultValue = ${this.poolType === "avg" ? "0.0" : "-1.0 / pow(10.0, -20.0)"};
var count = 0.0;
for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + uniforms.dilation.x) {
let xR = xRCorner + wR;
if (xR < 0 || xR >= uniforms.convDims.x) {
continue;
}
for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + uniforms.dilation.y) {
let xC = xCCorner + wC;
if (xC < 0 || xC >= uniforms.convDims.y) {
continue;
}
let value = getX(batch, xR, xC, coords[3]);
${e}
}
}
setOutputAtIndex(index, ${t});
}
}
`;
}
};
var W2 = class {
constructor(e) {
this.variableNames = ["x"], this.uniforms = "stride : vec2<i32>,", this.workGroupSize = [256, 1, 1], this.size = true, this.outputShape = e.outShape, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.shaderKey = "poolWithFilterSizeEqualsOne";
}
getUserCode() {
return `
${Ue()}
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let batch = coords[0];
let d = coords[3];
let xRCCorner = coords.yz * uniforms.stride;
let xRCorner = xRCCorner.x;
let xCCorner = xRCCorner.y;
let value = getX(batch, xRCorner, xCCorner, d);
setOutputAtIndex(index, value);
}
}
`;
}
};
function hre(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { filterSize: a, strides: o, pad: i, dimRoundingMode: u } = s, l = 1, c = C.computePool2DInfo(r.shape, a, o, l, i, u);
if (c.filterWidth === 1 && c.filterHeight === 1 && w.arraysEqual(c.inShape, c.outShape))
return Un({ inputs: { x: r }, backend: n });
let p, d = [{ type: "int32", data: [c.strideHeight, c.strideWidth] }];
return c.filterHeight === 1 && c.filterWidth === 1 ? p = new W2(c) : (p = new V2(c, "avg"), d.push({ type: "int32", data: [c.padInfo.top, c.padInfo.left] }, { type: "int32", data: [c.dilationHeight, c.dilationWidth] }, { type: "int32", data: [c.inHeight, c.inWidth] }, { type: "int32", data: [c.effectiveFilterHeight, c.effectiveFilterWidth] })), n.runWebGPUProgram(p, [r], r.dtype, d);
}
var fre = { kernelName: Ca, backendName: "webgpu", kernelFunc: hre };
function mre(e) {
let { inputs: t, backend: n, attrs: s } = e, { a: r, b: a } = t, { transposeA: o, transposeB: i } = s;
return Bv({ a: r, b: a, transposeA: o, transposeB: i, backend: n });
}
var gre = { kernelName: Na, backendName: "webgpu", kernelFunc: mre };
var bre = class {
constructor(e, t) {
this.variableNames = ["source"], this.workPerThread = 1, this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = t, this.rank = t.length, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize, [this.workPerThread, 1, 1]), this.start = e, this.uniforms = `start : ${Wt(e.length)}, `, this.shaderKey = "slice";
}
getUserCode() {
let e = Wt(this.rank), t = yre(this.rank), n;
return this.start.length === 1 ? n = this.outputShape.map((r, a) => "sourceLoc = uniforms.start + coords;") : n = this.outputShape.map((r, a) => `sourceLoc.${ag[a]} = uniforms.start[${a}] + coords.${ag[a]};`), `
${Ue()}
if (index < uniforms.size) {
var sourceLoc : ${e};
let coords = getCoordsFromIndex(index);
${n.join(`
`)}
setOutputAtIndex(index, getSource(${t}));
}
}
`;
}
};
var ag = ["x", "y", "z", "w", "u", "v"];
function yre(e) {
if (e === 1)
return "sourceLoc";
if (e <= 6)
return ag.slice(0, e).map((t) => `sourceLoc.${t}`).join(",");
throw Error(`Slicing for rank ${e} is not yet supported`);
}
function fu(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { begin: a, size: o } = s, [i, u] = kt.parseSliceParams(r, a, o);
if (kt.assertParamsValid(r, i, u), n.shouldExecuteOnCPU([r]) || r.dtype === "string") {
let p = n.tensorMap.get(r.dataId), d = Hse(p.values, i, u, r.shape, r.dtype);
return n.makeTensorInfo(u, r.dtype, d);
}
if (w.sizeFromShape(u) === 0)
return n.makeTensorInfo(u, r.dtype, []);
let l = new bre(i, u), c = [{ type: "int32", data: i }];
return n.runWebGPUProgram(l, [r], r.dtype, c);
}
var vre = { kernelName: Bi, backendName: "webgpu", kernelFunc: fu };
var xre = (e) => {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { blockShape: a, crops: o } = s;
w.assert(r.shape.length <= 4, () => "batchToSpaceND for rank > 4 with a WebGPU backend not implemented yet");
let i = a.reduce((y, v) => y * v), u = C.getReshaped(r.shape, a, i), l = C.getPermuted(u.length, a.length), c = C.getReshapedPermuted(r.shape, a, i), p = C.getSliceBeginCoords(o, a.length), d = C.getSliceSize(c, o, a.length), h = [], f = Le({ inputs: { x: r }, backend: n, attrs: { shape: u } }), m = Ks({ inputs: { x: f }, backend: n, attrs: { perm: l } }), g = Le({ inputs: { x: m }, backend: n, attrs: { shape: c } }), b = fu({ inputs: { x: g }, backend: n, attrs: { begin: p, size: d } });
return h.push(f), h.push(m), h.push(g), h.forEach((y) => n.disposeData(y.dataId)), b;
};
var wre = { kernelName: pi, backendName: "webgpu", kernelFunc: xre };
var U2 = gn({ opSnippet: 10, dtype: "bool", cpuKernelImpl: Mse });
var kre = { kernelName: _i, backendName: "webgpu", kernelFunc: U2 };
function ic(e) {
let { inputs: t, backend: n } = e, { input: s } = t, r = n.tensorMap.get(s.dataId);
return Un({ inputs: { x: r.complexTensorInfos.real }, backend: n });
}
var Sre = { kernelName: cp, backendName: "webgpu", kernelFunc: ic };
function Ire(e, t) {
let n = new oc(e.shape, 22), s = t.runWebGPUProgram(n, [e], "int32");
return { dataId: s.dataId, shape: s.shape, dtype: s.dtype };
}
function og(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { dtype: a } = s;
if (a === "complex64") {
if (r.dtype === "complex64")
return Un({ inputs: { x: r }, backend: n });
let o = $t(r.shape), i = og({ inputs: { x: r }, backend: n, attrs: { dtype: "float32" } }), u = hu({ inputs: { real: i, imag: o }, backend: n });
return o.dispose(), n.disposeData(i.dataId), u;
}
if (r.dtype === "complex64") {
let o = ic({ inputs: { input: r }, backend: n }), i = og({ inputs: { x: o }, backend: n, attrs: { dtype: a } });
return n.disposeData(o.dataId), i;
}
if (!w.hasEncodingLoss(r.dtype, a)) {
let o = Un({ inputs: { x: r }, backend: n });
return { dataId: o.dataId, shape: o.shape, dtype: a };
}
if (a === "int32")
return Ire(r, n);
if (a === "bool") {
let o = n.makeTensorInfo([], "bool", w.getTypedArrayFromDType("bool", 1)), u = U2({ inputs: { a: r, b: o }, backend: n });
return n.disposeData(o.dataId), u;
}
throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${a}`);
}
var Cre = { kernelName: Ta, backendName: "webgpu", kernelFunc: og };
var Nre = Kt({ opType: 1, cpuKernelImpl: wse });
var Tre = { kernelName: $a, backendName: "webgpu", kernelFunc: Nre };
var $re = class {
constructor(e) {
this.variableNames = ["A"], this.uniforms = "minVal : f32, maxVal : f32,", this.workPerThread = 4, this.workGroupSize = [64, 1, 1], this.isVec4 = true, this.size = true, this.outputShape = e, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize, [this.workPerThread, 1, 1]), this.shaderKey = "clipVec4";
}
getUserCode() {
return `
${Ue()}
if(index < uniforms.size) {
let value = getAByOutputIndex(index);
var clampedValue : vec4<f32>;
for (var i = 0; i < 4; i = i + 1) {
if (isnan(value[i])) {
clampedValue[i] = value[i];
} else {
clampedValue[i] = clamp(value[i], uniforms.minVal, uniforms.maxVal);
}
}
setOutputAtIndex(index, clampedValue);
}
}
`;
}
};
var _re = class {
constructor(e) {
this.variableNames = ["A"], this.uniforms = "minVal : f32, maxVal : f32,", this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.shaderKey = "clip";
}
getUserCode() {
return `
${Ue()}
if(index < uniforms.size) {
let value = getAByOutputIndex(index);
if (isnan(value)) {
setOutputAtIndex(index, value);
return;
}
setOutputAtIndex(index, clamp(value, uniforms.minVal, uniforms.maxVal));
}
}
`;
}
};
function Are(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { clipValueMin: a, clipValueMax: o } = s, i, u = [{ type: "float32", data: [a] }, { type: "float32", data: [o] }];
return w.sizeFromShape(r.shape) % 4 === 0 ? i = new $re(r.shape) : i = new _re(r.shape), n.runWebGPUProgram(i, [r], r.dtype, u);
}
var Ere = { kernelName: Nr, backendName: "webgpu", kernelFunc: Are };
var Rre = class {
constructor(e) {
this.uniforms = "", this.workPerThread = 4, this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = C.computeOutShape(e, 1), this.variableNames = e.map((t, n) => `T${n}`), this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize, [this.workPerThread, 1, 1]), this.offsetLength = e.length - 1;
for (let t = 0; t < this.offsetLength; t++)
this.uniforms += `offset${t} : i32,`;
this.shaderKey = "concat";
}
getUserCode() {
let e = [];
if (this.offsetLength > 0) {
e.push("if (yC < uniforms.offset0){ setOutputAtCoords(coords.x, coords.y, getT0(yR, yC)); }");
for (let r = 1; r < this.offsetLength; r++)
e.push(`else if (yC < uniforms.offset${[r]}){ setOutputAtCoords(coords.x, coords.y, getT${r}(yR, yC - uniforms.offset${r - 1})); }`);
let n = this.offsetLength, s = this.offsetLength - 1;
e.push(`else { setOutputAtCoords(coords.x, coords.y, getT${n}(yR, yC - uniforms.offset${s})); }`);
} else
e.push("setOutputAtCoords(coords.x, coords.y, getT0(yR, yC));");
return `
${Ue()}
for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
let flatIndex = index * ${this.workPerThread} + i;
if(flatIndex < uniforms.size) {
let coords = getCoordsFromIndex(flatIndex);
let yR = coords.x;
let yC = coords.y;
${e.join(`
`)}
}
}
}
`;
}
};
function ih(e) {
let { inputs: t, backend: n } = e, { input: s } = t, r = n.tensorMap.get(s.dataId);
return Un({ inputs: { x: r.complexTensorInfos.imag }, backend: n });
}
var Dre = { kernelName: ip, backendName: "webgpu", kernelFunc: ih };
function ig(e, t, n) {
let s = e[0].dtype;
if (s === "complex64") {
let h = e.map((y) => ic({ inputs: { input: y }, backend: n })), f = e.map((y) => ih({ inputs: { input: y }, backend: n })), m = ig(h, t, n), g = ig(f, t, n), b = hu({ inputs: { real: m, imag: g }, backend: n });
return h.forEach((y) => n.disposeData(y.dataId)), f.forEach((y) => n.disposeData(y.dataId)), n.disposeData(m.dataId), n.disposeData(g.dataId), b;
}
let r = n.shouldExecuteOnCPU(e);
if (s === "string" && (r = true), r) {
let h = e.map((x) => {
let k = w.sizeFromShape(x.shape.slice(t));
return Le({ inputs: { x }, backend: n, attrs: { shape: [-1, k] } });
}), f = h.map((x) => ({ vals: n.readSync(x.dataId), shape: x.shape })), m = C.computeOutShape(h.map((x) => x.shape), 1), g = h[0].shape[0] === 1, b = kse(f, m, s, g), y = C.computeOutShape(e.map((x) => x.shape), t), v = n.makeTensorInfo(y, s, b);
return h.forEach((x) => n.disposeData(x.dataId)), v;
}
let { tensors2D: a, outShape: o } = Fre(e, t, n), i = a.map((h) => h.shape), u = new Rre(i), l = [], c = new Array(i.length - 1);
if (c.length > 0) {
c[0] = i[0][1], l.push({ type: "int32", data: [c[0]] });
for (let h = 1; h < c.length; h++)
c[h] = c[h - 1] + i[h][1], l.push({ type: "int32", data: [c[h]] });
}
let p = n.runWebGPUProgram(u, a, a[0].dtype, l);
a.forEach((h) => n.disposeData(h.dataId));
let d = Le({ inputs: { x: p }, backend: n, attrs: { shape: o } });
return n.disposeData(p.dataId), d;
}
function Fre(e, t, n) {
let s = C.computeOutShape(e.map((a) => a.shape), t);
return { tensors2D: e.map((a) => Le({ inputs: { x: a }, backend: n, attrs: { shape: [w.sizeFromShape(a.shape.slice(0, t)), w.sizeFromShape(a.shape.slice(t))] } })), outShape: s };
}
function G2(e) {
let { inputs: t, backend: n, attrs: s } = e, { axis: r } = s, a = w.parseAxisParam(r, t[0].shape)[0], o = C.computeOutShape(t.map((l) => l.shape), a);
if (w.sizeFromShape(o) === 0)
return n.makeTensorInfo(o, t[0].dtype, []);
let i = t.filter((l) => w.sizeFromShape(l.shape) > 0);
if (i.length === 1)
return Un({ inputs: { x: i[0] }, backend: n });
let u = i.map((l) => l.shape);
return C.assertParamsConsistent(u, a), ig(i, a, n);
}
var Ore = { kernelName: hi, backendName: "webgpu", kernelFunc: G2 };
var nr = (e) => {
switch (e) {
case 1:
return "f32";
case 2:
return "vec2<f32>";
case 3:
return "vec3<f32>";
case 4:
return "vec4<f32>";
default:
throw new Error(`innerElementSize ${e} is not supported.`);
}
};
function Pre(e, t, n, s, r = false, a = null, o = false, i = 4, u = 4, l = 4) {
let c = (D) => {
switch (D) {
case 1:
return "resData = x[xIndex];";
case 3:
return "resData = vec3<f32>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);";
case 4:
return "resData = x[xIndex / 4];";
default:
throw new Error(`innerElementSize ${D} is not supported.`);
}
}, p = (D) => {
switch (D) {
case 1:
return "return W[row * uniforms.wShape[3] + colIn];";
case 4:
return "return W[row * uniforms.wShape[3] / 4 + colIn];";
default:
throw new Error(`innerElementSize ${D} is not supported.`);
}
}, d = e ? `
let coord = vec4<i32>(batch, xRow, xCol, xCh);
` : `
let coord = vec4<i32>(batch, xCh, xRow, xCol);
`, h = e ? `
let outCoord = vec4<i32>(
batch,
row / outWidth,
row % outWidth,
col);
` : `
let outCoord = vec4<i32>(
batch,
row,
col / outWidth,
col % outWidth);
`, f = e ? "uniforms.xShape[1]" : "uniforms.xShape[2]", m = e ? "uniforms.xShape[2]" : "uniforms.xShape[3]", g = e ? "row" : "col", b = e ? "col" : "row", y = `
let inChannels = uniforms.wShape[2];
let outWidth = ${e ? "uniforms.outShape[2]" : "uniforms.outShape[3]"};
let outRow = ${g} / outWidth;
let outCol = ${g} % outWidth;
let WRow = ${b} / (uniforms.filterDims[1] * inChannels);
let WCol = ${b} / inChannels % uniforms.filterDims[1];
let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];
let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];
let xCh = ${b} % inChannels;
var resData = ${nr(i)}(0.0);
// The bounds checking is always needed since we use it to pad zero for
// the 'same' padding type.
if (xRow >= 0 && xRow < ${f} && xCol >= 0 && xCol < ${m}) {
${d}
let xIndex = getIndexFromCoords4D(coord, uniforms.xShape);
${c(i)}
}
return resData;`, v = e ? t && s ? `
let col = colIn * ${i};
${y}` : `
let col = colIn * ${i};
if (row < uniforms.dimAOuter && col < uniforms.dimInner) {
${y}
}
return ${nr(i)}(0.0);` : s && n ? `
let col = colIn * ${i};
${y}` : `
let col = colIn * ${i};
if (row < uniforms.dimInner && col < uniforms.dimBOuter) {
${y}
}
return ${nr(i)}(0.0);`, x = `${p(u)}`, k = nr(l), I = nr(e ? i : u), $ = nr(e ? u : i), R = "", E = "";
if (a) {
let D = Io(a, l === 4);
o ? R = `fn activation(a: ${k}, outCoord : vec4<i32>) -> ${k} {
let b = getPreluActivationWeightsByOutputCoords(outCoord);
${D}
}` : R = `
fn activation(a : ${k}, outCoord : vec4<i32>) -> ${k} {
${D}
}`, E = "value = activation(value, outCoord);";
}
return `
${R}
fn mm_readA(row : i32, colIn : i32, globalId : vec3<u32>) -> ${I} {
var batch = i32(globalId.z);
${e ? v : x}
}
fn mm_readB(row : i32, colIn : i32, globalId : vec3<u32>) -> ${$} {
var batch = i32(globalId.z);
${e ? x : v}
}
fn mm_write(row : i32, colIn : i32, valueIn : ${k}, globalId : vec3<u32>) {
var col = colIn * ${l};
if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)
{
var batch = i32(globalId.z);
var value = valueIn;
let outWidth = ${e ? "uniforms.outShape[2]" : "uniforms.outShape[3]"};
${h}
${r ? "value = value + getBiasByOutputCoords(outCoord);" : ""}
${E}
setOutputAtCoords(outCoord[0], outCoord[1], outCoord[2], outCoord[3], value);
}
}`;
}
var zre = class {
constructor(e, t, n, s, r = false, a = null, o = false, i = false) {
this.variableNames = ["x", "W"], this.uniforms = "filterDims : vec2<i32>, pad : vec2<i32>, stride : vec2<i32>, dilation : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32,", this.outputShape = e.outShape, this.isChannelsLast = e.dataFormat === "channelsLast", this.isVec4 = i, this.dispatchLayout = this.isChannelsLast ? { x: [3], y: [1, 2], z: [0] } : { x: [2, 3], y: [1], z: [0] }, this.workGroupSize = Ov(this.dispatchLayout, this.outputShape, this.isVec4), this.elementsPerThread = Pv(this.dispatchLayout, this.outputShape, this.isVec4), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize, this.elementsPerThread), this.innerElementSize = this.isVec4 ? e.inChannels % 4 === 0 ? 4 : 3 : this.elementsPerThread[0], this.isVec4 && (this.variableTypes = this.innerElementSize === 3 ? ["f32", "vec4<f32>"] : ["vec4<f32>", "vec4<f32>"]), r && (this.variableNames.push("bias"), this.isVec4 && this.variableTypes.push("vec4<f32>")), o && (this.variableNames.push("preluActivationWeights"), this.isVec4 && this.variableTypes.push("vec4<f32>")), this.addBias = r, this.activation = a, this.hasPreluActivationWeights = o, this.tileAOuter = this.workGroupSize[1] * this.elementsPerThread[1], this.tileBOuter = this.workGroupSize[0] * this.elementsPerThread[0], this.tileInner = Math.max(this.workGroupSize[0] * this.innerElementSize, this.workGroupSize[1]), this.fitAOuter = t % this.tileAOuter === 0, this.fitBOuter = n % this.tileBOuter === 0, this.fitInner = s % this.tileInner === 0, this.shaderKey = `conv2DMM_${this.elementsPerThread}_${this.activation}}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.isVec4}_${this.innerElementSize}_${this.isChannelsLast}`;
}
getUserCode() {
let e = this.isVec4 ? z2(this.elementsPerThread, this.tileAOuter, this.tileBOuter, this.tileInner, this.innerElementSize, !this.isChannelsLast) : Mv(this.elementsPerThread, this.workGroupSize, !this.isChannelsLast, this.tileInner), t = this.isVec4 ? [this.isChannelsLast ? this.innerElementSize : 4, 4, 4] : [1, 1, 1];
return `
${Pre(this.isChannelsLast, this.fitAOuter, this.fitBOuter, this.fitInner, this.addBias, this.activation, this.hasPreluActivationWeights, t[0], t[1], t[2])}
${e}
`;
}
};
function Gw(e, t) {
let n = e.length;
return n >= 3 ? t ? [...e.slice(0, -3), e[n - 3] * e[n - 2], e[n - 1]] : [...e.slice(0, -3), e[n - 3], e[n - 2] * e[n - 1]] : !t && n === 1 && e[0] > 1 ? [e[0], 1] : null;
}
function Lre({ x: e, filter: t, convInfo: n, backend: s, bias: r = null, preluActivationWeights: a = null, leakyreluAlpha: o = 0, activation: i = null }) {
let u = n.dataFormat === "channelsLast", l = !u, c = false, p = u && n.filterHeight === n.inHeight && n.filterWidth === n.inWidth && n.padInfo.type === "VALID", d = [], h, f;
if (p) {
let b = n.inHeight * n.inWidth * n.inChannels;
h = Le({ inputs: { x: e }, backend: s, attrs: { shape: [1, n.batchSize, b] } }), f = Le({ inputs: { x: t }, backend: s, attrs: { shape: [1, b, n.outChannels] } });
} else
h = Le({ inputs: { x: e }, backend: s, attrs: { shape: u ? [n.batchSize, n.inHeight * n.inWidth, n.inChannels] : [n.batchSize, n.inChannels, n.inHeight * n.inWidth] } }), f = Le({ inputs: { x: t }, backend: s, attrs: { shape: [1, n.inChannels, n.outChannels] } });
if (d.push(h), d.push(f), a != null) {
let b = Gw(a.shape, u);
b != null && (a = Le({ inputs: { x: a }, backend: s, attrs: { shape: b } }), d.push(a));
}
if (r != null) {
let b = Gw(r.shape, u);
b != null && (r = Le({ inputs: { x: r }, backend: s, attrs: { shape: b } }), d.push(r));
}
let m = Bv({ a: u ? h : f, b: u ? f : h, transposeA: l, transposeB: c, backend: s, bias: r, activation: i, preluActivationWeights: a, leakyreluAlpha: o }), g = Le({ inputs: { x: m }, backend: s, attrs: { shape: n.outShape } });
d.push(m);
for (let b of d)
s.disposeData(b.dataId);
return g;
}
function H2({ x: e, filter: t, convInfo: n, backend: s, bias: r = null, preluActivationWeights: a = null, leakyreluAlpha: o = 0, activation: i = null }) {
let u = r != null, l = a != null, c = n.dataFormat === "channelsLast";
if (c && n.filterHeight === n.inHeight && n.filterWidth === n.inWidth && n.padInfo.type === "VALID" || n.filterHeight === 1 && n.filterWidth === 1 && n.dilationHeight === 1 && n.dilationWidth === 1 && n.strideHeight === 1 && n.strideWidth === 1 && (n.padInfo.type === "SAME" || n.padInfo.type === "VALID"))
return Lre({ x: e, filter: t, convInfo: n, backend: s, bias: r, activation: i, preluActivationWeights: a, leakyreluAlpha: o });
let d = ((n.inChannels % 4 === 0 || n.inChannels % 3 === 0) && c || n.outWidth % 4 === 0 && !c) && n.outChannels % 4 === 0, h = c ? n.outHeight * n.outWidth : n.outChannels, f = c ? n.outChannels : n.outHeight * n.outWidth, m = n.filterHeight * n.filterWidth * n.inChannels, g = [n.padInfo.top, n.padInfo.left], b = [{ type: "int32", data: [n.filterHeight, n.filterWidth] }, { type: "int32", data: [...g] }, { type: "int32", data: [n.strideHeight, n.strideWidth] }, { type: "int32", data: [n.dilationHeight, n.dilationWidth] }, { type: "int32", data: [h] }, { type: "int32", data: [f] }, { type: "int32", data: [m] }], y = new zre(n, h, f, m, u, i, l, d), v = [], x = [e, t];
u && (!c && r.shape.length === 1 && (r = Le({ inputs: { x: r }, backend: s, attrs: { shape: [r.shape[0], 1, 1] } }), v.push(r)), x.push(r)), l && (!c && a.shape.length === 1 && (a = Le({ inputs: { x: a }, backend: s, attrs: { shape: [a.shape[0], 1, 1] } }), v.push(a)), x.push(a)), i === "leakyrelu" && (b.push({ type: "float32", data: [o] }), y.uniforms += " alpha : f32,");
let k = s.runWebGPUProgram(y, x, e.dtype, b);
for (let I of v)
s.disposeData(I.dataId);
return k;
}
function Mre(e) {
let { inputs: t, attrs: n, backend: s } = e, { x: r, filter: a } = t, { strides: o, pad: i, dataFormat: u, dilations: l, dimRoundingMode: c } = n, p = C.convertConv2DDataFormat(u), d = C.computeConv2DInfo(r.shape, a.shape, o, l, i, c, false, p);
return H2({ x: r, filter: a, convInfo: d, backend: s });
}
var Bre = { kernelName: _a, backendName: "webgpu", kernelFunc: Mre };
var Vre = class {
constructor(e) {
this.variableNames = ["x", "W"], this.uniforms = "filterDims : vec2<i32>, pads : vec2<i32>, stride : vec2<i32>, outBackprop : vec4<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32,", this.outputShape = e.inShape, w.assert(e.dataFormat === "channelsLast", () => "TODO: NCHW is unimplemented"), this.dispatchLayout = { x: [3], y: [1, 2], z: [0] }, this.workGroupSize = Ov(this.dispatchLayout, this.outputShape), this.elementsPerThread = Pv(this.dispatchLayout, this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize, this.elementsPerThread), this.shaderKey = `conv2DDerInputMM_${this.elementsPerThread}`;
}
getUserCode() {
return `
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
var batch = i32(globalId.z);
if (row < uniforms.dimAOuter && col < uniforms.dimInner) {
let outRow = row / uniforms.outShape[2];
let outCol = row % uniforms.outShape[2];
let WRow = col / (uniforms.filterDims[1] * uniforms.outBackprop[3]);
let WCol = col / uniforms.outBackprop[3] % uniforms.filterDims[1];
let xR = f32(outRow - uniforms.pads[0] + WRow) / f32(uniforms.stride[0]);
let xC = f32(outCol - uniforms.pads[1] + WCol) / f32(uniforms.stride[1]);
if (xR < 0.0 || xR >= f32(uniforms.outBackprop[1]) || fract(xR) > 0.0) {
return 0.0;
}
if (xC < 0.0 || xC >= f32(uniforms.outBackprop[2]) || fract(xC) > 0.0) {
return 0.0;
}
let coord = vec4<i32>(
batch,
i32(xR),
i32(xC),
col % uniforms.outBackprop[3]);
return x[getIndexFromCoords4D(coord, uniforms.xShape)];
}
return 0.0;
}
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
let coordX = uniforms.filterDims.x - 1 -
row / (uniforms.filterDims[1] * uniforms.outBackprop[3]);
let coordY = uniforms.filterDims.y - 1 -
(row / uniforms.outBackprop[3]) % uniforms.filterDims[1];
if (row < uniforms.dimInner && col < uniforms.dimBOuter &&
coordX >= 0 && coordY >= 0) {
let coord = vec4<i32>(coordX, coordY, col,
row % uniforms.outBackprop[3]);
return W[getIndexFromCoords4D(coord, uniforms.wShape)];
}
return 0.0;
}
fn mm_write(row : i32, col : i32, valueInput : f32, globalId : vec3<u32>) {
if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)
{
var batch = i32(globalId.z);
var value = valueInput;
let outCoord = vec4<i32>(
batch,
row / uniforms.outShape[2],
row % uniforms.outShape[2],
col);
result[getIndexFromCoords4D(outCoord, uniforms.outShape)] = value;
}
}
${Mv(this.elementsPerThread, this.workGroupSize)}
`;
}
};
var Wre = class {
constructor(e) {
this.variableNames = ["dy", "W"], this.uniforms = "filterDims : vec2<i32>, pads : vec2<i32>, stride : vec2<i32>, outBackprop : vec4<i32>,", this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = e.inShape, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.isChannelsLast = e.dataFormat === "channelsLast", this.shaderKey = `conv2DDerInput_${this.isChannelsLast}`;
}
getUserCode() {
let e = this.isChannelsLast ? 1 : 2, t = this.isChannelsLast ? 2 : 3, n = this.isChannelsLast ? 3 : 1;
return `
${Ue()} {
if(index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let batch = coords[0];
let d1 = coords[${n}];
let dyCorner = vec2<i32>(coords[${e}]), coords[${t}]) - uniforms.pads;
let dyRCorner = dyCorner.x;
let dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
var dotProd = 0.0;
for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + 1) {
let dyR = (f32(dyRCorner) + f32(wR)) / f32(uniforms.stride.x);
let wRPerm = uniforms.filterDims.x - 1 - wR;
if (dyR < 0.0 || dyR >= f32(uniforms.outBackprop[1]) || fract(dyR) > 0.0 ||
wRPerm < 0) {
continue;
}
let idyR = dyR;
for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + 1) {
let dyC = (f32(dyCCorner) + f32(wC)) / f32(uniforms.stride.y);
let wCPerm = uniforms.filterDims.y - 1 - wC;
if (dyC < 0.0 || dyC >= f32(uniforms.outBackprop[2]) ||
fract(dyC) > 0.0 || wCPerm < 0) {
continue;
}
let idyC = dyC;
for (var d2 = 0; d2 < uniforms.outBackprop[3]; d2 = d2 + 1) {
if (${this.isChannelsLast}) {
let xValue = getDy(batch, idyR, idyC, d2);
let wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd = dotProd + xValue * wValue;
} else {
let xValue = getDy(batch, d2, idyR, idyC);
let wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd = dotProd + xValue * wValue;
}
}
}
}
setOutputAtIndex(index, dotProd);
}
}
`;
}
};
function Ure(e) {
let { inputs: t, backend: n, attrs: s } = e, { dy: r, filter: a } = t, { inputShape: o, strides: i, pad: u, dataFormat: l, dimRoundingMode: c } = s, p = C.convertConv2DDataFormat(l), d = C.computeConv2DInfo(o, a.shape, i, 1, u, c, false, p), h = [{ type: "int32", data: [d.filterHeight, d.filterWidth] }, { type: "int32", data: [d.filterHeight - 1 - d.padInfo.top, d.filterWidth - 1 - d.padInfo.left] }, { type: "int32", data: [d.strideHeight, d.strideWidth] }, { type: "int32", data: [d.batchSize, d.outHeight, d.outWidth, d.outChannels] }], f;
if (K().getBool("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE"))
f = new Wre(d);
else {
f = new Vre(d);
let m = d.inShape[1] * d.inShape[2], g = d.inShape[3], b = d.filterHeight * d.filterWidth * d.outChannels;
h.push({ type: "uint32", data: [m] }, { type: "uint32", data: [g] }, { type: "uint32", data: [b] });
}
return n.runWebGPUProgram(f, [r, a], "float32", h);
}
var Gre = { kernelName: Aa, backendName: "webgpu", kernelFunc: Ure };
var Hre = Kt({ opType: 2 });
var qre = { kernelName: Ea, backendName: "webgpu", kernelFunc: Hre };
var jre = Kt({ opType: 3 });
var Kre = { kernelName: Ra, backendName: "webgpu", kernelFunc: jre };
var Xre = class {
constructor(e, t, n, s) {
this.variableNames = ["Image", "Boxes", "BoxInd"], this.uniforms = "extrapolationValue : f32,", this.workGroupSize = [64, 1, 1], this.size = true;
let [r] = t;
this.outputShape = [r, n[0], n[1], e], this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.methodId = s === "bilinear" ? 1 : 0, this.cropHeightBiggerThan1 = this.outputShape[1] > 1, this.cropWidthBiggerThan1 = this.outputShape[2] > 1, this.shaderKey = `cropAndResize_${this.methodId}_${this.cropHeightBiggerThan1}_${this.cropWidthBiggerThan1}`;
}
getUserCode() {
let [e, t] = ["f32(uniforms.imageShape[1] - 1)", "f32(uniforms.imageShape[2] - 1)"], [n, s, r] = this.cropHeightBiggerThan1 ? [`(${e} / f32(uniforms.outShape[1] - 1))`, "(y2-y1) * height_ratio", `y1*${e} + f32(y)*(height_scale)`] : ["0.0", "0.0", `0.5 * (y1+y2) * ${e}`], [a, o, i] = this.cropWidthBiggerThan1 ? [`(${t} / f32(uniforms.outShape[2] - 1))`, "(x2-x1) * width_ratio", `x1*${t} + f32(x)*(width_scale)`] : ["0.0", "0.0", `0.5 * (x1+x2) * ${t}`];
return `
${Ue()}
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let height_ratio = f32(${n});
let width_ratio = f32(${a});
let b = coords[0];
let y = coords[1];
let x = coords[2];
let d = coords[3];
// get box vals
let y1 = getBoxes(b, 0);
let x1 = getBoxes(b, 1);
let y2 = getBoxes(b, 2);
let x2 = getBoxes(b, 3);
// get image in batch index
let bInd = i32(round(getBoxInd(b)));
if(bInd < 0 || bInd >= uniforms.outShape[0]) {
return;
}
let height_scale = ${s};
let width_scale = ${o};
let in_y = ${r};
if( in_y < 0.0 || in_y > ${e} ) {
setOutputAtIndex(index, uniforms.extrapolationValue);
return;
}
let in_x = ${i};
if( in_x < 0.0 || in_x > ${t} ) {
setOutputAtIndex(index, uniforms.extrapolationValue);
return;
}
let sourceFracIndexCR = vec2<f32>(in_x,in_y);
if(${this.methodId} == 1) {
// Compute the four integer indices.
let sourceFloorCR = vec2<i32>(sourceFracIndexCR);
let sourceCeilCR = vec2<i32>(ceil(sourceFracIndexCR));
let topLeft = getImage(bInd, sourceFloorCR.y, sourceFloorCR.x, d);
let bottomLeft = getImage(bInd, sourceCeilCR.y, sourceFloorCR.x, d);
let topRight = getImage(bInd, sourceFloorCR.y, sourceCeilCR.x, d);
let bottomRight = getImage(bInd, sourceCeilCR.y, sourceCeilCR.x, d);
let fracCR = sourceFracIndexCR - vec2<f32>(sourceFloorCR);
let top = topLeft + (topRight - topLeft) * fracCR.x;
let bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
let newValue = top + (bottom - top) * fracCR.y;
setOutputAtIndex(index, newValue);
} else {
// Compute the coordinators of nearest neighbor point.
let sourceNearestCR = vec2<i32>(floor(
sourceFracIndexCR + vec2<f32>(0.5,0.5)));
let newValue = getImage(
bInd, sourceNearestCR.y, sourceNearestCR.x, d);
setOutputAtIndex(index, newValue);
}
}
}
`;
}
};
var Yre = (e) => {
let { inputs: t, backend: n, attrs: s } = e, { image: r, boxes: a, boxInd: o } = t, { cropSize: i, method: u, extrapolationValue: l } = s, c = new Xre(r.shape[3], a.shape, i, u), p = [{ type: "float32", data: [l] }];
return n.runWebGPUProgram(c, [r, a, o], "float32", p);
};
var Qre = { kernelName: mi, backendName: "webgpu", kernelFunc: Yre };
var Hw = class {
constructor(e, t, n, s) {
this.variableNames = ["x"], this.uniforms = "index : f32,", this.size = true;
let r = 128;
this.workGroupSize = [r, 1, 1], this.outputShape = t, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.exclusive = n, this.reverse = s, this.op = e, this.shaderKey = `cum_${this.op}_${this.exclusive}_${this.reverse}`;
}
getUserCode() {
let e = this.outputShape.length, t = this.op === "*" ? "1.0" : "0.0", n = this.exclusive ? t : `getX(${qw(e, "coords", this.op)})`, s = this.outputShape[this.outputShape.length - 1], r = "", a = "";
return this.exclusive ? (r = this.reverse ? `end != ${s - 1}` : "end != 0", a = this.reverse ? "end + 1" : "end - 1") : (r = this.reverse ? `end + pow2 < ${s}` : "end >= pow2", a = this.reverse ? "end + pow2" : "end - pow2"), `
${Ue()}
if (index < uniforms.size) {
var coords = getCoordsFromIndex(index);
let end = ${jw(e, "coords", this.op)};
var val = ${n};
let pow2 = i32(pow(2.0, uniforms.index));
if (${r}) {
let idx = ${a};
${jw(e, "coords", this.op)} = idx;
val ${this.op}= getX(${qw(e, "coords", this.op)});
}
setOutputAtIndex(index, val);
}
}
`;
}
};
function qw(e, t, n) {
if (e === 1)
return `${t}`;
if (e === 2)
return `${t}.x, ${t}.y`;
if (e === 3)
return `${t}.x, ${t}.y, ${t}.z`;
if (e === 4)
return `${t}.x, ${t}.y, ${t}.z, ${t}.w`;
throw Error(`Cumulative ${n} for rank ${e} is not yet supported`);
}
function jw(e, t, n) {
if (e === 1)
return `${t}`;
if (e === 2)
return `${t}.y`;
if (e === 3)
return `${t}.z`;
if (e === 4)
return `${t}.w`;
throw Error(`Cumulative ${n} for rank ${e} is not yet supported`);
}
function q2(e, t, n, s, r, a) {
let o = t.shape.length, i = C.getAxesPermutation([s], o), u = t;
i != null && (u = Ks({ inputs: { x: t }, backend: n, attrs: { perm: i } }));
let l = C.getInnerMostAxes(1, o)[0];
if (l !== o - 1)
throw new Error(`WebGPU cumprod shader expects an inner-most axis=${t.shape.length - 1} but got axis=${s}`);
let c = u.shape[l], p = Un({ inputs: { x: u }, backend: n });
for (let d = 0; d <= Math.ceil(Math.log2(c)) - 1; d++) {
let h = new Hw(e, u.shape, false, a), f = p, m = [{ type: "float32", data: [d] }];
p = n.runWebGPUProgram(h, [p], p.dtype, m), n.disposeData(f.dataId);
}
if (r) {
let d = new Hw(e, u.shape, r, a), h = p, f = [{ type: "float32", data: [0] }];
p = n.runWebGPUProgram(d, [p], p.dtype, f), n.disposeData(h.dataId);
}
if (i != null) {
let d = C.getUndoAxesPermutation(i), h = Ks({ inputs: { x: p }, backend: n, attrs: { perm: d } });
return n.disposeData(p.dataId), n.disposeData(u.dataId), h;
}
return p;
}
function Zre(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, exclusive: o, reverse: i } = s;
return q2("*", r, n, a, o, i);
}
var Jre = { kernelName: fi, backendName: "webgpu", kernelFunc: Zre };
function eae(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, exclusive: o, reverse: i } = s;
return q2("+", r, n, a, o, i);
}
var tae = { kernelName: Da, backendName: "webgpu", kernelFunc: eae };
var nae = class {
constructor(e, t) {
this.variableNames = ["x"], this.workGroupSize = [64, 1, 1], this.size = true, this.uniforms = "blockSize : i32,", this.outputShape = e, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.shaderKey = `depthToSpace_${t}`, this.dataFormat = t;
}
getUserCode() {
return `
${Ue()}
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let b = coords[0];
let h = ${this.getHeightCoordString()};
let w = ${this.getWidthCoordString()};
let d = ${this.getDepthCoordString()};
let in_h = h / uniforms.blockSize;
let offset_h = h % uniforms.blockSize;
let in_w = w / uniforms.blockSize;
let offset_w = w % uniforms.blockSize;
let offset_d = (offset_h * uniforms.blockSize + offset_w) *
${this.getOutputDepthSize()};
let in_d = d + offset_d;
let rlt = ${this.getInputSamplingString()};
setOutputAtIndex(index, rlt);
}
}`;
}
getHeightCoordString() {
return this.dataFormat === "NHWC" ? "coords[1]" : "coords[2]";
}
getWidthCoordString() {
return this.dataFormat === "NHWC" ? "coords[2]" : "coords[3]";
}
getDepthCoordString() {
return this.dataFormat === "NHWC" ? "coords[3]" : "coords[1]";
}
getOutputDepthSize() {
return this.dataFormat === "NHWC" ? "uniforms.outShape[3]" : "uniforms.outShape[1]";
}
getInputSamplingString() {
return this.dataFormat === "NHWC" ? "getX(b, in_h, in_w, in_d)" : "getX(b, in_d, in_h, in_w)";
}
};
function sae(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { blockSize: a, dataFormat: o } = s, i = r.shape[0], u = o === "NHWC" ? r.shape[1] : r.shape[2], l = o === "NHWC" ? r.shape[2] : r.shape[3], c = o === "NHWC" ? r.shape[3] : r.shape[1], p = u * a, d = l * a, h = c / (a * a), f = o === "NHWC" ? [i, p, d, h] : [i, h, p, d], m = [{ type: "int32", data: [a] }], g = new nae(f, o);
return n.runWebGPUProgram(g, [r], r.dtype, m);
}
var rae = { kernelName: gi, backendName: "webgpu", kernelFunc: sae };
var j2 = class {
constructor(e, t = false, n = null, s = false) {
this.variableNames = ["x", "W"], this.uniforms = "pad : vec2<i32>, stride : vec2<i32>, dilation : vec2<i32>, inDims : vec2<i32>,", this.workGroupSize = [4, 4, 4], this.isVec4 = true, this.outputShape = e.outShape, this.dispatchLayout = { x: [0, 1], y: [2], z: [3] }, this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize, [1, 4, 4]), w.assert(e.dataFormat === "channelsLast", () => "TODO: NCHW is unimplemented"), t && this.variableNames.push("bias"), s && this.variableNames.push("preluActivationWeights"), this.convInfo = e, this.addBias = t, this.activation = n, this.hasPreluActivation = s, this.shaderKey = `depthwise3x3_${n}`;
}
getUserCode() {
let e = "", t = "";
if (this.activation) {
let r = Io(this.activation, this.isVec4);
this.hasPreluActivation ? e = `fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
let b = getPreluActivationWeightsByOutputCoords(outCoord);
${r}
}` : e = `
fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
${r}
}
`, t = "dotProd[i] = activation(dotProd[i], coords);";
}
let n = this.addBias ? "dotProd[i] = dotProd[i] + getBiasByOutputCoords(coords);" : "";
return `
${e}
${Lv()}
fn main(@builtin(global_invocation_id) globalId: vec3<u32>) {
let batch = 0;
let r = i32(globalId.x);
let c = i32(globalId.y) * 4;
let d2 = i32(globalId.z) * 4;
let xRCCorner = vec2<i32>(r, c) * uniforms.stride - uniforms.pad;
let d1 = d2;
let q = 0;
let xRCorner = xRCCorner.x;
let xCCorner = xRCCorner.y;
var wVals : array<vec4<f32>, 9>;
wVals[0] = getW(0, 0, d1, q);
wVals[1] = getW(0, 1, d1, q);
wVals[2] = getW(0, 2, d1, q);
wVals[3] = getW(1, 0, d1, q);
wVals[4] = getW(1, 1, d1, q);
wVals[5] = getW(1, 2, d1, q);
wVals[6] = getW(2, 0, d1, q);
wVals[7] = getW(2, 1, d1, q);
wVals[8] = getW(2, 2, d1, q);
var xVals : array<array<vec4<f32>, 6>, 3>;
for (var wR = 0; wR < 3; wR = wR + 1) {
let xR = xRCorner + wR * uniforms.dilation[0];
for (var wC = 0; wC < 6; wC = wC + 1) {
let xC = xCCorner + wC * uniforms.dilation[1];
if (xR < 0 || xR >= uniforms.inDims[0] || xC < 0 || xC >= uniforms.inDims[1]) {
xVals[wR][wC] = vec4<f32>(0.0);
} else {
xVals[wR][wC] = getX(batch, xR, xC, d1);
}
}
}
var dotProd : array<vec4<f32>, 4>;
dotProd[0] = vec4<f32>(0.0);
dotProd[1] = vec4<f32>(0.0);
dotProd[2] = vec4<f32>(0.0);
dotProd[3] = vec4<f32>(0.0);
for (var wR = 0; wR < 3; wR = wR + 1) {
for (var wC = 0; wC < 3; wC = wC + 1) {
let indexW = wR * 3 + wC;
dotProd[0] = dotProd[0] + xVals[wR][0 + wC] * wVals[indexW];
dotProd[1] = dotProd[1] + xVals[wR][1 + wC] * wVals[indexW];
dotProd[2] = dotProd[2] + xVals[wR][2 + wC] * wVals[indexW];
dotProd[3] = dotProd[3] + xVals[wR][3 + wC] * wVals[indexW];
}
}
for (var i = 0; i < 4; i = i + 1) {
let coords = vec4<i32>(batch, r, c + i, d2);
if (coordsInBounds4D(coords, uniforms.outShape)) {
${n}
${t}
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], dotProd[i]);
}
}
}
`;
}
};
var K2 = class {
constructor(e, t = false, n = null, s = false) {
this.variableNames = ["x", "W"], this.uniforms = `pad : vec2<i32>, stride : vec2<i32>, dilation : vec2<i32>,
inDims : vec2<i32>, filterHeight : i32, filterWidth : i32,
channelMul : i32,`, this.workGroupSize = [256, 1, 1], this.outputShape = e.outShape, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), w.assert(e.dataFormat === "channelsLast", () => "TODO: NCHW is unimplemented"), t && this.variableNames.push("bias"), s && this.variableNames.push("preluActivationWeights"), this.convInfo = e, this.addBias = t, this.activation = n, this.hasPreluActivation = s, this.shaderKey = `depthwise_${this.activation}`;
}
getUserCode() {
let e = "", t = "";
if (this.activation) {
let r = Io(this.activation, false);
this.hasPreluActivation ? e = `fn activation(a : f32, outCoord : vec4<i32>) -> f32 {
let b = getPreluActivationWeightsByOutputCoords(outCoord);
${r}
}` : e = `
fn activation(a : f32, outCoord : vec4<i32>) -> f32 {
${r}
}
`, t = "dotProd = activation(dotProd, coords);";
}
let n = this.addBias ? "dotProd = dotProd + getBiasByOutputCoords(coords);" : "";
return `
${e}
fn writeResult(batch : i32, row : i32, col : i32, chan : i32,
value : f32) {
let coord = vec4<i32>(batch, row, col, chan);
if (coordsInBounds4D(coord, uniforms.outShape)) {
setOutputAtCoords(batch, row, col, chan, value);
}
}
${ac()}
let coords = getOutputCoords();
let batch = coords[0];
let xRCCorner = vec2<i32>(coords.yz) * uniforms.stride - uniforms.pad;
let d2 = coords[3];
let d1 = d2 / uniforms.channelMul;
let q = d2 - d1 * uniforms.channelMul;
let inputRowStart = xRCCorner.x;
let inputColStart = xRCCorner.y;
let inputRowEnd = inputRowStart + uniforms.filterHeight *
uniforms.dilation[0];
let inputColEnd = inputColStart + uniforms.filterWidth *
uniforms.dilation[1];
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
var dotProd = 0.0;
// Extract if checking out of for loop for performance.
if (inputRowStart >= 0 && inputColStart >= 0 &&
inputRowEnd < uniforms.inDims[0] &&
inputColEnd < uniforms.inDims[1]) {
// Here using a constant value |this.convInfo.filterHeight| instead
// of uniform value is in order to loop unrolling.
for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) {
let xR = inputRowStart + wR * uniforms.dilation[0];
for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) {
let xC = inputColStart + wC * uniforms.dilation[1];
let xVal = getX(batch, xR, xC, d1);
let wVal = getW(wR, wC, d1, q);
dotProd = dotProd + xVal * wVal;
}
}
} else {
for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) {
let xR = inputRowStart + wR * uniforms.dilation[0];
if (xR < 0 || xR >= uniforms.inDims[0]) {
continue;
}
for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) {
let xC = inputColStart + wC * uniforms.dilation[1];
if (xC < 0 || xC >= uniforms.inDims[1]) {
continue;
}
let xVal = getX(batch, xR, xC, d1);
let wVal = getW(wR, wC, d1, q);
dotProd = dotProd + xVal * wVal;
}
}
}
${n}
${t}
writeResult(batch, coords[1], coords[2], d2, dotProd);
}
`;
}
};
function aae(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, filter: a } = t, { strides: o, pad: i, dilations: u, dimRoundingMode: l } = s, c = u;
c == null && (c = [1, 1]);
let p = C.computeConv2DInfo(r.shape, a.shape, o, c, i, l, true), d = [{ type: "int32", data: [p.padInfo.top, p.padInfo.left] }, { type: "int32", data: [p.strideHeight, p.strideWidth] }, { type: "int32", data: [p.dilationHeight, p.dilationWidth] }, { type: "int32", data: [p.inHeight, p.inWidth] }], h;
return p.batchSize === 1 && p.inHeight === p.outHeight && p.inWidth === p.outWidth && p.strideHeight === 1 && p.strideWidth === 1 && p.filterHeight === p.filterWidth && p.inChannels === p.outChannels && p.dilationHeight === 1 && p.dilationWidth === 1 && p.filterHeight === 3 && p.inChannels % 4 === 0 ? h = new j2(p) : (h = new K2(p), d.push({ type: "int32", data: [p.filterHeight] }, { type: "int32", data: [p.filterWidth] }, { type: "int32", data: [p.outChannels / p.inChannels] })), n.runWebGPUProgram(h, [r, a], r.dtype, d);
}
var oae = { kernelName: Fa, backendName: "webgpu", kernelFunc: aae };
var X2 = gn({ opSnippet: 0, cpuKernelImpl: zse, supportsComplex: true });
var iae = { kernelName: Za, backendName: "webgpu", kernelFunc: X2 };
var uae = class {
constructor(e, t) {
this.workGroupSize = [64, 1, 1], this.variableNames = ["x"], this.uniforms = "reduceSize : i32,", this.size = true, this.inputShape = [e.batchSize, e.inSize];
let [n] = C.computeOutAndReduceShapes(this.inputShape, [1]);
this.outputShape = n.length === 0 ? [1] : n, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, [1, 1, 1]), this.reduceType = t, this.shaderKey = `reduce_${t}`;
}
getUserCode() {
let e = "", t = "0.0";
this.reduceType === "min" || this.reduceType === "max" ? (e = `
if (isnan(candidate)) {
bestValue = uniforms.NAN;
} else if (!isnan(bestValue) && candidate ${this.reduceType === "min" ? "<" : ">"} bestValue)
{ bestValue = candidate; }`, t = "f32(x[offset])") : this.reduceType === "sum" || this.reduceType === "mean" ? e = " bestValue = bestValue + candidate; " : this.reduceType === "prod" && (e = " bestValue = bestValue * candidate; ", t = "1.0");
let n = this.reduceType === "mean" ? "setOutputAtIndex(outputIndex, bestValue / f32(uniforms.reduceSize));" : "setOutputAtIndex(outputIndex, bestValue);";
return `
fn DIV_CEIL(a : u32, b : u32) -> u32 {
return ((a - 1u) / b + 1u);
}
${`
var<workgroup> xBestValues : array<f32, ${this.workGroupSize[0]}>;
`}
fn getOffset(outputIndex : i32) -> i32 {
let outputCoords = getCoordsFromIndex(outputIndex);
let offset = ${this.outputShape.length === 1 ? "outputCoords" : "outputCoords[0]"} * uniforms.reduceSize;
return offset;
}
${Ue()}
let outputIndex = index / i32(workGroupSizeX);
let offset = getOffset(outputIndex);
var bestValue = ${t};
let Length = uniforms.reduceSize;
let WorkPerThread = DIV_CEIL(u32(Length), workGroupSizeX);
for (var k = i32(localId.x); k < Length && outputIndex < uniforms.size;
k = k + i32(workGroupSizeX)) {
let candidate = f32(x[offset + k]);
${e}
}
xBestValues[localId.x] = bestValue;
workgroupBarrier();
var reduceSize = min(u32(Length), workGroupSizeX);
for (var currentSize = reduceSize / 2u; reduceSize > 1u;
currentSize = reduceSize / 2u) {
let interval = DIV_CEIL(reduceSize, 2u);
if (localId.x < currentSize) {
let candidate = xBestValues[localId.x + interval];
${e}
xBestValues[localId.x] = bestValue;
}
reduceSize = interval;
workgroupBarrier();
}
if (localId.x == 0u && outputIndex < uniforms.size) {
${n}
}
}
`;
}
};
function uc(e, t, n, s, r) {
let a = e.shape.length, o = [], i = w.parseAxisParam(t, e.shape), u = i, l = C.getAxesPermutation(u, a), c = e;
l != null && (c = Ks({ inputs: { x: e }, attrs: { perm: l }, backend: r }), u = C.getInnerMostAxes(u.length, a), o.push(c)), C.assertAxesAreInnerMostDims(s, u, a);
let [p, d] = C.computeOutAndReduceShapes(c.shape, u), h = p;
n && (h = C.expandShapeToKeepDim(p, i));
let f;
if ((s === "max" || s === "prod") && r.shouldExecuteOnCPU([c])) {
let m = r.tensorMap.get(c.dataId).values;
switch (s) {
case "max":
let g = Fse(m, w.sizeFromShape(d), h, e.dtype);
f = r.makeTensorInfo(h, e.dtype, g);
break;
case "prod":
let { outVals: b, outShape: y, outDtype: v } = Bse(c.shape, c.dtype, m, u);
f = r.makeTensorInfo(y, v, b);
break;
default:
throw new Error(`${s} CPU implementation is not yet supported.`);
}
} else {
let m = w.sizeFromShape(d), b = w.sizeFromShape(c.shape) / m, y = { windowSize: m, inSize: m, batchSize: b, outSize: 1 }, v = s === "mean" ? "float32" : yp(e.dtype), x = [{ type: "int32", data: [m] }], k = new uae(y, s), I = r.runWebGPUProgram(k, [c], v, x);
o.push(I), f = Le({ inputs: { x: I }, attrs: { shape: h }, backend: r });
}
return o.forEach((m) => r.disposeData(m.dataId)), f;
}
function Vv(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, keepDims: o } = s;
return uc(r, a, o, "sum", n);
}
var lae = { kernelName: co, backendName: "webgpu", kernelFunc: Vv };
function cae(e) {
let { inputs: t, backend: n, attrs: s } = e, { equation: r } = s, a = t, { allDims: o, summedDims: i, idDims: u } = C.decodeEinsumEquation(r, a.length);
C.checkEinsumDimSizes(o.length, u, a);
let { path: l, steps: c } = C.getEinsumComputePath(i, u), p = c.length, d = null, h = o.length, f = [];
for (let m = 0; m < p; ++m) {
for (let g of c[m]) {
let { permutationIndices: b, expandDims: y } = C.getEinsumPermutation(h, u[g]), v;
C.isIdentityPermutation(b) ? v = a[g] : (v = Ks({ inputs: { x: a[g] }, backend: n, attrs: { perm: b } }), f.push(v));
let x = v.shape.slice();
for (let k = 0; k < y.length; ++k)
x.splice(y[k], 0, 1);
w.arraysEqual(v.shape, x) || (v = Le({ inputs: { x: v }, backend: n, attrs: { shape: x } }), f.push(v)), d === null ? d = v : (d = X2({ inputs: { a: v, b: d }, backend: n }), f.push(d));
}
m < p - 1 && (l[m] >= 0 && (d = Vv({ inputs: { x: d }, backend: n, attrs: { axis: l[m] - (o.length - h), keepDims: false } }), f.push(d)), h--);
}
for (let m of f)
m !== d && n.disposeData(m.dataId);
return d;
}
var dae = { kernelName: op, backendName: "webgpu", kernelFunc: cae };
var pae = Kt({ opType: 4 });
var hae = { kernelName: Pa, backendName: "webgpu", kernelFunc: pae };
var fae = gn({ opSnippet: 4, dtype: "bool", cpuKernelImpl: Sse });
var mae = { kernelName: bi, backendName: "webgpu", kernelFunc: fae };
var Y2 = Kt({ opType: 5, cpuKernelImpl: Ise, dtype: "float32" });
var gae = { kernelName: za, backendName: "webgpu", kernelFunc: Y2 };
function ug(e) {
let { inputs: t, attrs: n, backend: s } = e, { dim: r } = n, { input: a } = t, o = a.shape.length, i = a.shape.slice(), u = r;
return r < 0 && (w.assert(-(o + 1) <= r, () => `Axis must be in the interval [${-(o + 1)}, ${o}]`), u = o + r + 1), i.splice(u, 0, 1), Le({ inputs: { x: a }, backend: s, attrs: { shape: i } });
}
var bae = { kernelName: yi, backendName: "webgpu", kernelFunc: ug };
var yae = Kt({ opType: 6, cpuKernelImpl: Cse });
var vae = { kernelName: vi, backendName: "webgpu", kernelFunc: yae };
var xae = class {
constructor(e) {
this.variableNames = [], this.outputShape = [], this.uniforms = "value : f32,", this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.shaderKey = "fill";
}
getUserCode() {
return `
${Ue()}
if (index < uniforms.size) {
setOutputAtIndex(index, uniforms.value);
}
}
`;
}
};
function mu(e) {
let { backend: t, attrs: n } = e, { shape: s, value: r } = n, { dtype: a } = n;
if (a = a || w.inferDtype(r), a === "string") {
let o = w.getArrayFromDType(a, w.sizeFromShape(s));
return o.fill(r), t.makeTensorInfo(s, a, o);
} else {
let o = new xae(s), i = [{ type: "float32", data: [r] }];
return t.runWebGPUProgram(o, [], a, i);
}
}
var wae = { kernelName: vl, backendName: "webgpu", kernelFunc: mu };
var kae = class {
constructor(e) {
this.outputShape = [], this.variableNames = ["x"], this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.shaderKey = "flipLeftRight";
}
getUserCode() {
return `
${Ue()}
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let coordX = uniforms.xShape[2] - coords[2] - 1;
let outputValue = getX(coords[0], coords[1], coordX, coords[3]);
setOutputAtIndex(index, outputValue);
}
}
`;
}
};
var Sae = { kernelName: xi, backendName: "webgpu", kernelFunc: ({ inputs: e, backend: t }) => {
let { image: n } = e, s = t, r = new kae(n.shape);
return s.runWebGPUProgram(r, [n], n.dtype);
} };
var Iae = Kt({ opType: 7, cpuKernelImpl: Nse });
var Cae = { kernelName: La, backendName: "webgpu", kernelFunc: Iae };
var Nae = gn({ opSnippet: 12, dtype: "int32" });
var Tae = { kernelName: Ma, backendName: "webgpu", kernelFunc: Nae };
var $ae = class {
constructor(e, t = false) {
this.outputShape = [0], this.variableNames = [], this.workGroupSize = [256, 1, 1], this.outputShape = e, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.useImport = t, this.shaderKey = `fromPixels_${this.useImport}`;
}
getUserCode() {
let e = this.useImport ? "textureLoad(src, vec2<i32>(coords.yx));" : "textureLoad(src, vec2<i32>(coords.yx), 0)";
return `
@binding(1) @group(0) var src: ${this.useImport ? "texture_external" : "texture_2d<f32>"};
${Ue()}
let flatIndexBase = index * uniforms.numChannels;
for (var i = 0; i < uniforms.numChannels; i = i + 1) {
let flatIndex = flatIndexBase + i;
if (flatIndex < uniforms.size) {
let coords = getCoordsFromIndex(flatIndexBase);
let values = ${e};
result[flatIndex] = i32(floor(255.0 * values[i]));
}
}
}
`;
}
};
var _ae = { kernelName: xd, backendName: "webgpu", kernelFunc: Aae };
var Uo;
function Aae(e) {
let { inputs: t, backend: n, attrs: s } = e, { pixels: r } = t, { numChannels: a } = s;
if (r == null)
throw new Error("pixels passed to tf.browser.fromPixels() can not be null");
let o = typeof HTMLVideoElement != "undefined" && r instanceof HTMLVideoElement, i = typeof HTMLImageElement != "undefined" && r instanceof HTMLImageElement, u = typeof HTMLCanvasElement != "undefined" && r instanceof HTMLCanvasElement || typeof OffscreenCanvas != "undefined" && r instanceof OffscreenCanvas, l = typeof ImageBitmap != "undefined" && r instanceof ImageBitmap, [c, p] = o ? [r.videoWidth, r.videoHeight] : [r.width, r.height], d = [p, c, a];
if (K().getBool("WEBGPU_USE_IMPORT") && o)
return Kw({ externalImage: r, backend: n, attrs: s, outShape: d, useImport: true });
if ((o || i) && (Uo == null && (Uo = document.createElement("canvas").getContext("2d")), Uo.canvas.width = c, Uo.canvas.height = p, Uo.drawImage(r, 0, 0, c, p), r = Uo.canvas), l || u || o || i)
return Kw({ externalImage: r, backend: n, attrs: s, outShape: d, useImport: false });
let h = r.data, f = h;
if (a != null && a !== 4) {
f = new Uint8Array(r.width * r.height * a);
let b = h.length, y = 0;
for (let v = 0; v < b; v++)
v % 4 < a && (f[y++] = h[v]);
}
let m = n.makeTensorInfo(d, "int32"), g = n.tensorMap.get(m.dataId);
return g.values = new Int32Array(f), n.maybeReleaseBuffer(m.dataId), n.uploadToGPU(m.dataId), m;
}
function Kw(e) {
let { externalImage: t, backend: n, attrs: s, outShape: r, useImport: a } = e, { numChannels: o } = s, i = w.sizeFromShape(r), u = w.computeStrides(r), l = new $ae(r, a), c = [{ type: "uint32", data: [i] }, { type: "uint32", data: [o] }, { type: "uint32", data: [...u] }, { type: "uint32", data: [...l.dispatch] }];
return n.runFromPixelsProgram(l, r, c, a, t);
}
var Eae = class {
constructor(e, t, n, s, r) {
this.uniforms = "varianceEpsilon : f32,", this.workGroupSize = [128, 1, 1], this.size = true, this.variableNames = ["x", "mean", "variance"], C.assertAndGetBroadcastShape(e, t), C.assertAndGetBroadcastShape(e, n), this.outputShape = e, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), s != null && (C.assertAndGetBroadcastShape(e, s), this.variableNames.push("offset")), r != null && (C.assertAndGetBroadcastShape(e, r), this.variableNames.push("scale")), this.offsetShape = s, this.scaleShape = r, this.shaderKey = "batchNorm";
}
getUserCode() {
let e = "0.0";
this.offsetShape != null && (e = "getOffsetByOutputIndex(index)");
let t = "1.0";
return this.scaleShape != null && (t = "getScaleByOutputIndex(index)"), `
${Ue()}
if (index < uniforms.size)
{
let xValue = getXByOutputIndex(index);
let meanValue = getMeanByOutputIndex(index);
let varianValue = getVarianceByOutputIndex(index);
let offsetValue = ${e};
let scaleValue = ${t};
let inv = scaleValue * inverseSqrt(varianValue + f32(uniforms.varianceEpsilon));
setOutputAtIndex(index,dot(vec3<f32>(xValue, -meanValue, offsetValue), vec3<f32>(inv, inv, 1.0)));
}
}
`;
}
};
var Rae = { kernelName: Ba, backendName: "webgpu", kernelFunc: ({ inputs: e, attrs: t, backend: n }) => {
let { x: s, scale: r, offset: a, mean: o, variance: i } = e, { varianceEpsilon: u } = t, l = n, c = [s, o, i], p = null;
a != null && (p = a.shape, c.push(a));
let d = null;
r != null && (d = r.shape, c.push(r));
let h = new Eae(s.shape, o.shape, i.shape, p, d), f = [{ type: "float32", data: [u] }];
return l.runWebGPUProgram(h, c, s.dtype, f);
} };
function Dae(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, filter: a, bias: o, preluActivationWeights: i } = t, { strides: u, pad: l, dataFormat: c, dilations: p, dimRoundingMode: d, activation: h, leakyreluAlpha: f } = s, m = C.convertConv2DDataFormat(c), g = C.computeConv2DInfo(r.shape, a.shape, u, p, l, d, false, m);
return H2({ x: r, filter: a, convInfo: g, backend: n, bias: o, preluActivationWeights: i, leakyreluAlpha: f, activation: h });
}
var Fae = { kernelName: ia, backendName: "webgpu", kernelFunc: Dae };
function Oae(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, filter: a, bias: o, preluActivationWeights: i } = t, { strides: u, pad: l, dilations: c, dimRoundingMode: p, activation: d, leakyreluAlpha: h } = s, f = c;
f == null && (f = [1, 1]), w.assert(C.eitherStridesOrDilationsAreOne(u, f), () => `Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${u} and dilations '${f}'`);
let m = C.computeConv2DInfo(r.shape, a.shape, u, f, l, p, true), g = [r, a], b = o != null, y = i != null;
b && g.push(o), y && g.push(i);
let v = [{ type: "int32", data: [m.padInfo.top, m.padInfo.left] }, { type: "int32", data: [m.strideHeight, m.strideWidth] }, { type: "int32", data: [m.dilationHeight, m.dilationWidth] }, { type: "int32", data: [m.inHeight, m.inWidth] }], x;
return m.batchSize === 1 && m.inHeight === m.outHeight && m.inWidth === m.outWidth && m.strideHeight === 1 && m.strideWidth === 1 && m.filterHeight === m.filterWidth && m.inChannels === m.outChannels && m.dilationHeight === 1 && m.dilationWidth === 1 && m.filterHeight === 3 && m.inChannels % 4 === 0 ? x = new j2(m, b, d, y) : (x = new K2(m, b, d, y), v.push({ type: "int32", data: [m.filterHeight] }, { type: "int32", data: [m.filterWidth] }, { type: "int32", data: [m.outChannels / m.inChannels] })), d === "leakyrelu" && (v.push({ type: "float32", data: [h] }), x.uniforms += " alpha : f32,"), n.runWebGPUProgram(x, g, "float32", v);
}
var Pae = { kernelName: ua, backendName: "webgpu", kernelFunc: Oae };
var zae = class {
constructor(e, t) {
this.variableNames = ["A", "indices"], this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = t, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.shaderKey = `gathernd_${e}`, this.sliceDim = e, this.uniforms = `sliceDim : i32, strides : ${Wt(e)},`;
}
getUserCode() {
let e;
return this.sliceDim > 1 ? e = "uniforms.strides[j]" : e = "uniforms.strides", `
${Ue()}
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
var flattenIndex = 0;
for (var j = 0; j < uniforms.sliceDim; j = j + 1) {
let indexTemp = i32(round(getIndices(coords[0], j)));
let strideNum = ${e};
flattenIndex = flattenIndex + indexTemp * strideNum;
}
setOutputAtIndex(index, getA(flattenIndex, coords[1]));
}
}
`;
}
};
function Lae(e) {
let { inputs: t, backend: n } = e, { params: s, indices: r } = t, a = r.shape, o = a[a.length - 1], i = w.sizeFromShape(s.shape), [u, l, c, p] = C.prepareAndValidate(s, r), d = Le({ inputs: { x: r }, backend: n, attrs: { shape: [l, o] } }), h = Le({ inputs: { x: s }, backend: n, attrs: { shape: [w.sizeFromShape(s.shape) / c, c] } });
if (n.shouldExecuteOnCPU([s, r]) || s.dtype === "string") {
let y = n.readSync(r.dataId), v = n.bufferSync(s), x = Tse(y, v, s.dtype, l, o, c, p, s.shape, i);
return n.makeTensorInfo(u, s.dtype, x.values);
}
let f = new zae(o, [l, c]), m = [{ type: "int32", data: [o] }, { type: "int32", data: p }], g = n.runWebGPUProgram(f, [h, d], h.dtype, m), b = Le({ inputs: { x: g }, backend: n, attrs: { shape: u } });
return n.disposeData(d.dataId), n.disposeData(h.dataId), n.disposeData(g.dataId), b;
}
var Mae = { kernelName: ki, backendName: "webgpu", kernelFunc: Lae };
var Bae = class {
constructor(e, t) {
this.variableNames = ["A", "indices"], this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = e.slice(), this.aShape = e, this.outputShape = t, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.shaderKey = "gather";
}
getUserCode() {
let e = Vae(this.aShape);
return `
${Ue()}
if (index < uniforms.size) {
let resRC = getCoordsFromIndex(index);
let indexZ = i32(getIndices(resRC.x, resRC.z));
let inBounds = select(0.0, 1.0, indexZ >= 0 && indexZ < uniforms.aShape[2]);
setOutputAtIndex(index, inBounds * getA(${e}));
}
}
`;
}
};
function Vae(e) {
let t = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"], n = [];
for (let s = 0; s < e.length; s++)
s === 2 ? n.push("indexZ") : n.push(`${t[s]}`);
return n.join();
}
function Q2(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r, indices: a } = t, { axis: o, batchDims: i } = s, u = w.parseAxisParam(o, r.shape)[0], l = C.segment_util.collectGatherOpShapeInfo(r, a, u, i), c = w.sizeFromShape(a.shape), p = [], d = Le({ inputs: { x: r }, backend: n, attrs: { shape: [l.batchSize, l.outerSize, l.dimSize, l.sliceSize] } }), h = Le({ inputs: { x: a }, backend: n, attrs: { shape: [l.batchSize, c / l.batchSize] } });
p.push(d), p.push(h);
let f = [l.batchSize, l.outerSize, c / l.batchSize, l.sliceSize];
if (n.shouldExecuteOnCPU([r, a])) {
let v = n.tensorMap.get(h.dataId).values, x = Ae(h.shape, h.dtype, v), I = n.tensorMap.get(d.dataId).values, $ = Ae(d.shape, d.dtype, I), R = $se($, x, f);
return p.forEach((E) => n.disposeData(E.dataId)), n.makeTensorInfo(l.outputShape, R.dtype, R.values);
}
let m = new Bae(d.shape, f), g = n.runWebGPUProgram(m, [d, h], d.dtype);
p.push(g);
let b = Le({ inputs: { x: g }, backend: n, attrs: { shape: l.outputShape } });
return p.forEach((y) => n.disposeData(y.dataId)), b;
}
var Wae = { kernelName: wi, backendName: "webgpu", kernelFunc: Q2 };
var Uae = gn({ opSnippet: 5, cpuKernelImpl: Ase, dtype: "bool" });
var Gae = { kernelName: Si, backendName: "webgpu", kernelFunc: Uae };
var Hae = gn({ opSnippet: 6, dtype: "bool", cpuKernelImpl: _se });
var qae = { kernelName: Va, backendName: "webgpu", kernelFunc: Hae };
function jae(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { alpha: a } = s, o = [{ type: "float32", data: [a] }], i = new oc(r.shape, 14);
return i.uniforms = "alpha : f32,", n.runWebGPUProgram(i, [r], "float32", o);
}
var Kae = { kernelName: Ua, backendName: "webgpu", kernelFunc: jae };
var Xae = gn({ opSnippet: 7, dtype: "bool", cpuKernelImpl: Rse });
var Yae = { kernelName: Ii, backendName: "webgpu", kernelFunc: Xae };
var Qae = gn({ opSnippet: 8, dtype: "bool", cpuKernelImpl: Ese });
var Zae = { kernelName: Ci, backendName: "webgpu", kernelFunc: Qae };
var Jae = Kt({ opType: 9, cpuKernelImpl: Dse });
var eoe = { kernelName: Ga, backendName: "webgpu", kernelFunc: Jae };
var toe = gn({ opSnippet: 9, dtype: "bool" });
var noe = { kernelName: Ni, backendName: "webgpu", kernelFunc: toe };
var soe = Kt({ opType: 10 });
var roe = { kernelName: Ti, backendName: "webgpu", kernelFunc: soe };
function Z2(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { reductionIndices: a, keepDims: o } = s;
return uc(r, a, o, "max", n);
}
var aoe = { kernelName: Ha, backendName: "webgpu", kernelFunc: Z2 };
var ooe = gn({ opSnippet: 15, cpuKernelImpl: Ose });
var ioe = { kernelName: qa, backendName: "webgpu", kernelFunc: ooe };
function uoe(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { filterSize: a, strides: o, pad: i, dimRoundingMode: u } = s, l = 1, c = C.computePool2DInfo(r.shape, a, o, l, i, u), p, d = [];
if (c.filterHeight === 1 && c.filterWidth === 1) {
if (w.arraysEqual(c.inShape, c.outShape))
return Un({ inputs: { x: r }, backend: n });
p = new W2(c), d.push({ type: "int32", data: [c.strideHeight, c.strideWidth] });
} else
p = new V2(c, "max"), d.push({ type: "int32", data: [c.strideHeight, c.strideWidth] }, { type: "int32", data: [c.padInfo.top, c.padInfo.left] }, { type: "int32", data: [c.dilationHeight, c.dilationWidth] }, { type: "int32", data: [c.inHeight, c.inWidth] }, { type: "int32", data: [c.effectiveFilterHeight, c.effectiveFilterWidth] });
return n.runWebGPUProgram(p, [r], r.dtype, d);
}
var loe = { kernelName: ja, backendName: "webgpu", kernelFunc: uoe };
function coe(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { keepDims: a, axis: o } = s;
return uc(r, o, a, "mean", n);
}
var doe = { kernelName: Ka, backendName: "webgpu", kernelFunc: coe };
function poe(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, keepDims: o } = s;
return uc(r, a, o, "min", n);
}
var hoe = { kernelName: Xa, backendName: "webgpu", kernelFunc: poe };
var foe = gn({ opSnippet: 16, cpuKernelImpl: Pse });
var moe = { kernelName: Ya, backendName: "webgpu", kernelFunc: foe };
var goe = class {
constructor(e, t, n) {
this.uniforms = "", this.variableNames = ["x"], this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = t.map((s, r) => s[0] + e[r] + s[1]), this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.xShape = e, t.map((s, r) => {
this.uniforms += ` pad${r} : vec2<i32>,`;
}), this.offset = n === "reflect" ? 0 : 1, this.shaderKey = `mirrorPad_${n}`;
}
getUserCode() {
let e = this.xShape.length, t = this.xShape.map((u, l) => `uniforms.pad${l}[0]`).join(","), n = this.xShape.map((u, l) => `uniforms.pad${l}[0] + uniforms.xShape${e > 1 ? `[${l}]` : ""}`).join(","), s = e === 1 ? "start" : "start[i]", r = e === 1 ? "end" : "end[i]", a = e === 1 ? "outC" : "outC[i]", o = Wt(e), i = e > 1 ? ["coords[0]", "coords[1]", "coords[2]", "coords[3]"].slice(0, e) : "coords";
return `
${Ue()}
if (index < uniforms.size) {
let start = ${o}(${t});
let end = ${o}(${n});
var outC = getCoordsFromIndex(index);
for (var i = 0; i < ${e}; i = i + 1) {
if (${a} < ${s}) {
${a} = ${s} * 2 - ${a} - ${this.offset};
} else if(${a} >= ${r}) {
${a} = (${r} - 1) * 2 - ${a} + ${this.offset};
}
}
let coords = outC - start;
setOutputAtIndex(index, getX(${i}));
}
}
`;
}
};
var boe = { kernelName: Qa, backendName: "webgpu", kernelFunc: ({ inputs: e, attrs: t, backend: n }) => {
let { x: s } = e, { paddings: r, mode: a } = t, o = n, i = r.map((c) => ({ type: "int32", data: [c[0], c[1]] })), u = new goe(s.shape, r, a);
return o.runWebGPUProgram(u, [s], s.dtype, i);
} };
function yoe(e) {
let { inputs: t, backend: n } = e, { x: s } = t;
if (n.shouldExecuteOnCPU([s])) {
let a = n.tensorMap.get(s.dataId), [o, i] = Lse(a.values, s.shape, s.dtype);
return n.makeTensorInfo(i, s.dtype, o);
}
let r = new oc(s.shape, 11);
return n.runWebGPUProgram(r, [s], s.dtype);
}
var voe = { kernelName: $i, backendName: "webgpu", kernelFunc: yoe };
function xoe(e) {
console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
let { inputs: t, backend: n, attrs: s } = e, { boxes: r, scores: a } = t, { maxOutputSize: o, iouThreshold: i, scoreThreshold: u } = s, l = n.readSync(r.dataId), c = n.readSync(a.dataId), { selectedIndices: p } = ws.nonMaxSuppressionV3Impl(l, c, o, i, u);
return n.makeTensorInfo([p.length], "int32", new Int32Array(p));
}
var woe = { kernelName: Ai, backendName: "webgpu", kernelFunc: xoe };
function koe(e) {
console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
let { inputs: t, backend: n, attrs: s } = e, { boxes: r, scores: a } = t, { maxOutputSize: o, iouThreshold: i, scoreThreshold: u, softNmsSigma: l } = s, c = n.readSync(r.dataId), p = n.readSync(a.dataId), d = o, h = i, f = u, m = l, { selectedIndices: g, selectedScores: b } = ws.nonMaxSuppressionV5Impl(c, p, d, h, f, m);
return [n.makeTensorInfo([g.length], "int32", new Int32Array(g)), n.makeTensorInfo([b.length], "float32", new Float32Array(b))];
}
var Soe = { kernelName: Ei, backendName: "webgpu", kernelFunc: koe };
function Kd(e) {
let { inputs: t, backend: n } = e, { x: s } = t;
if (s.dtype === "complex64") {
let r = ic({ inputs: { input: s }, backend: n }), a = Kd({ inputs: { x: r }, backend: n }), o = ih({ inputs: { input: s }, backend: n }), i = Kd({ inputs: { x: o }, backend: n }), u = hu({ inputs: { real: a, imag: i }, backend: n });
return n.disposeData(r.dataId), n.disposeData(a.dataId), n.disposeData(o.dataId), n.disposeData(i.dataId), u;
} else
return mu({ attrs: { shape: s.shape, dtype: s.dtype, value: s.dtype === "string" ? "" : 0 }, backend: n });
}
var Ioe = { kernelName: Xi, backendName: "webgpu", kernelFunc: Kd };
function J2(e) {
let { inputs: t, backend: n } = e, { x: s } = t;
if (s.dtype === "string")
throw new Error("onesLike is not supported under string dtype");
if (s.dtype === "complex64") {
let r = ic({ inputs: { input: s }, backend: n }), a = J2({ inputs: { x: r }, backend: n }), o = ih({ inputs: { input: s }, backend: n }), i = Kd({ inputs: { x: o }, backend: n }), u = hu({ inputs: { real: a, imag: i }, backend: n });
return n.disposeData(r.dataId), n.disposeData(a.dataId), n.disposeData(o.dataId), n.disposeData(i.dataId), u;
} else
return mu({ attrs: { shape: s.shape, dtype: s.dtype, value: 1 }, backend: n });
}
var Coe = { kernelName: Ri, backendName: "webgpu", kernelFunc: J2 };
function Noe(e) {
let { inputs: t, backend: n, attrs: s } = e, { axis: r } = s;
if (t.length === 1)
return ug({ inputs: { input: t[0] }, backend: n, attrs: { dim: r } });
let a = t[0].shape, o = t[0].dtype;
t.forEach((c) => {
w.assertShapesMatch(a, c.shape, "All tensors passed to stack must have matching shapes"), w.assert(o === c.dtype, () => "All tensors passed to stack must have matching dtypes");
});
let i = [], u = t.map((c) => {
let p = ug({ inputs: { input: c }, backend: n, attrs: { dim: r } });
return i.push(p), p;
}), l = G2({ inputs: u, backend: n, attrs: { axis: r } });
return i.forEach((c) => n.disposeData(c.dataId)), l;
}
var Toe = { kernelName: Fi, backendName: "webgpu", kernelFunc: Noe };
var $oe = class {
constructor(e, t) {
this.variableNames = ["x"], this.uniforms = "constantValue : f32,", this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = t.map((n, s) => n[0] + e[s] + n[1]), this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), t.map((n, s) => {
this.uniforms += ` pad${s} : vec2<i32>,`;
}), this.xShape = e, this.shaderKey = "pad";
}
getUserCode() {
let e = this.xShape.length, t = Wt(e), n = this.xShape.map((c, p) => `uniforms.pad${p}[0]`).join(","), s = this.xShape.map((c, p) => `uniforms.pad${p}[0] + uniforms.xShape${e > 1 ? `[${p}]` : ""}`).join(","), r = e > 1 ? `${t}(${n})` : `${n}`, a = e > 1 ? `${t}(${s})` : `${s}`, o = e > 1 ? "any(outC < start)" : "outC < start", i = e > 1 ? "any(outC >= end)" : "outC >= end", u = e > 1 ? ["coords[0]", "coords[1]", "coords[2]", "coords[3]"].slice(0, e) : "coords";
return `
${Ue()}
if (index < uniforms.size) {
let start = ${r};
let end = ${a};
let outC = getCoordsFromIndex(index);
if (${o} || ${i}) {
setOutputAtIndex(index, uniforms.constantValue);
} else {
let coords = outC - start;
setOutputAtIndex(index, getX(${u}));
}
}
}
`;
}
};
var eN = (e) => {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { paddings: a, constantValue: o } = s;
if (a.every((l) => w.arraysEqual(l, [0, 0])))
return Un({ inputs: { x: r }, backend: n });
if (w.sizeFromShape(r.shape) === 0) {
let l = a.map((c, p) => c[0] + r.shape[p] + c[1]);
return mu({ backend: n, attrs: { shape: l, value: o, dtype: r.dtype } });
}
let i = [{ type: "float32", data: [o] }];
a.map((l) => i.push({ type: "int32", data: [l[0], l[1]] }));
let u = new $oe(r.shape, a);
return n.runWebGPUProgram(u, [r], r.dtype, i);
};
var _oe = { kernelName: Ja, backendName: "webgpu", kernelFunc: eN };
var Aoe = gn({ opSnippet: 13 });
var Eoe = { kernelName: eo, backendName: "webgpu", kernelFunc: Aoe };
function Roe(e) {
let { inputs: t, backend: n } = e, { x: s, alpha: r } = t, a = new M2(14, s.shape, r.shape);
return n.runWebGPUProgram(a, [s, r], "float32");
}
var Doe = { kernelName: to, backendName: "webgpu", kernelFunc: Roe };
function Foe(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, keepDims: o } = s;
return uc(r, a, o, "prod", n);
}
var Ooe = { kernelName: no, backendName: "webgpu", kernelFunc: Foe };
var Poe = (e) => {
let { backend: t, attrs: n } = e, { start: s, stop: r, step: a, dtype: o } = n, i = Vse(s, r, a, o);
return t.makeTensorInfo([i.length], o, i);
};
var zoe = { kernelName: Tl, backendName: "webgpu", kernelFunc: Poe };
var tN = gn({ opSnippet: 3 });
var Loe = { kernelName: Oa, backendName: "webgpu", kernelFunc: tN };
var Moe = Kt({ opType: 12 });
var Boe = { kernelName: so, backendName: "webgpu", kernelFunc: Moe };
var Voe = Kt({ opType: 13 });
var Woe = { kernelName: ao, backendName: "webgpu", kernelFunc: Voe };
var Uoe = class {
constructor(e, t, n) {
this.variableNames = ["x"], this.uniforms = "adjustHeightWidth : vec2<f32>, halfPixelCenters : f32,", this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = [e[0], t, n, e[3]], this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.shaderKey = "resizeBilinear";
}
getUserCode() {
return `
${Ue()}
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let b = coords[0];
let d = coords[3];
let rc = coords.yz;
let effectiveInSize = vec2<f32>(
f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0],
f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]);
let effectiveOutSize = vec2<f32>(
f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0],
f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]);
let effectiveInputOverOutputRatioRC =
effectiveInSize / effectiveOutSize;
// Fractional source index
let sourceFracIndexRC =
(vec2<f32>(rc) + vec2<f32>(uniforms.halfPixelCenters)) *
effectiveInputOverOutputRatioRC - vec2<f32>(uniforms.halfPixelCenters);
// Compute the four integer indices.
let sourceFloorRC = vec2<i32>(sourceFracIndexRC);
let sourceCeilRC = vec2<i32>(
min(vec2<f32>(uniforms.xShape.yz) - vec2<f32>(1.0), ceil(sourceFracIndexRC)));
let topLeft = getX(b, sourceFloorRC.x, sourceFloorRC.y, d);
let bottomLeft = getX(b, sourceCeilRC.x, sourceFloorRC.y, d);
let topRight = getX(b, sourceFloorRC.x, sourceCeilRC.y, d);
let bottomRight = getX(b, sourceCeilRC.x, sourceCeilRC.y, d);
let fracRC = sourceFracIndexRC - vec2<f32>(sourceFloorRC);
let top = topLeft + (topRight - topLeft) * fracRC.y;
let bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
let newValue = top + (bottom - top) * fracRC.x;
setOutputAtIndex(index, newValue);
}
}
`;
}
};
function Goe(e) {
let { inputs: t, backend: n, attrs: s } = e, { images: r } = t, { alignCorners: a, size: o, halfPixelCenters: i } = s, [u, l] = o, c = a && u > 1 ? 1 : 0, p = a && l > 1 ? 1 : 0, h = [{ type: "float32", data: [c, p] }, { type: "float32", data: [i ? 0.5 : 0] }], f = new Uoe(r.shape, u, l);
return n.runWebGPUProgram(f, [r], "float32", h);
}
var Hoe = { kernelName: ro, backendName: "webgpu", kernelFunc: Goe };
var qoe = class {
constructor(e, t, n, s) {
this.variableNames = ["x"], this.uniforms = "adjustHeightWidth : vec2<f32>, roundBase : f32,", this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = [e[0], t, n, e[3]], this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.halfPixelCenters = s, this.shaderKey = `resizeNearest_${s}`;
}
getUserCode() {
let e;
return this.halfPixelCenters ? e = "max((vec2<f32>(rc) + vec2<f32>(0.5)) * effectiveInputOverOutputRatioRC, vec2<f32>(0.0))" : e = "vec2<f32>(rc) * effectiveInputOverOutputRatioRC", `
${Ue()}
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let b = coords[0];
let d = coords[3];
let rc = coords.yz;
let effectiveInSize = vec2<f32>(
f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0],
f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]);
let effectiveOutSize = vec2<f32>(
f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0],
f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]);
let effectiveInputOverOutputRatioRC =
effectiveInSize / effectiveOutSize;
// Fractional source index
let sourceFracIndexRC = ${e};
// Compute the coordinators of nearest neighbor point.
let inputShapeRC = vec2<f32>(f32(uniforms.xShape.y), f32(uniforms.xShape.z));
let sourceNearestRC = vec2<i32>(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + uniforms.roundBase)));
let newValue = getX(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutputAtIndex(index, newValue);
}
}
`;
}
};
function joe(e) {
let { inputs: t, backend: n, attrs: s } = e, { images: r } = t, { alignCorners: a, halfPixelCenters: o, size: i } = s, [u, l] = i, c = a && u > 1 ? 1 : 0, p = a && l > 1 ? 1 : 0, h = [{ type: "float32", data: [c, p] }, { type: "float32", data: [a ? 0.5 : 0] }], f = new qoe(r.shape, u, l, o);
return n.runWebGPUProgram(f, [r], r.dtype, h);
}
var Koe = { kernelName: _l, backendName: "webgpu", kernelFunc: joe };
var Xoe = class {
constructor(e, t) {
this.outputShape = [], this.variableNames = ["x"], this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.uniforms = `centerX : f32, centerY : f32, sinRadians : f32,
cosRadians : f32,`, this.shaderKey = "rotate", this.outputShape = e, typeof t == "number" ? (this.uniforms += " fillValue : f32,", this.fillSnippet = "var outputValue = uniforms.fillValue;", this.shaderKey += "_float") : (this.uniforms += " fillValue : vec3<f32>,", this.fillSnippet = "var outputValue = uniforms.fillValue[coords[3]];", this.shaderKey += "_vec3");
}
getUserCode() {
return `
${Ue()}
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let coordXFloat = (f32(coords[2]) - uniforms.centerX) *
uniforms.cosRadians - (f32(coords[1]) - uniforms.centerY) *
uniforms.sinRadians;
let coordYFloat = (f32(coords[2]) - uniforms.centerX) *
uniforms.sinRadians + (f32(coords[1]) - uniforms.centerY) *
uniforms.cosRadians;
let coordX = i32(round(coordXFloat + uniforms.centerX));
let coordY = i32(round(coordYFloat + uniforms.centerY));
${this.fillSnippet}
if(coordX >= 0 && coordX < uniforms.xShape[2] && coordY >= 0 &&
coordY < uniforms.xShape[1]) {
outputValue = getX(coords[0], coordY, coordX, coords[3]);
}
setOutputAtIndex(index, outputValue);
}
}
`;
}
};
var Yoe = { kernelName: Yi, backendName: "webgpu", kernelFunc: ({ inputs: e, attrs: t, backend: n }) => {
let { image: s } = e, { radians: r, fillValue: a, center: o } = t, i = n, u = new Xoe(s.shape, a), [l, c] = C.getImageCenter(o, s.shape[1], s.shape[2]), p = [{ type: "float32", data: [l] }, { type: "float32", data: [c] }, { type: "float32", data: [Math.sin(r)] }, { type: "float32", data: [Math.cos(r)] }];
return typeof a == "number" ? p.push({ type: "float32", data: [Number.parseFloat(a.toFixed(2))] }) : p.push({ type: "float32", data: a }), i.runWebGPUProgram(u, [s], s.dtype, p);
} };
var Qoe = Kt({ opType: 15, cpuKernelImpl: Wse });
var Zoe = { kernelName: oo, backendName: "webgpu", kernelFunc: Qoe };
var Joe = class {
constructor(e, t, n, s, r, a, o) {
this.variableNames = ["updates", "indices"], this.workGroupSize = [64, 1, 1], this.atomic = true, this.outputShape = a, this.type = o, this.dispatchLayout = Ve(e), this.dispatch = _e(this.dispatchLayout, e, this.workGroupSize), this.sliceDimGreaterThanOne = t > 1, this.shaderKey = `scatter_${n}_${s}_${this.sliceDimGreaterThanOne}_${o}`;
let i = Wt(r.length);
this.uniforms = `sliceDim : i32, strides: ${i}, size: i32,`, this.updatesRank = s, this.indicesRank = n;
}
getUserCode() {
let e = "";
this.indicesRank === 1 ? e = "coords[0]" : this.indicesRank === 2 && (e = "coords[0], j");
let t = `getIndices(${e})`, n = this.sliceDimGreaterThanOne ? "uniforms.strides[j]" : "uniforms.strides", s = "", r = "", a = "";
this.updatesRank === 1 ? (s = "coords[0]", r = "flattenedIndex", a = `
fn getUpdatesCoordsFromFlatIndex(index : i32) -> i32 {
return index;
}
`) : this.updatesRank === 2 && (s = "coords[0], coords[1]", r = "vec2<i32>(flattenedIndex, coords[1])", a = `
fn getUpdatesCoordsFromFlatIndex(index : i32) -> vec2<i32> {
let d0 = index / uniforms.updatesShape[1];
let d1 = index - d0 * uniforms.updatesShape[1];
return vec2<i32>(d0, d1);
}
`);
let o = `getUpdates(${s})`, i = this.type === "int32" ? "atomicAdd(&(result[flatIndex]), i32(updateValue));" : `
var oldValue = atomicLoad(&(result[flatIndex]));
var exchanged = false;
for (; !exchanged;) {
let newValueF32 = bitcast<f32>(oldValue) + updateValue;
let newValue = bitcast<i32>(newValueF32);
let res = atomicCompareExchangeWeak(&(result[flatIndex]), oldValue, newValue);
oldValue = res.old_value;
exchanged = res.exchanged;
}
`;
return `
${a}
${Ue()}
if (index < uniforms.size) {
let coords = getUpdatesCoordsFromFlatIndex(index);
var flattenedIndex = 0;
for (var j = 0; j < uniforms.sliceDim; j = j + 1) {
let indexInside = i32(round(${t}));
flattenedIndex = flattenedIndex + indexInside * ${n};
}
let updateValue = ${o};
let flatIndex = getOutputIndexFromCoords(${r});
${i}
}
}`;
}
};
function eie(e) {
let { inputs: t, backend: n, attrs: s } = e, { indices: r, updates: a } = t, { shape: o } = s, { sliceRank: i, numUpdates: u, sliceSize: l, strides: c, outputSize: p } = C.calculateShapes(a, r, o), d = [p / l, l];
if (p === 0)
return n.makeTensorInfo(o, r.dtype);
let h = Le({ inputs: { x: r }, backend: n, attrs: { shape: [u, i] } }), f = Le({ inputs: { x: a }, backend: n, attrs: { shape: [u, l] } }), m = f.dtype, g = mu({ backend: n, attrs: { shape: d, value: 0, dtype: m } }), b = w.sizeFromShape(f.shape), y = [{ type: "int32", data: [i] }, { type: "int32", data: c }, { type: "int32", data: [b] }], v = new Joe(f.shape, i, h.shape.length, f.shape.length, c, d, m), x = n.runWebGPUProgram(v, [f, h], m, y, g), k = Le({ inputs: { x }, backend: n, attrs: { shape: o } });
return n.disposeData(h.dataId), n.disposeData(f.dataId), n.disposeData(x.dataId), k;
}
var tie = { kernelName: Li, backendName: "webgpu", kernelFunc: eie };
var nie = class {
constructor(e, t, n) {
this.variableNames = ["c", "a", "b"], this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = t, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.cRank = e, this.rank = n, this.shaderKey = "select";
}
getUserCode() {
let e, t;
if (this.rank > 4)
throw Error(`Where for rank ${this.rank} is not yet supported`);
if (this.rank === 1)
t = "resRC", e = "resRC";
else {
let s = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"], r = [], a = [];
for (let o = 0; o < this.outputShape.length; o++)
a.push(`${s[o]}`), o < this.cRank && r.push(`${s[o]}`);
e = r.join(), t = a.join();
}
return `
${Ue()}
if (index < uniforms.size) {
let resRC = getCoordsFromIndex(index);
let cVal = getC(${e});
if (cVal >= 1.0) {
setOutputAtIndex(index, getA(${t}));
} else {
setOutputAtIndex(index, getB(${t}));
}
}
}
`;
}
};
function sie(e) {
let { inputs: t, backend: n } = e, { condition: s, t: r, e: a } = t, o = new nie(s.shape.length, r.shape, r.shape.length);
return n.runWebGPUProgram(o, [s, r, a], cn(r.dtype, a.dtype));
}
var rie = { kernelName: Mi, backendName: "webgpu", kernelFunc: sie };
var aie = Kt({ opType: 18 });
var oie = { kernelName: uo, backendName: "webgpu", kernelFunc: aie };
var iie = Kt({ opType: 16 });
var uie = { kernelName: io, backendName: "webgpu", kernelFunc: iie };
var lie = Kt({ opType: 17 });
var cie = { kernelName: Vi, backendName: "webgpu", kernelFunc: lie };
var nN = gn({ opSnippet: 2, cpuKernelImpl: Kse, supportsComplex: true });
var die = { kernelName: fo, backendName: "webgpu", kernelFunc: nN };
function pie(e) {
let { inputs: t, backend: n, attrs: s } = e, { logits: r } = t, { dim: a } = s, o = w.parseAxisParam([a], r.shape), i = Z2({ inputs: { x: r }, backend: n, attrs: { reductionIndices: o, keepDims: false } }), u = C.expandShapeToKeepDim(i.shape, o), l = Le({ inputs: { x: i }, backend: n, attrs: { shape: u } }), c = nN({ inputs: { a: r, b: l }, backend: n }), p = Y2({ inputs: { x: c }, backend: n }), d = Vv({ inputs: { x: p }, backend: n, attrs: { axis: o, keepDims: false } }), h = Le({ inputs: { x: d }, backend: n, attrs: { shape: u } }), f = tN({ inputs: { a: p, b: h }, backend: n });
return n.disposeData(i.dataId), n.disposeData(l.dataId), n.disposeData(c.dataId), n.disposeData(p.dataId), n.disposeData(d.dataId), n.disposeData(h.dataId), f;
}
var hie = { kernelName: po, backendName: "webgpu", kernelFunc: pie };
var fie = (e) => {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { blockShape: a, paddings: o } = s;
w.assert(r.shape.length <= 4, () => "spaceToBatchND for rank > 4 with a WebGPU backend not implemented yet");
let i = a.reduce((b, y) => b * y), u = [[0, 0]];
u.push(...o);
for (let b = 1 + a.length; b < r.shape.length; ++b)
u.push([0, 0]);
let l = [], c = eN({ inputs: { x: r }, backend: n, attrs: { paddings: u, constantValue: 0 } }), p = C.getReshaped(c.shape, a, i, false), d = C.getPermuted(p.length, a.length, false), h = C.getReshapedPermuted(c.shape, a, i, false), f = Le({ inputs: { x: c }, backend: n, attrs: { shape: p } }), m = Ks({ inputs: { x: f }, backend: n, attrs: { perm: d } }), g = Le({ inputs: { x: m }, backend: n, attrs: { shape: h } });
return l.push(c), l.push(f), l.push(m), l.forEach((b) => n.disposeData(b.dataId)), g;
};
var mie = { kernelName: Wi, backendName: "webgpu", kernelFunc: fie };
var gie = class {
constructor(e, t, n, s, r, a, o = true) {
this.variableNames = ["updates", "indices", "defaultValue"], this.workGroupSize = [64, 1, 1], this.workPerThread = 4, this.size = true, this.outputShape = a, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize, [this.workPerThread, 1, 1]);
let i = t > 1;
this.shaderKey = `scatter_${n}_${s}_${i}`;
let u = Wt(r.length);
this.uniforms = `updateSize : i32, sliceDim : i32, strides: ${u},`;
let l = "";
n === 1 ? l = "i" : n === 2 && (l = "i, j"), this.indicesSnippet = `getIndices(${l})`;
let c = "";
s === 1 ? c = "i" : s === 2 && (c = "i, coords[1]"), this.updatesSnippet = `getUpdates(${c})`, this.strideString = i ? "uniforms.strides[j]" : "uniforms.strides";
}
getUserCode() {
return `
${Ue()}
let globalIndex = index * ${this.workPerThread};
if (globalIndex < uniforms.size) {
var sum = vec4<f32>(0.0);
var found = vec4<bool>(false);
for (var i = 0; i < uniforms.updateSize; i = i + 1) {
var flattenedIndex = 0;
for (var j = 0; j < uniforms.sliceDim; j = j + 1) {
let indexInside = i32(round(${this.indicesSnippet}));
flattenedIndex = flattenedIndex + indexInside * ${this.strideString};
}
for (var innerIndex = 0; innerIndex < ${this.workPerThread}; innerIndex = innerIndex + 1) {
let curIndex = globalIndex + innerIndex;
let coords = getCoordsFromIndex(curIndex);
if (flattenedIndex == coords[0]) {
sum[innerIndex] = sum[innerIndex] + ${this.updatesSnippet};
found[innerIndex] = true;
}
}
}
for (var innerIndex = 0; innerIndex < ${this.workPerThread}; innerIndex = innerIndex + 1) {
let curIndex = globalIndex + innerIndex;
if (curIndex < uniforms.size)
{
setOutputAtIndex(curIndex, mix(getDefaultValue(), sum[innerIndex], f32(found[innerIndex])));
}
}
}
}`;
}
};
function bie(e) {
let { inputs: t, backend: n, attrs: s } = e, { sparseIndices: r, sparseValues: a, defaultValue: o } = t, { outputShape: i } = s, { sliceRank: u, numUpdates: l, sliceSize: c, strides: p, outputSize: d } = C.calculateShapes(a, r, i), h = false;
if (a.dtype === "string") {
let y = n.bufferSync(r), v = n.bufferSync(a), x = w.decodeString(n.readSync(o.dataId)[0]), k = Use(y, v, i, d, c, l, u, p, x, h);
return n.makeTensorInfo(i, k.dtype, k.values);
}
let f = [{ type: "int32", data: [l] }, { type: "int32", data: [u] }, { type: "int32", data: p }], m = new gie(l, u, r.shape.length, a.shape.length, p, [d, 1], h), g = n.runWebGPUProgram(m, [a, r, o], a.dtype, f), b = Le({ inputs: { x: g }, backend: n, attrs: { shape: i } });
return n.disposeData(g.dataId), b;
}
var yie = { kernelName: fp, backendName: "webgpu", kernelFunc: bie };
function vie(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { numOrSizeSplits: a, axis: o } = s, i = w.parseAxisParam(o, r.shape)[0], u = C.prepareSplitSize(r, a, i), l = r.shape.length, c = new Array(l).fill(0), p = r.shape.slice();
return u.map((d) => {
let h = [...p];
h[i] = d;
let f = fu({ inputs: { x: r }, backend: n, attrs: { begin: c, size: h } });
return c[i] += d, f;
});
}
var xie = { kernelName: Ui, backendName: "webgpu", kernelFunc: vie };
var wie = Kt({ opType: 19 });
var kie = { kernelName: lo, backendName: "webgpu", kernelFunc: wie };
var Sie = { kernelName: Fl, backendName: "webgpu", kernelFunc: ({ inputs: e, backend: t }) => {
let { x: n } = e, s = t, r = new oc(n.shape, 20);
return s.runWebGPUProgram(r, [n], n.dtype);
} };
var Iie = gn({ opSnippet: 11 });
var Cie = { kernelName: ho, backendName: "webgpu", kernelFunc: Iie };
var Nie = class {
constructor(e) {
this.variableNames = ["x"], this.workPerThread = 1, this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize, [this.workPerThread, 1, 1]);
let t = Wt(this.outputShape.length);
this.uniforms = `begin : ${t}, strides : ${t}, `, this.shaderKey = "stridedSlice";
}
getUserCode() {
let e = this.outputShape.length, t = "";
if (e === 1)
t = "coords * uniforms.strides + uniforms.begin";
else {
let s = 0;
t = this.outputShape.map((r, a) => (s++, this.outputShape.length === 1 ? `coords * uniforms.strides[${a}] + uniforms.begin[${a}]` : `coords[${s - 1}] * uniforms.strides[${a}] + uniforms.begin[${a}]`)).join(",");
}
return `
${Ue()}
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
setOutputAtIndex(index, getX(${t}));
}
}
`;
}
};
function Tie(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { begin: a, end: o, strides: i, beginMask: u, endMask: l, ellipsisMask: c, newAxisMask: p, shrinkAxisMask: d } = s, { finalShapeSparse: h, finalShape: f, isIdentity: m, sliceDim0: g, isSimpleSlice: b, begin: y, end: v, strides: x } = kt.sliceInfo(r.shape, a, o, i, u, l, c, p, d), k;
if (m)
k = Le({ inputs: { x: r }, backend: n, attrs: { shape: f } });
else if (g || b) {
w.assert(r.shape.length >= 1, () => `Input must have rank at least 1, got: ${r.shape.length}`);
let I = kt.computeOutShape(y, v, x), $ = fu({ inputs: { x: r }, backend: n, attrs: { begin: y, size: I } });
k = Le({ inputs: { x: $ }, backend: n, attrs: { shape: f } }), n.disposeData($.dataId);
} else if (n.shouldExecuteOnCPU([r])) {
let $ = n.readSync(r.dataId), R = Ae(r.shape, r.dtype, $), E = qse(h, R, x, y);
k = n.makeTensorInfo(f, r.dtype, E.values);
} else {
let $ = new Nie(h), R = [{ type: "int32", data: y }, { type: "int32", data: x }], E = n.runWebGPUProgram($, [r], r.dtype, R);
k = Le({ inputs: { x: E }, backend: n, attrs: { shape: f } }), n.disposeData(E.dataId);
}
return k;
}
var $ie = { kernelName: Gi, backendName: "webgpu", kernelFunc: Tie };
function _ie(e) {
let { inputs: t, backend: n, attrs: s } = e, { separator: r, nGramWidths: a, leftPad: o, rightPad: i, padWidth: u, preserveShortSequences: l } = s, { data: c, dataSplits: p } = t, d = n.readSync(c.dataId), h = n.readSync(p.dataId), [f, m] = jse(d, h, r, a, o, i, u, l);
return [n.makeTensorInfo([f.length], "string", f), n.makeTensorInfo(p.shape, "int32", m)];
}
var Aie = { kernelName: mp, backendName: "webgpu", kernelFunc: _ie };
var Eie = Kt({ opType: 21 });
var Rie = { kernelName: mo, backendName: "webgpu", kernelFunc: Eie };
var Die = class {
constructor(e, t) {
this.variableNames = ["A"], this.workGroupSize = [64, 1, 1], this.size = true;
let n = new Array(e.length);
for (let s = 0; s < n.length; s++)
n[s] = e[s] * t[s];
this.outputShape = n, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.rank = this.outputShape.length, this.shaderKey = "tile";
}
getUserCode() {
let e = Fie(this.rank, "uniforms.");
return `
${Ue()}
if (index < uniforms.size) {
let resRC = getCoordsFromIndex(index);
setOutputAtIndex(index, getA(${e}));
}
}
`;
}
};
function Fie(e, t = "") {
if (e >= 5)
throw Error(`Tile for rank ${e} is not yet supported`);
if (e === 1)
return `(resRC % ${t}aShape)`;
let n = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"], s = [];
for (let r = 0; r < e; r++)
s.push(`(${n[r]} % ${t}aShape[${r}])`);
return s.join();
}
function Oie(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { reps: a } = s;
if (n.shouldExecuteOnCPU([r]) || r.dtype === "string" || r.shape.length >= 5) {
let u = n.readSync(r.dataId), l = r.dtype === "string" ? u.map((d) => w.decodeString(d)) : u, c = Ae(r.shape, r.dtype, l), p = Xse(c, a);
return n.makeTensorInfo(p.shape, p.dtype, p.values);
}
let o = new Die(r.shape, a);
return n.runWebGPUProgram(o, [r], r.dtype);
}
var Pie = { kernelName: Tr, backendName: "webgpu", kernelFunc: Oie };
var zie = class {
constructor(e) {
this.variableNames = ["x", "indices"], this.workGroupSize = [256, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.uniforms = `inputSize : i32, firstPass : i32, negativeInf : f32,
dir : i32, inc : i32,`, this.shaderKey = "swap";
}
getUserCode() {
return `
${Ue()}
if (index < uniforms.size) {
let outC = getCoordsFromIndex(index);
let batch = outC[0];
let elemIdx = outC[1];
// We compare elements pair-wise within a group of size 2 * inc.
// The comparing rule for each group alternates between ascending
// and descending. Within each group, we compare each pair at
// positions i and i+inc. To decide whether an element at position i
// is x0 or x1, we mod it by 2 * inc, if the result is smaller than
// inc, it is in the first half of the group, we denote it as x0,
// otherwise we denote it as x1.
// For example, as shown in the Bitonic top K paper referenced
// above, Figure5(a) shows that element[1] is in the second half of
// the group when group size is 2, but it is in the first half of
// the group when group size is 4.
let isFirstInPair = elemIdx % (2 * uniforms.inc) < uniforms.inc;
var i = 0;
if (isFirstInPair) {
i = elemIdx;
} else {
i = elemIdx - uniforms.inc;
}
var i0 = 0;
if (uniforms.firstPass == 1) {
i0 = i;
} else {
i0 = i32(getIndices(batch, i));
}
var i1 = 0;
if (uniforms.firstPass == 1) {
i1 = i + uniforms.inc;
} else {
i1 = i32(getIndices(batch, i + uniforms.inc));
}
var x0 = f32(0.0);
var x1 = f32(0.0);
if (i0 < uniforms.inputSize) {
x0 = getX(batch, i0);
} else {
x0 = uniforms.negativeInf;
}
if (i1 < uniforms.inputSize) {
x1 = getX(batch, i1);
} else {
x1 = uniforms.negativeInf;
}
let reverse = elemIdx % (2 * uniforms.dir) >= uniforms.dir;
let isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
if (reverse == isGreater) {
// Elements in opposite order of direction
let iTemp = i0;
i0 = i1;
i1 = iTemp;
}
if (isFirstInPair) {
setOutputAtIndex(index, f32(i0));
} else {
setOutputAtIndex(index, f32(i1));
}
}
}
`;
}
};
var Lie = class {
constructor(e) {
this.variableNames = ["x", "indices"], this.workGroupSize = [256, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.uniforms = "inputSize : i32, firstPass : i32, k : i32,", this.shaderKey = "merge";
}
getUserCode() {
return `
${Ue()}
if (index < uniforms.size) {
let outC = getCoordsFromIndex(index);
let batch = outC[0];
let elemIdx = outC[1];
// The output size is half of the previous size.
// If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _
// (k=4), we only need to output the indices at positions |, the
// indices at positions _ can be thrown away, see Figure5(b) After
// Phase 2 (Merge phase) in the Bitonic Top K paper referenced
// above.
// For example, the paper shows we only need to output the orange
// bars. The output sequence should look like this | | | | | | | |.
// Because the sequence is halved, to map the output index back to
// the previous sequence to find the corresponding value, we need
// to double the index. When we double the index, we basically
// interpolate a position, so 2i looks like
// | _ | _ | _ | _ | _ | _ | _. We move the | to the first k
// position of each 2k positions by - elemIdx % k. E.g. for output
// at index 4,5,6,7, we want to get the corresponding element at
// original index 8,9,10,11, for output at index 8,9,10,11,
// we want to get the corresponding element at original index
// 16,17,18,19, so on and so forth.
var i = 0;
if (elemIdx < uniforms.k) {
i = elemIdx;
} else {
i = elemIdx * 2 - elemIdx % uniforms.k;
}
var i0 = 0;
if (uniforms.firstPass == 1) {
i0 = i;
} else {
i0 = i32(getIndices(batch, i));
}
var i1 = 0;
if (uniforms.firstPass == 1) {
i1 = i + uniforms.k;
} else {
i1 = i32(getIndices(batch, i + uniforms.k));
}
let x0 = getX(batch, i0);
var x1 = f32(0.0);
if (i1 < uniforms.inputSize) {
x1 = getX(batch, i1);
} else {
x1 = x0;
}
if (x0 >= x1) {
setOutputAtIndex(index, f32(i0));
} else {
setOutputAtIndex(index, f32(i1));
}
}
}
`;
}
};
function Go(e, t) {
t !== null && e.disposeData(t.dataId);
}
function Xw(e) {
let t = 1;
for (; t < e; )
t *= 2;
return t;
}
function Mie(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { k: a, sorted: o } = s, i = r.shape, u = i[i.length - 1];
if (n.shouldExecuteOnCPU([r])) {
let k = n.readSync(r.dataId), [I, $] = Yse(k, i, r.dtype, a, o);
return [n.makeTensorInfo(I.shape, I.dtype, I.values), n.makeTensorInfo($.shape, $.dtype, $.values)];
}
if (a === 0)
return i[i.length - 1] = 0, [n.makeTensorInfo(i, r.dtype, []), n.makeTensorInfo(i, "int32", [])];
if (u === 1)
return [r, mu({ attrs: { shape: i, dtype: "int32", value: 0 }, backend: n })];
let c = w.sizeFromShape(i) / u, p = Le({ inputs: { x: r }, attrs: { shape: [c, u] }, backend: n }), d = Xw(a), h = Xw(u), f = null, m = () => f === null ? [p, p] : [p, f], g = (k, I, $) => {
let R = m(), E = new zie($), A = [{ type: "int32", data: [u] }, { type: "int32", data: [f === null ? 1 : 0] }, { type: "float32", data: [Number.NEGATIVE_INFINITY] }, { type: "int32", data: [k] }, { type: "int32", data: [I] }], D = f;
f = n.runWebGPUProgram(E, R, "int32", A), Go(n, D);
};
for (let k = 1; k < d; k *= 2) {
let I = k * 2;
for (let $ = k; $ >= 1; $ /= 2)
g(I, $, [c, h]);
}
for (let k = h; k > d; k /= 2) {
let I = m(), $ = new Lie([c, k / 2]), E = [{ type: "int32", data: [u] }, { type: "int32", data: [f === null ? 1 : 0] }, { type: "int32", data: [d] }], P = f;
f = n.runWebGPUProgram($, I, "int32", E), Go(n, P);
let A = d / 2, D = A * 2;
for (let T = A; T >= 1; T /= 2)
g(D, T, f.shape);
}
let b = f;
f = fu({ inputs: { x: f }, backend: n, attrs: { begin: 0, size: [c, a] } }), Go(n, b);
let y = Q2({ inputs: { x: p, indices: f }, backend: n, attrs: { axis: 1, batchDims: 1 } });
Go(n, p);
let v = i.slice(0, -1);
v.push(a), b = f, f = Le({ inputs: { x: f }, attrs: { shape: v }, backend: n }), Go(n, b);
let x = y;
return y = Le({ inputs: { x: y }, attrs: { shape: v }, backend: n }), Go(n, x), [y, f];
}
var Bie = { kernelName: qi, backendName: "webgpu", kernelFunc: Mie };
var Vie = class {
constructor(e) {
this.variableNames = ["Image", "Transforms"], this.uniforms = "interpolationModeId : i32, fillModeId : i32, fillValue : f32,", this.workGroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = Ve(this.outputShape), this.dispatch = _e(this.dispatchLayout, this.outputShape, this.workGroupSize), this.shaderKey = "transform";
}
getUserCode() {
return `
fn mapCoord(outCoord : f32, len : f32) -> f32{
var inCoord = outCoord;
if(uniforms.fillModeId == 2) {
if (inCoord < 0.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
let sz2 = 2.0 * len;
if (inCoord < sz2) {
inCoord = sz2 * f32(i32(f32(-inCoord / sz2))) +
inCoord;
}
if (inCoord < -len) {
inCoord = inCoord + sz2;
} else {
inCoord = -inCoord - 1.0;
}
}
} else if (inCoord > len - 1.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
let sz2 = 2.0 * len;
inCoord = inCoord - sz2 * f32(i32(f32(inCoord / sz2)));
if (inCoord >= len) {
inCoord = sz2 - inCoord - 1.0;
}
}
}
return clamp(inCoord, 0.0, len - 1.0);
} else if (uniforms.fillModeId == 3) {
if (inCoord < 0.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
let sz = len - 1.0;
inCoord = inCoord + len * (f32(i32(f32(-inCoord / sz))) + 1.0);
}
} else if (inCoord > len - 1.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
let sz = len - 1.0;
inCoord = inCoord - len * f32(i32(f32(inCoord / sz)));
}
}
return clamp(inCoord, 0.0, len - 1.0);
} else if (uniforms.fillModeId == 4) {
return clamp(outCoord, 0.0, len - 1.0);
}
return outCoord;
}
fn readWithFillValue(batch : i32, coordY : i32, coordX : i32,
channel : i32) -> f32 {
var outputValue : f32;
if (0 <= coordY && coordY < uniforms.imageShape[1] && 0 <= coordX && coordX < uniforms.imageShape[2]) {
outputValue = getImage(batch, coordY, coordX, channel);
} else {
outputValue = uniforms.fillValue;
}
return outputValue;
}
${Ue()}
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
var outputValue : f32;
let batch = coords[0];
let x = coords[2];
let y = coords[1];
let channel = coords[3];
let xf = f32(x);
let yf = f32(y);
let a1 = getTransforms(batch, 0);
let a2 = getTransforms(batch, 1);
let a3 = getTransforms(batch, 2);
let b1 = getTransforms(batch, 3);
let b2 = getTransforms(batch, 4);
let b3 = getTransforms(batch, 5);
let c1 = getTransforms(batch, 6);
let c2 = getTransforms(batch, 7);
let projection = c1 * xf + c2 * yf + 1.0;
if (projection == 0.0) {
outputValue = uniforms.fillValue;
} else {
let inX = (a1 * xf + a2 * yf + a3) / projection;
let inY = (b1 * xf + b2 * yf + b3) / projection;
let mapX = mapCoord(inX, f32(uniforms.imageShape[2]));
let mapY = mapCoord(inY, f32(uniforms.imageShape[1]));
if (uniforms.interpolationModeId == 1) {
let coordY = i32(round(mapY));
let coordX = i32(round(mapX));
outputValue = readWithFillValue(batch, coordY, coordX,
channel);
} else {
let yFloor = floor(mapY);
let xFloor = floor(mapX);
let yCeil = yFloor + 1.0;
let xCeil = xFloor + 1.0;
let valueYFloor = (xCeil - mapX) *
readWithFillValue(batch, i32(yFloor), i32(xFloor), channel) +
(mapX - xFloor) *
readWithFillValue(batch, i32(yFloor), i32(xCeil), channel);
let valueYCeil = (xCeil - mapX) *
readWithFillValue(batch, i32(yCeil), i32(xFloor), channel) +
(mapX - xFloor) *
readWithFillValue(batch, i32(yCeil), i32(xCeil), channel);
outputValue = (yCeil - mapY) * valueYFloor +
(mapY - yFloor) * valueYCeil;
}
}
setOutputAtIndex(index, outputValue);
}
}
`;
}
};
function Wie(e) {
let { inputs: t, backend: n, attrs: s } = e, { image: r, transforms: a } = t, { interpolation: o, fillMode: i, fillValue: u, outputShape: l } = s, [c, p, d, h] = r.shape, [f, m] = l != null ? l : [p, d], g = [c, f, m, h], b = new Vie(g), y = o === "nearest" ? 1 : 2, v;
switch (i) {
case "constant":
v = 1;
break;
case "reflect":
v = 2;
break;
case "wrap":
v = 3;
break;
case "nearest":
v = 4;
break;
default:
v = 1;
break;
}
let x = [{ type: "int32", data: [y] }, { type: "int32", data: [v] }, { type: "float32", data: [u] }];
return n.runWebGPUProgram(b, [r, a], "float32", x);
}
var Uie = { kernelName: ji, backendName: "webgpu", kernelFunc: Wie };
function Gie(e) {
let { inputs: t, backend: n, attrs: s } = e, { value: r } = t, { axis: a } = s;
a < 0 && (a += r.shape.length);
let o = r, i = o.shape.length, u = r.shape[a], l = new Array(i - 1), c = 0;
for (let m = 0; m < i; m++)
m !== a && (l[c++] = o.shape[m]);
let p = [], d = new Array(i).fill(0), h = o.shape.slice();
h[a] = 1;
let f = new Array(u);
for (let m = 0; m < f.length; m++) {
d[a] = m;
let g = fu({ inputs: { x: o }, backend: n, attrs: { begin: d, size: h } }), b = Le({ inputs: { x: g }, backend: n, attrs: { shape: l } });
f[m] = b, p.push(g);
}
return p.forEach((m) => n.disposeData(m.dataId)), f;
}
var Hie = { kernelName: Ki, backendName: "webgpu", kernelFunc: Gie };
var qie = [mse, Jse, tre, rre, cre, pre, fre, gre, wre, Cre, Tre, Ere, vse, Ore, Bre, Gre, qre, Kre, Qre, Jre, tae, rae, oae, dae, hae, mae, gae, bae, vae, wae, Sae, _ae, Cae, Tae, Rae, Fae, Pae, Mae, Wae, Gae, qae, yse, Dre, Kae, Yae, Zae, eoe, noe, roe, aoe, ioe, loe, doe, hoe, moe, boe, iae, voe, woe, Soe, kre, Coe, Toe, _oe, Eoe, Doe, Ooe, zoe, Sre, Loe, Boe, Woe, hse, Hoe, Koe, Yoe, Zoe, tie, rie, oie, uie, cie, vre, $ie, Aie, hie, mie, yie, xie, kie, Sie, Cie, die, lae, Rie, Pie, Bie, Uie, ure, Hie, Ioe];
for (let e of qie)
Ol(e);
var jie = class {
constructor(e) {
this.device = e, this.numUsedBuffers = 0, this.numFreeBuffers = 0, this.freeBuffers = /* @__PURE__ */ new Map(), this.usedBuffers = /* @__PURE__ */ new Map(), this.numBytesUsed = 0, this.numBytesAllocated = 0;
}
acquireUploadBuffer(e, t) {
return this.acquireBuffer(e, t, true);
}
acquireBuffer(e, t, n = false) {
let s = Yw(e, t);
if (this.freeBuffers.has(s) || this.freeBuffers.set(s, []), this.usedBuffers.has(s) || this.usedBuffers.set(s, []), this.numBytesUsed += e, this.numUsedBuffers++, this.freeBuffers.get(s).length > 0) {
this.numFreeBuffers--;
let a = this.freeBuffers.get(s).shift();
return this.usedBuffers.get(s).push(a), a;
}
this.numBytesAllocated += e;
let r = this.device.createBuffer({ mappedAtCreation: n, size: e, usage: t });
return this.usedBuffers.get(s).push(r), r;
}
releaseBuffer(e, t, n) {
if (this.freeBuffers.size === 0)
return;
let s = Yw(t, n);
this.freeBuffers.has(s) || this.freeBuffers.set(s, []), this.freeBuffers.get(s).push(e), this.numFreeBuffers++, this.numUsedBuffers--;
let r = this.usedBuffers.get(s), a = r.indexOf(e);
if (a < 0)
throw new Error("Cannot release a buffer that was never provided by this buffer manager");
r.splice(a, 1), this.numBytesUsed -= t;
}
releaseUploadBuffer(e, t, n) {
e.mapAsync(GPUMapMode.WRITE).then(() => {
this.releaseBuffer(e, t, n);
}, (s) => {
});
}
getNumUsedBuffers() {
return this.numUsedBuffers;
}
getNumFreeBuffers() {
return this.numFreeBuffers;
}
dispose() {
this.freeBuffers.forEach((e, t) => {
e.forEach((n) => {
n.destroy();
});
}), this.usedBuffers.forEach((e, t) => {
e.forEach((n) => {
n.destroy();
});
}), this.freeBuffers = /* @__PURE__ */ new Map(), this.usedBuffers = /* @__PURE__ */ new Map(), this.numUsedBuffers = 0, this.numFreeBuffers = 0, this.numBytesUsed = 0, this.numBytesAllocated = 0;
}
};
function Yw(e, t) {
return `${e}_${t}`;
}
var Kie = class {
constructor(e) {
this.device = e, this.numUsedTextures = 0, this.numFreeTextures = 0, this.freeTextures = /* @__PURE__ */ new Map(), this.usedTextures = /* @__PURE__ */ new Map(), this.numBytesUsed = 0, this.numBytesAllocated = 0;
}
acquireTexture(e, t, n, s) {
let r = Zw(n), a = e * t * r, o = Qw(e, t, n, s);
if (this.freeTextures.has(o) || this.freeTextures.set(o, []), this.usedTextures.has(o) || this.usedTextures.set(o, []), this.numBytesUsed += a, this.numUsedTextures++, this.freeTextures.get(o).length > 0) {
this.numFreeTextures--;
let u = this.freeTextures.get(o).shift();
return this.usedTextures.get(o).push(u), u;
}
this.numBytesAllocated += a;
let i = this.device.createTexture({ size: [e, t], format: n, usage: s });
return this.usedTextures.get(o).push(i), i;
}
releaseTexture(e, t, n, s, r) {
if (this.freeTextures.size === 0)
return;
let a = Qw(t, n, s, r);
this.freeTextures.has(a) || this.freeTextures.set(a, []), this.freeTextures.get(a).push(e), this.numFreeTextures++, this.numUsedTextures--;
let o = this.usedTextures.get(a), i = o.indexOf(e);
if (i < 0)
throw new Error("Cannot release a texture that was never provided by this texture manager");
o.splice(i, 1);
let u = Zw(s), l = t * n * u;
this.numBytesUsed -= l;
}
getNumUsedTextures() {
return this.numUsedTextures;
}
getNumFreeTextures() {
return this.numFreeTextures;
}
dispose() {
this.freeTextures.forEach((e, t) => {
e.forEach((n) => {
n.destroy();
});
}), this.usedTextures.forEach((e, t) => {
e.forEach((n) => {
n.destroy();
});
}), this.freeTextures = /* @__PURE__ */ new Map(), this.usedTextures = /* @__PURE__ */ new Map(), this.numUsedTextures = 0, this.numFreeTextures = 0, this.numBytesUsed = 0, this.numBytesAllocated = 0;
}
};
function Qw(e, t, n, s) {
return `${e}_${t}_${n}_${s}`;
}
function Zw(e) {
if (e === "rgba8unorm")
return 16;
throw new Error(`${e} is not supported!`);
}
var Xie = K().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD");
var Jw = (e, t) => {
let n = e.limits.maxComputeWorkgroupsPerDimension, s = t.dispatchLayout, r = t.dispatch;
if (r.every((o) => o <= n))
return r;
w.assert(r[0] > n && s.y === void 0 && s.z === void 0, () => "Dispatch size exceeds WebGPU limits in Y or Z dimension.");
let a = Math.ceil(Math.sqrt(r[0]));
return a > n ? (a = Math.ceil(Math.cbrt(r[0])), w.assert(a <= n, () => "Total dispatch size exceeds WebGPU maximum."), [a, a, a]) : [a, a, 1];
};
var sN = class extends il {
constructor(e, t = false) {
if (super(), this.commandQueueOwnedIds = /* @__PURE__ */ new WeakSet(), this.tensorDisposalQueue = [], this.uniformDisposalQueue = [], this.stagingDisposalQueue = [], this.textureDisposalQueue = [], this.disposed = false, this.uploadWaitMs = 0, this.downloadWaitMs = 0, this.dispatchNumberInEncoder = 0, this.fromPixelTextureLayout = null, this.fromPixelImportTextureLayout = null, !zv())
throw new Error("WebGPU is not supported on this device");
this.layoutCache = {}, this.pipelineCache = {}, this.device = e, this.queue = e.queue, this.currentCommandEncoder = null, this.currentComputePass = null, this.supportTimeQuery = t, this.bufferManager = new jie(this.device), this.textureManager = new Kie(this.device), this.tensorMap = new Zd(this, ds()), this.supportTimeQuery && (this.querySet = this.device.createQuerySet({ type: "timestamp", count: 2 })), K().getBool("WEBGPU_USE_PROFILE_TOOL") && (this.dummyCanvas = document.createElement("canvas"), this.dummyCanvas.width = 1, this.dummyCanvas.height = 1, this.dummyContext = this.dummyCanvas.getContext("webgpu"), this.dummyContext.configure({ device: e, format: "bgra8unorm" }), document.body.appendChild(this.dummyCanvas));
}
nextDataId() {
return sN.nextDataId++;
}
floatPrecision() {
return 32;
}
defaultGpuBufferUsage() {
return GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
}
flushDisposalQueue() {
this.tensorDisposalQueue.forEach((e) => {
this.maybeReleaseBuffer(e), this.tensorMap.delete(e);
}), this.uniformDisposalQueue.forEach((e) => this.bufferManager.releaseBuffer(e.buffer, e.byteSize, e.usage)), this.stagingDisposalQueue.forEach((e) => this.bufferManager.releaseUploadBuffer(e.buffer, e.byteSize, e.usage)), this.textureDisposalQueue.forEach((e) => this.textureManager.releaseTexture(e.texture, e.width, e.height, e.format, e.usage)), this.tensorDisposalQueue = [], this.uniformDisposalQueue = [], this.stagingDisposalQueue = [], this.textureDisposalQueue = [];
}
disposeData(e, t = false) {
if (this.tensorMap.has(e)) {
let n = this.tensorMap.get(e);
if (n.refCount--, !t && n.refCount > 0)
return false;
if (this.commandQueueOwnedIds.has(e))
return this.tensorDisposalQueue.push(e), false;
this.maybeReleaseBuffer(e);
let { complexTensorInfos: s } = this.tensorMap.get(e);
s != null && (this.disposeData(s.real.dataId, true), this.disposeData(s.imag.dataId, true)), this.tensorMap.delete(e);
}
return true;
}
memory() {
return { numBytesInGPU: this.bufferManager.numBytesUsed, numBytesAllocatedInGPU: this.bufferManager.numBytesAllocated, unreliable: false };
}
getBufferManager() {
return this.bufferManager;
}
getTextureManager() {
return this.textureManager;
}
acquireBuffer(e, t = this.defaultGpuBufferUsage()) {
return this.bufferManager.acquireBuffer(e, t);
}
maybeReleaseBuffer(e) {
let t = this.tensorMap.get(e);
t != null && t.bufferInfo.buffer != null && (this.bufferManager.releaseBuffer(t.bufferInfo.buffer, t.bufferInfo.byteSize, t.bufferInfo.usage), t.bufferInfo.buffer = null);
}
refCount(e) {
return this.tensorMap.has(e) ? this.tensorMap.get(e).refCount : 0;
}
incRef(e) {
let t = this.tensorMap.get(e);
t.refCount++;
}
decRef(e) {
if (this.tensorMap.has(e)) {
let t = this.tensorMap.get(e);
t.refCount--;
}
}
write(e, t, n) {
if (n === "complex64" && e != null)
throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");
let s = { id: this.nextDataId() }, r = w.sizeFromShape(t) * md(n);
return this.tensorMap.set(s, { dtype: n, shape: t, values: e, bufferInfo: { byteSize: r, usage: this.defaultGpuBufferUsage() }, refCount: 1 }), s;
}
move(e, t, n, s, r) {
if (s === "complex64")
throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");
let a = w.sizeFromShape(n) * md(s);
this.tensorMap.set(e, { dtype: s, shape: n, values: t, bufferInfo: { byteSize: a, usage: this.defaultGpuBufferUsage() }, refCount: r });
}
submitQueue() {
this.ensureComputePassEnded(), this.queue.submit([this.currentCommandEncoder.finish()]), this.currentCommandEncoder = null, this.dispatchNumberInEncoder = 0, this.commandQueueOwnedIds = /* @__PURE__ */ new WeakSet(), this.flushDisposalQueue();
}
getBuffer(e) {
return this.uploadToGPU(e), this.tensorMap.get(e).bufferInfo.buffer;
}
ensureCommandEncoderReady() {
this.currentCommandEncoder || (this.currentCommandEncoder = this.device.createCommandEncoder());
}
ensureComputePassEnded() {
this.currentComputePass && (this.currentComputePass.end(), this.currentComputePass = null);
}
getComputePass() {
return this.currentComputePass || (this.currentComputePass = this.currentCommandEncoder.beginComputePass()), this.currentComputePass;
}
async getBufferData(e, t) {
let n = this.acquireBuffer(t, GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ);
this.ensureCommandEncoderReady(), this.ensureComputePassEnded(), this.currentCommandEncoder.copyBufferToBuffer(e, 0, n, 0, t), this.submitQueue(), await n.mapAsync(GPUMapMode.READ);
let s = n.getMappedRange().slice(0);
return n.unmap(), n != null && this.bufferManager.releaseBuffer(n, t, GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ), K().getBool("WEBGPU_USE_PROFILE_TOOL") && (w.assert(this.dummyContext !== void 0, () => "Fail to get context for profiling tool"), this.dummyContext.getCurrentTexture()), s;
}
convertAndCacheOnCPU(e, t) {
let n = this.tensorMap.get(e);
return this.maybeReleaseBuffer(e), n.values = t, n.values;
}
readSync(e) {
let t = this.tensorMap.get(e), { values: n } = t;
if (n == null)
throw new Error("WebGPU readSync is only available for CPU-resident tensors.");
return n;
}
async read(e) {
if (!this.tensorMap.has(e))
throw new Error(`Tensor ${e} was not registered!`);
let t = this.tensorMap.get(e), { values: n } = t;
if (n != null)
return this.convertAndCacheOnCPU(e, n);
let s;
if (t.dtype === "complex64") {
let r = await Promise.all([this.read(t.complexTensorInfos.real.dataId), this.read(t.complexTensorInfos.imag.dataId)]), a = r[0], o = r[1];
s = C.mergeRealAndImagArrays(a, o);
} else {
let r = t.values != null ? t.values : await this.getBufferData(t.bufferInfo.buffer, t.bufferInfo.byteSize);
s = P2(r, t.dtype);
}
return this.convertAndCacheOnCPU(e, s), s;
}
readToGPU(e) {
let t = this.tensorMap.get(e), { values: n, dtype: s, shape: r, bufferInfo: a } = t;
if (s === "complex64")
throw new Error("Does not support reading buffer for complex64 dtype.");
if (a.buffer == null)
throw n != null ? new Error("Data is not on GPU but on CPU.") : new Error("There is no data on GPU or CPU.");
let o = w.sizeFromShape(r) * md(s), i = this.acquireBuffer(o);
this.ensureCommandEncoderReady(), this.ensureComputePassEnded(), this.currentCommandEncoder.copyBufferToBuffer(a.buffer, 0, i, 0, o), this.submitQueue();
let u = this.makeTensorInfo(r, s), l = ds().makeTensorFromTensorInfo(u), c = this.tensorMap.get(u.dataId);
return c.bufferInfo.buffer = i, { tensorRef: l, buffer: i, bufSize: o };
}
bufferSync(e) {
let t = this.readSync(e.dataId);
if (e.dtype === "string")
try {
let n = t.map((s) => w.decodeString(s));
return Ae(e.shape, e.dtype, n);
} catch (n) {
throw new Error("Failed to decode encoded string bytes into utf-8");
}
return Ae(e.shape, e.dtype, t);
}
async time(e) {
let t = this.activeTimers, n = [], s = false;
this.programTimersStack == null ? (this.programTimersStack = n, s = true) : this.activeTimers.push(n), this.activeTimers = n, e();
let r = w.flatten(this.activeTimers.map((u) => u.query)).filter((u) => u != null), a = w.flatten(this.activeTimers.map((u) => u.name)).filter((u) => u != null);
this.activeTimers = t, s && (this.programTimersStack = null);
let o = { uploadWaitMs: this.uploadWaitMs, downloadWaitMs: this.downloadWaitMs, kernelMs: null, wallMs: null }, i = await Promise.all(r);
return o.kernelMs = w.sum(i), o.getExtraProfileInfo = () => i.map((u, l) => ({ name: a[l], ms: u })).map((u) => `${u.name}: ${u.ms}`).join(", "), this.uploadWaitMs = 0, this.downloadWaitMs = 0, o;
}
getAndSavePipeline(e, t) {
return e in this.pipelineCache || (this.pipelineCache[e] = t()), this.pipelineCache[e];
}
makeTensorInfo(e, t, n) {
let s;
if (t === "string" && n != null && n.length > 0 && w.isString(n[0])) {
let r = n.map((a) => w.encodeString(a));
s = this.write(r, e, t);
} else
s = this.write(n, e, t);
return { dataId: s, shape: e, dtype: t };
}
tensorToBinding(e) {
if (!e)
return null;
let t = this.tensorMap.get(e.dataId);
return { offset: 0, size: t.bufferInfo.byteSize, buffer: t.bufferInfo.buffer };
}
async getQueryTime(e) {
return this.supportTimeQuery ? this.getTimeFromQuerySet(e) : 0;
}
uploadToGPU(e) {
let t = this.tensorMap.get(e);
if (t.bufferInfo.buffer == null && (t.bufferInfo.buffer = this.acquireBuffer(t.bufferInfo.byteSize), t.values)) {
let n = this.bufferManager.acquireUploadBuffer(t.bufferInfo.byteSize, GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC), s = n.getMappedRange();
t.dtype === "int32" || t.dtype === "bool" ? new Int32Array(s).set(t.values) : new Float32Array(s).set(t.values), n.unmap(), this.ensureCommandEncoderReady(), this.ensureComputePassEnded(), this.currentCommandEncoder.copyBufferToBuffer(n, 0, t.bufferInfo.buffer, 0, t.bufferInfo.byteSize);
let r = { byteSize: t.bufferInfo.byteSize, usage: GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC, buffer: n };
this.stagingDisposalQueue.push(r);
}
}
makeUniforms(e) {
let t = 0, n = 0, s = [];
e.forEach((i) => {
i.data.length === 0 && (i.data = [1]);
let u;
switch (i.data.length) {
case 1:
u = 4;
break;
case 2:
u = 8;
break;
case 3:
u = 16;
break;
case 4:
u = 16;
break;
case 5:
u = 16;
break;
case 6:
u = 16;
break;
default:
w.assert(false, () => `Unsupported ${i.data.length}D shape`);
}
(n === 5 || n === 6) && (u = 16), t = Math.ceil(t / u) * u, n = i.data.length, s.push(t), t += i.data.length * 4;
});
let r = new ArrayBuffer(t);
e.forEach((i, u) => {
let l = s[u];
i.type === "int32" ? new Int32Array(r, l, i.data.length).set(i.data) : i.type === "uint32" ? new Uint32Array(r, l, i.data.length).set(i.data) : new Float32Array(r, l, i.data.length).set(i.data);
});
let a = this.acquireBuffer(t, GPUBufferUsage.COPY_DST | GPUBufferUsage.UNIFORM);
this.queue.writeBuffer(a, 0, r, 0, t);
let o = { byteSize: t, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.UNIFORM, buffer: a };
return this.uniformDisposalQueue.push(o), { offset: 0, size: t, buffer: a };
}
createLayout(e) {
let t = [];
t.push({ binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage" } });
for (let r = 0; r < e; r++)
t.push({ binding: r + 1, visibility: GPUShaderStage.COMPUTE, buffer: { type: "read-only-storage" } });
t.push({ binding: e + 1, visibility: GPUShaderStage.COMPUTE, buffer: { type: "uniform" } });
let n = this.device.createBindGroupLayout({ entries: t }), s = this.device.createPipelineLayout({ bindGroupLayouts: [n] });
return { bindGroupLayout: n, pipelineLayout: s };
}
getCachedOrCreateLayout(e) {
return e in this.layoutCache || (this.layoutCache[e] = this.createLayout(e)), this.layoutCache[e];
}
makeBindGroup(e, t, n, s, r) {
let a = [s, ...n];
return r && a.push(r), e.createBindGroup({ layout: t, entries: a.map((o, i) => ({ binding: i, resource: o })) });
}
runWebGPUProgram(e, t, n, s, r) {
if (!r) {
if (r = this.makeTensorInfo(e.outputShape, n), w.sizeFromShape(r.shape) === 0) {
let I = this.tensorMap.get(r.dataId);
return I.values = w.getTypedArrayFromDType(r.dtype, 0), r;
}
this.uploadToGPU(r.dataId);
}
e.dispatch = Jw(this.device, e);
let a = [{ type: "float32", data: [NaN] }], o = t.concat(r).map((I) => I.shape), i = "int32";
o.map((I) => {
a.push({ type: i, data: I });
});
let u = w.computeStrides(r.shape);
if (a.push({ type: i, data: u }), e.size) {
let I = w.sizeFromShape(e.outputShape);
a.push({ type: i, data: [e.isVec4 ? I / 4 : I] });
}
s && (a = [...a, ...s]);
let l = this.makeUniforms(a), c = t.map((I, $) => {
if (I.dtype === "complex64")
throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");
return this.uploadToGPU(I.dataId), { dtype: this.tensorMap.get(I.dataId).dtype, shape: I.shape, name: e.variableNames[$] };
}), p = c.map((I) => I.dtype).concat(r.dtype), d = c.map((I) => C.getBroadcastDims(I.shape, r.shape)), h = c.map((I) => w.arraysEqual(I.shape, r.shape)).join("_"), f = d.map((I) => I.join("_")).join(";"), m = Mw(e, o, p, f, h), { bindGroupLayout: g, pipelineLayout: b } = this.getCachedOrCreateLayout(e.variableNames.length), y = this.getAndSavePipeline(m, () => Lw(this.device, e, b, c, r)), v = this.activeTimers != null, x = this.makeBindGroup(this.device, g, t.map((I) => this.tensorToBinding(I)), this.tensorToBinding(r), l);
this.ensureCommandEncoderReady();
let k = this.getComputePass();
return v && this.supportTimeQuery && k.writeTimestamp(this.querySet, 0), k.setPipeline(y), k.setBindGroup(0, x), k.dispatchWorkgroups(e.dispatch[0], e.dispatch[1], e.dispatch[2]), v && this.supportTimeQuery && k.writeTimestamp(this.querySet, 1), this.dispatchNumberInEncoder++, t.forEach((I) => {
this.commandQueueOwnedIds.add(I.dataId);
}), this.commandQueueOwnedIds.add(r.dataId), K().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE") <= this.dispatchNumberInEncoder && this.submitQueue(), v && this.activeTimers.push({ name: e.constructor.name, query: this.getQueryTime(this.querySet) }), r;
}
getFromPixelTextureLayout(e) {
return e ? (this.fromPixelImportTextureLayout === null && (this.fromPixelImportTextureLayout = this.createFromPixelTextureLayout(true)), this.fromPixelImportTextureLayout) : (this.fromPixelTextureLayout === null && (this.fromPixelTextureLayout = this.createFromPixelTextureLayout(false)), this.fromPixelTextureLayout);
}
createFromPixelTextureLayout(e) {
let t = [];
t.push({ binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage" } }), e ? t.push({ binding: 1, visibility: GPUShaderStage.COMPUTE, externalTexture: {} }) : t.push({ binding: 1, visibility: GPUShaderStage.COMPUTE, texture: {} }), t.push({ binding: 2, visibility: GPUShaderStage.COMPUTE, buffer: {} });
let n = this.device.createBindGroupLayout({ entries: t }), s = this.device.createPipelineLayout({ bindGroupLayouts: [n] });
return { bindGroupLayout: n, pipelineLayout: s };
}
copyExternalImageToTexture(e, t) {
let n = GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING, s = "rgba8unorm", r = this.textureManager.acquireTexture(t[1], t[0], s, n), a = r.createView();
this.queue.copyExternalImageToTexture({ source: e }, { texture: r }, [t[1], t[0]]);
let o = { width: t[1], height: t[0], format: s, usage: n, texture: r };
return this.textureDisposalQueue.push(o), a;
}
runFromPixelsProgram(e, t, n, s, r) {
e.dispatch = Jw(this.device, e);
let a = this.makeTensorInfo(t, "int32");
if (w.sizeFromShape(a.shape) === 0) {
let m = this.tensorMap.get(a.dataId);
return m.values = w.getTypedArrayFromDType(a.dtype, 0), a;
}
this.uploadToGPU(a.dataId);
let o = Mw(e, [a.shape]), i = this.getFromPixelTextureLayout(s), u = this.getAndSavePipeline(o, () => Lw(this.device, e, i.pipelineLayout, [], a, true)), l;
if (s) {
let m = { source: r };
l = this.device.importExternalTexture(m);
} else
l = this.copyExternalImageToTexture(r, a.shape);
let c = this.tensorToBinding(a), p = this.makeUniforms(n), d = this.device.createBindGroup({ layout: i.bindGroupLayout, entries: [{ binding: 0, resource: { buffer: c.buffer } }, { binding: 1, resource: l }, { binding: 2, resource: { buffer: p.buffer } }] });
this.ensureCommandEncoderReady();
let h = this.getComputePass(), f = this.activeTimers != null;
return f && this.supportTimeQuery && h.writeTimestamp(this.querySet, 0), h.setPipeline(u), h.setBindGroup(0, d), h.dispatchWorkgroups(e.dispatch[0], e.dispatch[1], e.dispatch[2]), f && this.supportTimeQuery && h.writeTimestamp(this.querySet, 1), this.commandQueueOwnedIds.add(a.dataId), this.dispatchNumberInEncoder++, K().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE") <= this.dispatchNumberInEncoder && this.submitQueue(), f && this.activeTimers.push({ name: e.constructor.name, query: this.getQueryTime(this.querySet) }), a;
}
async getTimeFromQuerySet(e) {
let t = this.acquireBuffer(16, GPUBufferUsage.COPY_SRC | GPUBufferUsage.QUERY_RESOLVE), n = this.acquireBuffer(16, GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST);
this.ensureCommandEncoderReady(), this.ensureComputePassEnded(), this.currentCommandEncoder.resolveQuerySet(e, 0, 2, t, 0), this.currentCommandEncoder.copyBufferToBuffer(t, 0, n, 0, 16), this.submitQueue(), await n.mapAsync(GPUMapMode.READ);
let s = new BigUint64Array(n.getMappedRange()), r = Number(s[1] - s[0]);
return n.unmap(), this.bufferManager.releaseBuffer(n, 16, GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST), this.bufferManager.releaseBuffer(t, 16, GPUBufferUsage.COPY_SRC | GPUBufferUsage.QUERY_RESOLVE), r / 1e6;
}
shouldExecuteOnCPU(e, t = Xie) {
return K().getBool("WEBGPU_CPU_FORWARD") && e.every((n) => this.tensorMap.get(n.dataId).bufferInfo.buffer == null && w.sizeFromShape(n.shape) < t);
}
numDataIds() {
return this.tensorMap.numDataIds() - this.tensorDisposalQueue.length;
}
dispose() {
this.disposed || (this.bufferManager.dispose(), this.textureManager.dispose(), this.disposed = true);
}
};
var Wv = sN;
Wv.nextDataId = 0;
var Yie = {};
Ee(Yie, { WebGPUBackend: () => Wv, webgpu_util: () => F2 });
zv() && xp("webgpu", async () => {
K().set("CHECK_COMPUTATION_FOR_ERRORS", false);
let e = { powerPreference: K().get("WEBGPU_USE_LOW_POWER_GPU") ? "low-power" : "high-performance" }, t = await navigator.gpu.requestAdapter(e), n = t.limits, s = {}, r = t.features.has("timestamp-query");
s.requiredLimits = { maxComputeWorkgroupStorageSize: n.maxComputeWorkgroupStorageSize, maxComputeWorkgroupsPerDimension: n.maxComputeWorkgroupsPerDimension }, r ? s.requiredFeatures = ["timestamp-query"] : console.warn("This device doesn't support timestamp-query extension. Start Chrome browser with flag --disable-dawn-features=disallow_unsafe_apis then try again. Or zero will shown for the kernel time when profiling mode isenabled. Using performance.now is not workable for webgpu sinceit doesn't support synchronously to read data from GPU.");
let a = await t.requestDevice(s);
return new Wv(a, r);
}, 3);
var St = ((e) => (e[e.float32 = 0] = "float32", e[e.int32 = 1] = "int32", e[e.bool = 2] = "bool", e[e.string = 3] = "string", e[e.complex64 = 4] = "complex64", e))(St || {});
var uh = ((e) => (e[e.linear = 0] = "linear", e[e.relu = 1] = "relu", e[e.relu6 = 2] = "relu6", e[e.prelu = 3] = "prelu", e[e.leakyrelu = 4] = "leakyrelu", e[e.sigmoid = 5] = "sigmoid", e[e.elu = 6] = "elu", e))(uh || {});
var rN;
function Qie(e) {
rN = e.wasm.cwrap(oa, null, ["number", "array", "number", "number", "array", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Zie(e) {
let { inputs: t, backend: n, attrs: s } = e, { a: r, b: a, bias: o, preluActivationWeights: i } = t;
if (r.dtype !== "float32" || a.dtype !== "float32")
throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");
let { transposeA: u, transposeB: l, activation: c, leakyreluAlpha: p } = s, d = n.dataIdMap.get(r.dataId).id, h = n.dataIdMap.get(a.dataId).id, f = 0;
if (o != null) {
let R = n.dataIdMap.get(o.dataId);
if (R.shape.length !== 1)
throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${R.shape.length}.`);
f = R.id;
}
let m = i == null ? 0 : n.dataIdMap.get(i.dataId).id, g = uh[c];
if (g == null)
throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);
let b = u ? r.shape[2] : r.shape[1], y = l ? a.shape[1] : a.shape[2], v = Qi.assertAndGetBroadcastShape(r.shape.slice(0, -2), a.shape.slice(0, -2)), x = n.makeOutput([...v, b, y], r.dtype), k = n.dataIdMap.get(x.dataId).id, I = new Uint8Array(new Int32Array(r.shape).buffer), $ = new Uint8Array(new Int32Array(a.shape).buffer);
return rN(d, I, r.shape.length, h, $, a.shape.length, u, l, g, f, m, p || 0, k), x;
}
var Jie = { kernelName: oa, backendName: "wasm", setupFunc: Qie, kernelFunc: Zie };
function Ht(e, t) {
let n;
function s(a) {
n = a.wasm.cwrap(e, null, ["number", "number", "number"]);
}
function r(a) {
let { backend: o, inputs: { x: i } } = a, u = o.dataIdMap.get(i.dataId).id, l = o.makeOutput(i.shape, t || i.dtype), c = o.dataIdMap.get(l.dataId).id;
return w.sizeFromShape(l.shape) === 0 || n(u, St[i.dtype], c), l;
}
return { kernelName: e, backendName: "wasm", setupFunc: s, kernelFunc: r };
}
var eue = Ht(di);
function Xt(e, t, n) {
let s;
function r(o) {
s = o.wasm.cwrap(e, null, ["number", "array", "number", "number", "array", "number", "number", "number"]);
}
function a(o) {
let { backend: i, inputs: u } = o, { a: l, b: c } = u, p = i.dataIdMap.get(l.dataId).id, d = i.dataIdMap.get(c.dataId).id, h = n != null ? n : l.dtype, f = C.assertAndGetBroadcastShape(l.shape, c.shape), m = i.makeOutput(f, h);
if (w.sizeFromShape(f) === 0)
return m;
let g = new Uint8Array(new Int32Array(l.shape).buffer), b = new Uint8Array(new Int32Array(c.shape).buffer), y = i.dataIdMap.get(m.dataId).id;
return (() => s(p, g, l.shape.length, d, b, c.shape.length, St[l.dtype], y))(), m;
}
return { kernelName: e, backendName: "wasm", setupFunc: r, kernelFunc: a };
}
var tue = true;
var nue = Xt(Cr, tue);
var aN;
function sue(e) {
aN = e.wasm.cwrap(Sa, null, ["array", "number", "number", "number"]);
}
function rue(e) {
let { inputs: t, backend: n } = e, s = n.makeOutput(t[0].shape, t[0].dtype);
if (w.sizeFromShape(s.shape) === 0)
return s;
let r = t.map((i) => n.dataIdMap.get(i.dataId).id), a = new Uint8Array(new Int32Array(r).buffer), o = n.dataIdMap.get(s.dataId).id;
return aN(a, r.length, St[s.dtype], o), s;
}
var aue = { kernelName: Sa, backendName: "wasm", setupFunc: sue, kernelFunc: rue };
function lh(e) {
let { inputs: { x: t }, backend: n } = e, s = n.makeOutput(t.shape, t.dtype), r = n.typedArrayFromHeap(t);
return n.typedArrayFromHeap(s).set(r), s;
}
var oue = { kernelName: Wa, backendName: "wasm", kernelFunc: lh };
var oN;
function iue(e) {
oN = e.wasm.cwrap(Hs, null, ["number", "array", "number", "number", "number", "array", "number"]);
}
function Sr(e) {
let { inputs: t, backend: n, attrs: s } = e, [r, a] = lue(t.x.shape, s.perm), o = true;
for (let f = 0; f < a.length; f++)
a[f] !== f && (o = false);
let i = uue(t.x.shape, s.perm), u = { dataId: t.x.dataId, shape: r, dtype: t.x.dtype };
if (o) {
let f = lh({ inputs: t, backend: n });
return f.shape = i, f;
}
let l = n.makeOutput(i, u.dtype), c = n.dataIdMap.get(u.dataId).id, p = n.dataIdMap.get(l.dataId).id, d = new Uint8Array(new Int32Array(a).buffer), h = new Uint8Array(new Int32Array(u.shape).buffer);
return oN(c, h, u.shape.length, St[u.dtype], p, d, a.length), l;
}
function uue(e, t) {
let n = new Array(e.length);
for (let s = 0; s < n.length; s++)
n[s] = e[t[s]];
return n;
}
function lue(e, t) {
let n = [], s = [];
for (let r = 0; r < e.length; ++r)
e[r] !== 1 && n.push(e[r]), e[t[r]] !== 1 && s.push(t[r]);
for (let r = 0; r < s.length; ++r) {
let a = -1;
for (let o = 0; o < s.length; ++o)
s[o] >= r && (a === -1 || s[a] > s[o]) && (a = o);
s[a] = r;
}
return [n, s];
}
var cue = { kernelName: Hs, backendName: "wasm", kernelFunc: Sr, setupFunc: iue };
function Pr(e, t, n) {
let s = e.shape, r = e.shape.length, a = w.parseAxisParam(t, s), o = a, i = C.getAxesPermutation(o, r), u = null, l = false;
if (i != null) {
let c = new Array(r);
for (let h = 0; h < c.length; h++)
c[h] = s[i[h]];
o = C.getInnerMostAxes(o.length, r), u = Sr({ inputs: { x: e }, attrs: { perm: i }, backend: n });
let p = n.dataIdMap.get(e.dataId).id;
n.dataIdMap.get(u.dataId).id !== p && (l = true);
}
return { transposed: u, originalAxes: a, axes: o, inputWasTransposed: l };
}
var iN;
function due(e) {
iN = e.wasm.cwrap(cl, null, ["number, number, number"]);
}
function pue(e) {
let { backend: t, inputs: n, attrs: s } = e, { axis: r, keepDims: a } = s, { x: o } = n, u = t.dataIdMap.get(o.dataId).id, l = o, { transposed: c, axes: p, originalAxes: d, inputWasTransposed: h } = Pr(o, r, t);
if (h) {
let v = t.dataIdMap.get(c.dataId).id;
l = c, u = v;
}
let f = l.shape.length;
C.assertAxesAreInnerMostDims("all", p, f);
let [m, g] = C.computeOutAndReduceShapes(l.shape, p), b = w.sizeFromShape(g), y = t.makeOutput(m, o.dtype);
if (w.sizeFromShape(l.shape) !== 0) {
let v = t.dataIdMap.get(y.dataId).id;
iN(u, b, v);
}
if (h && t.disposeData(c.dataId), a) {
let v = C.expandShapeToKeepDim(y.shape, d);
y.shape = v;
}
return y;
}
var hue = { kernelName: cl, backendName: "wasm", setupFunc: due, kernelFunc: pue };
var uN;
function fue(e) {
uN = e.wasm.cwrap(dl, null, ["number, number, number"]);
}
function mue(e) {
let { backend: t, inputs: n, attrs: s } = e, { axis: r, keepDims: a } = s, { x: o } = n, u = t.dataIdMap.get(o.dataId).id, l = o, { transposed: c, axes: p, originalAxes: d, inputWasTransposed: h } = Pr(o, r, t);
if (h) {
let v = t.dataIdMap.get(c.dataId).id;
l = c, u = v;
}
let f = l.shape.length;
C.assertAxesAreInnerMostDims("any", p, f);
let [m, g] = C.computeOutAndReduceShapes(l.shape, p), b = w.sizeFromShape(g), y = t.makeOutput(m, o.dtype);
if (w.sizeFromShape(l.shape) !== 0) {
let v = t.dataIdMap.get(y.dataId).id;
uN(u, b, v);
}
if (h && t.disposeData(c.dataId), a) {
let v = C.expandShapeToKeepDim(y.shape, d);
y.shape = v;
}
return y;
}
var gue = { kernelName: dl, backendName: "wasm", setupFunc: fue, kernelFunc: mue };
var lN;
function bue(e) {
lN = e.wasm.cwrap(Ia, null, ["number", "number", "number", "number", "number"]);
}
function yue(e) {
let { backend: t, inputs: n, attrs: s } = e, { axis: r } = s, { x: a } = n, o = t.dataIdMap.get(a.dataId).id, i = o, u = a, { transposed: l, axes: c, inputWasTransposed: p } = Pr(a, r, t);
if (p) {
let b = t.dataIdMap.get(l.dataId).id;
b !== o && (u = l, i = b);
}
let d = u.shape.slice(0, -1), h = t.makeOutput(d, "int32"), f = t.dataIdMap.get(h.dataId).id, m = w.sizeFromShape(h.shape), g = u.shape[c[0]];
return lN(i, St[u.dtype], m, g, f), p && t.disposeData(l.dataId), h;
}
var vue = { kernelName: Ia, backendName: "wasm", kernelFunc: yue, setupFunc: bue };
var cN;
function xue(e) {
cN = e.wasm.cwrap(Ca, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function wue(e) {
let { inputs: t, attrs: n, backend: s } = e, r = t.x, a = s.dataIdMap.get(r.dataId).id, { filterSize: o, strides: i, pad: u, dimRoundingMode: l } = n, c = C.computePool2DInfo(r.shape, o, i, 1, u, l), p = c.filterHeight, d = c.filterWidth, h = c.padInfo.top, f = c.padInfo.right, m = c.padInfo.bottom, g = c.padInfo.left, b = c.strideHeight, y = c.strideWidth, v = c.inChannels;
if (c.dataFormat !== "channelsLast")
throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);
if (c.dilationWidth !== 1 || c.dilationHeight !== 1)
throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${c.dilationHeight}, ${c.dilationWidth}].`);
let x = s.makeOutput(c.outShape, "float32"), k = s.dataIdMap.get(x.dataId).id;
return cN(a, r.shape[0], r.shape[1], r.shape[2], p, d, h, f, m, g, b, y, v, k), x;
}
var kue = { kernelName: Ca, backendName: "wasm", setupFunc: xue, kernelFunc: wue };
function yn(e) {
let { inputs: t, attrs: n } = e, { x: s } = t, { shape: r } = n, a = w.sizeFromShape(s.shape), o = w.inferFromImplicitShape(r, a);
return w.assert(a === w.sizeFromShape(o), () => `new shape: ${o}, old shape: ${s.shape}. New shape and old shape must have the same number of elements.`), e.backend.incRef(s.dataId), { dataId: s.dataId, shape: o, dtype: s.dtype };
}
var Sue = { kernelName: Oi, backendName: "wasm", kernelFunc: yn };
var dN;
function Iue(e) {
dN = e.wasm.cwrap(Na, null, ["number", "array", "number", "number", "array", "number", "number", "number", "number"]);
}
function Cue(e) {
let { inputs: t, backend: n, attrs: s } = e, { a: r, b: a } = t, { transposeA: o, transposeB: i } = s;
if (r.dtype !== "float32" || a.dtype !== "float32")
throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");
let u = r.shape.length, l = a.shape.length, c = o ? r.shape[u - 2] : r.shape[u - 1], p = i ? a.shape[l - 1] : a.shape[l - 2], d = o ? r.shape[u - 1] : r.shape[u - 2], h = i ? a.shape[l - 2] : a.shape[l - 1], f = r.shape.slice(0, -2), m = a.shape.slice(0, -2), g = w.sizeFromShape(f), b = w.sizeFromShape(m), v = Qi.assertAndGetBroadcastShape(r.shape.slice(0, -2), a.shape.slice(0, -2)).concat([d, h]);
w.assert(c === p, () => `Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${r.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);
let x = o ? [g, c, d] : [g, d, c], k = i ? [b, h, p] : [b, p, h], I = yn({ inputs: { x: r }, backend: n, attrs: { shape: x } }), $ = yn({ inputs: { x: a }, backend: n, attrs: { shape: k } }), R = n.dataIdMap.get(I.dataId).id, E = n.dataIdMap.get($.dataId).id, P = o ? I.shape[2] : I.shape[1], A = i ? $.shape[1] : $.shape[2], D = Math.max(g, b), T = n.makeOutput([D, P, A], I.dtype), L = n.dataIdMap.get(T.dataId).id, W = new Uint8Array(new Int32Array(I.shape).buffer), j = new Uint8Array(new Int32Array($.shape).buffer);
return dN(R, W, I.shape.length, E, j, $.shape.length, o, i, L), n.disposeData(I.dataId), n.disposeData($.dataId), T.shape = v, T;
}
var Nue = { kernelName: Na, backendName: "wasm", setupFunc: Iue, kernelFunc: Cue };
function xa(e) {
let { inputs: { x: t }, attrs: { begin: n, size: s }, backend: r } = e, [a, o] = kt.parseSliceParams(t, n, s), i = kt.isSliceContinous(t.shape, a, o), u = r.readSync(t.dataId), l = r.makeOutput(o, t.dtype), c = w.computeStrides(t.shape), p = r.dataIdMap.get(l.dataId);
if (i) {
let f = kt.computeFlatOffset(a, c);
return t.dtype === "string" ? p.stringBytes = u.slice(f, f + w.sizeFromShape(o)) : r.typedArrayFromHeap(l).set(u.subarray(f, f + w.sizeFromShape(o))), l;
}
if (t.dtype === "string") {
let f = Vd(u, a, o, t.shape, t.dtype);
return p.stringBytes = f, l;
}
let d = r.typedArrayFromHeap(l), h = t.shape.length;
if (h === 2)
Tue(u, c[0], d, a, o);
else if (h === 3)
$ue(u, c[0], c[1], d, a, o);
else if (h === 4)
_ue(u, c[0], c[1], c[2], d, a, o);
else {
let f = Vd(u, a, o, t.shape, t.dtype);
d.set(f);
}
return l;
}
function Tue(e, t, n, s, r) {
let a = 0, o = s[0], i = s[1], u = o + r[0];
for (let l = o; l < u; l++) {
let c = l * t + i;
n.set(e.subarray(c, c + r[1]), a), a += r[1];
}
}
function $ue(e, t, n, s, r, a) {
let o = 0, i = r[0], u = r[1], l = r[2], c = i + a[0], p = u + a[1];
for (let d = i; d < c; d++)
for (let h = u; h < p; h++) {
let f = d * t + h * n + l;
s.set(e.subarray(f, f + a[2]), o), o += a[2];
}
}
function _ue(e, t, n, s, r, a, o) {
let i = 0, u = a[0], l = a[1], c = a[2], p = u + o[0], d = l + o[1], h = c + o[2], f = a[3];
for (let m = u; m < p; m++)
for (let g = l; g < d; g++)
for (let b = c; b < h; b++) {
let y = m * t + g * n + b * s + f;
r.set(e.subarray(y, y + o[3]), i), i += o[3];
}
}
var Aue = { kernelName: Bi, backendName: "wasm", kernelFunc: xa };
function Eue(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { blockShape: a, crops: o } = s, i = a.reduce((b, y) => b * y), u = C.getReshaped(r.shape, a, i), l = C.getPermuted(u.length, a.length), c = C.getReshapedPermuted(r.shape, a, i), p = C.getSliceBeginCoords(o, a.length), d = C.getSliceSize(c, o, a.length), h = yn({ inputs: { x: r }, backend: n, attrs: { shape: u } }), f = Sr({ inputs: { x: h }, backend: n, attrs: { perm: l } }), m = yn({ inputs: { x: f }, backend: n, attrs: { shape: c } }), g = xa({ inputs: { x: m }, backend: n, attrs: { begin: p, size: d } });
return n.disposeData(h.dataId), n.disposeData(f.dataId), n.disposeData(h.dataId), g;
}
var Rue = { kernelName: pi, backendName: "wasm", kernelFunc: Eue };
function lc(e) {
let { inputs: { x: t }, attrs: { dtype: n }, backend: s } = e, r = s.makeOutput(t.shape, n), a = s.typedArrayFromHeap(t);
return s.typedArrayFromHeap(r).set(a), r;
}
var Due = { kernelName: Ta, backendName: "wasm", kernelFunc: lc };
var Fue = Ht($a);
var pN;
function Oue(e) {
pN = e.wasm.cwrap(Nr, null, ["number", "number", "number", "number"]);
}
function Pue(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { clipValueMin: a, clipValueMax: o } = s, i = n.dataIdMap.get(r.dataId).id, u = n.makeOutput(r.shape, r.dtype), l = n.dataIdMap.get(u.dataId).id;
return pN(i, a, o, l), u;
}
var zue = { kernelName: Nr, backendName: "wasm", setupFunc: Oue, kernelFunc: Pue };
function hN(e) {
let { inputs: t, backend: n } = e, s = w.parseAxisParam(e.attrs.axis, t[0].shape)[0], r = C.computeOutShape(t.map((h) => h.shape), s), a = t.filter((h) => w.sizeFromShape(h.shape) > 0);
if (a.length === 1)
return lh({ inputs: { x: a[0] }, backend: n });
let o = n.makeOutput(r, t[0].dtype);
if (w.sizeFromShape(r) === 0)
return o;
let i = a.map((h) => h.shape);
if (C.assertParamsConsistent(i, s), a[0].dtype === "string") {
let h = a.map((v) => {
let x = w.sizeFromShape(v.shape.slice(s));
return yn({ inputs: { x: v }, backend: n, attrs: { shape: [-1, x] } });
}), f = h.map((v) => ({ vals: n.readSync(v.dataId), shape: v.shape }));
r = C.computeOutShape(h.map((v) => v.shape), 1);
let m = h[0].shape[0] === 1, g = hv(f, r, t[0].dtype, m), b = C.computeOutShape(a.map((v) => v.shape), s);
o.shape = b;
let y = n.dataIdMap.get(o.dataId);
return y.stringBytes = C.fromStringArrayToUint8(g), h.forEach((v) => n.disposeData(v.dataId)), o;
}
let u = w.sizeFromShape(a[0].shape.slice(0, s)), l = 0, c = a.map((h) => {
let f = w.sizeFromShape(h.shape.slice(s));
return l += f, f;
}), p = a.map((h) => n.typedArrayFromHeap(h)), d = n.typedArrayFromHeap(o);
for (let h = 0; h < u; h++) {
let f = h * l;
for (let m = 0; m < p.length; m++) {
let g = c[m], b = h * g, y = p[m].subarray(b, b + g);
d.set(y, f), f += g;
}
}
return o;
}
var Lue = { kernelName: hi, backendName: "wasm", kernelFunc: hN };
var fN;
function Mue(e) {
fN = e.wasm.cwrap(_a, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Bue(e) {
let { inputs: t, attrs: n, backend: s } = e, { x: r, filter: a } = t, o = s.dataIdMap.get(r.dataId).id, i = s.dataIdMap.get(a.dataId).id, { strides: u, dilations: l, pad: c, dimRoundingMode: p, dataFormat: d } = n, h = C.convertConv2DDataFormat(d), f = C.computeConv2DInfo(r.shape, a.shape, u, l, c, p, false, h), m = f.filterHeight, g = f.filterWidth, b = f.padInfo.top, y = f.padInfo.right, v = f.padInfo.bottom, x = f.padInfo.left, k = f.dilationHeight, I = f.dilationWidth, $ = f.strideHeight, R = f.strideWidth, E = f.inChannels, P = f.outChannels, A = f.padInfo.type === "SAME" ? 1 : 0;
if (f.dataFormat !== "channelsLast")
throw new Error(`wasm backend Conv2D does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);
let D = s.makeOutput(f.outShape, "float32"), T = s.dataIdMap.get(D.dataId).id;
return fN(o, r.shape[0], r.shape[1], r.shape[2], i, m, g, b, y, v, x, A, k, I, $, R, E, P, T), D;
}
var Vue = { kernelName: _a, backendName: "wasm", setupFunc: Mue, kernelFunc: Bue };
var mN;
function Wue(e) {
mN = e.wasm.cwrap(Aa, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Uue(e) {
let { backend: t, inputs: n, attrs: s } = e, { dy: r, filter: a } = n, { strides: o, pad: i, dataFormat: u, dimRoundingMode: l, inputShape: c } = s, p = 1, d = C.convertConv2DDataFormat(u), h = C.computeConv2DInfo(c, a.shape, o, p, i, l, false, d), { batchSize: f, filterHeight: m, filterWidth: g, inChannels: b, inHeight: y, inWidth: v, outChannels: x, outHeight: k, outWidth: I, strideHeight: $, strideWidth: R } = h, E = m - 1 - h.padInfo.top, P = g - 1 - h.padInfo.left, A = h.dataFormat === "channelsLast", D = w.computeStrides(h.inShape), T = w.computeStrides(r.shape), [L, W, j] = w.computeStrides(a.shape), Y = D[0], X = A ? D[1] : D[2], Z = A ? D[2] : 1, ne = A ? 1 : D[1], ee = T[0], se = A ? T[1] : T[2], te = A ? T[2] : 1, ie = A ? 1 : T[1], ae = t.makeOutput(h.inShape, "float32"), de = t.dataIdMap.get(ae.dataId).id, me = t.dataIdMap.get(r.dataId).id, ke = t.dataIdMap.get(a.dataId).id;
return mN(me, ke, f, m, g, y, v, b, k, I, x, $, R, E, P, L, W, j, Y, X, Z, ne, ee, se, te, ie, de), ae;
}
var Gue = { kernelName: Aa, backendName: "wasm", setupFunc: Wue, kernelFunc: Uue };
var Hue = Ht(Ea);
var que = Ht(Ra);
var gN = ((e) => (e[e.bilinear = 0] = "bilinear", e[e.nearest = 1] = "nearest", e))(gN || {});
var bN;
function jue(e) {
bN = e.wasm.cwrap(mi, null, ["number", "number", "number", "number", "array", "number", "number", "number", "number", "number"]);
}
function Kue(e) {
let { backend: t, inputs: n, attrs: s } = e, { method: r, extrapolationValue: a, cropSize: o } = s, { image: i, boxes: u, boxInd: l } = n, c = u.shape[0], [p, d] = o, h = [c, p, d, i.shape[3]], f = t.dataIdMap.get(i.dataId), m;
i.dtype !== "float32" && (m = lc({ backend: t, inputs: { x: i }, attrs: { dtype: "float32" } }), f = t.dataIdMap.get(m.dataId));
let g = f.id, b = t.dataIdMap.get(u.dataId).id, y = t.dataIdMap.get(l.dataId).id, v = t.makeOutput(h, "float32"), x = t.dataIdMap.get(v.dataId).id, k = new Uint8Array(new Int32Array(i.shape).buffer);
return bN(g, b, y, c, k, p, d, gN[r], a, x), m != null && t.disposeData(m.dataId), v;
}
var Xue = { kernelName: mi, backendName: "wasm", setupFunc: jue, kernelFunc: Kue };
var yN;
function Yue(e) {
yN = e.wasm.cwrap(fi, null, ["number", "number", "number", "number", "number", "number"]);
}
function Que(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, exclusive: o, reverse: i } = s, u = r.shape.length;
w.assert(r.dtype === "float32" || r.dtype === "int32", () => `cumprod does not support ${r.dtype} tensors in the WASM backend`);
let l = C.getAxesPermutation([a], u), c = r;
l !== null && (c = Sr({ inputs: { x: r }, attrs: { perm: l }, backend: n }));
let p = C.getInnerMostAxes(1, u)[0];
C.assertAxesAreInnerMostDims("cumprod", [p], u);
let d = n.makeOutput(c.shape, c.dtype), h = c.shape[p], f = n.dataIdMap.get(c.dataId).id, m = n.dataIdMap.get(d.dataId).id;
yN(f, o ? 1 : 0, i ? 1 : 0, h, m, St[r.dtype]);
let g = d;
if (l !== null) {
let b = C.getUndoAxesPermutation(l);
g = Sr({ inputs: { x: d }, attrs: { perm: b }, backend: n }), n.disposeData(c.dataId), n.disposeData(d.dataId);
}
return g;
}
var Zue = { kernelName: fi, backendName: "wasm", setupFunc: Yue, kernelFunc: Que };
var vN;
function Jue(e) {
vN = e.wasm.cwrap(Da, null, ["number", "number", "number", "number", "number", "number"]);
}
function ele(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { axis: a, exclusive: o, reverse: i } = s, u = r.shape.length;
w.assert(r.dtype === "float32" || r.dtype === "int32", () => `cumsum does not support ${r.dtype} tensors in the WASM backend`);
let l = C.getAxesPermutation([a], u), c = r;
l !== null && (c = Sr({ inputs: { x: r }, attrs: { perm: l }, backend: n }));
let p = C.getInnerMostAxes(1, u)[0];
C.assertAxesAreInnerMostDims("cumsum", [p], u);
let d = n.makeOutput(c.shape, c.dtype), h = c.shape[p], f = n.dataIdMap.get(c.dataId).id, m = n.dataIdMap.get(d.dataId).id;
vN(f, o ? 1 : 0, i ? 1 : 0, h, m, St[r.dtype]);
let g = d;
if (l !== null) {
let b = C.getUndoAxesPermutation(l);
g = Sr({ inputs: { x: d }, attrs: { perm: b }, backend: n }), n.disposeData(c.dataId), n.disposeData(d.dataId);
}
return g;
}
var tle = { kernelName: Da, backendName: "wasm", setupFunc: Jue, kernelFunc: ele };
var xN;
function nle(e) {
xN = e.wasm.cwrap(gi, null, ["number", "number", "number", "array", "number", "array", "array", "number", "number"]);
}
function sle(e) {
let { backend: t, inputs: n, attrs: s } = e, { x: r } = n, { blockSize: a, dataFormat: o } = s, i = r.shape[0], u = o === "NHWC" ? r.shape[1] : r.shape[2], l = o === "NHWC" ? r.shape[2] : r.shape[3], c = o === "NHWC" ? r.shape[3] : r.shape[1], p = u * a, d = l * a, h = c / (a * a), f = o === "NHWC" ? [i, p, d, h] : [i, h, p, d], m = t.makeOutput(f, "float32"), b = t.dataIdMap.get(r.dataId).id, y = new Uint8Array(new Int32Array(w.computeStrides(r.shape)).buffer), v = new Uint8Array(new Int32Array(f).buffer), x = new Uint8Array(new Int32Array(w.computeStrides(f)).buffer), k = t.dataIdMap.get(m.dataId).id;
return xN(b, a, o === "NHWC" ? 1 : 0, y, r.shape.length - 1, v, x, f.length, k), m;
}
var rle = { kernelName: gi, backendName: "wasm", setupFunc: nle, kernelFunc: sle };
var wN;
function ale(e) {
wN = e.wasm.cwrap(Fa, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function ole(e) {
let { inputs: t, attrs: n, backend: s } = e, { x: r, filter: a } = t, o = s.dataIdMap.get(r.dataId).id, i = s.dataIdMap.get(a.dataId).id, { strides: u, dilations: l, pad: c, dimRoundingMode: p } = n, d = l == null ? [1, 1] : l, h = C.computeConv2DInfo(r.shape, a.shape, u, d, c, p, true), f = h.filterHeight, m = h.filterWidth, g = h.padInfo.top, b = h.padInfo.right, y = h.padInfo.bottom, v = h.padInfo.left, x = h.dilationHeight, k = h.dilationWidth, I = h.strideHeight, $ = h.strideWidth, R = h.inChannels, E = h.outChannels, P = h.padInfo.type === "SAME" ? 1 : 0;
if (h.dataFormat !== "channelsLast")
throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${h.dataFormat}'. Please use 'channelsLast'.`);
let A = s.makeOutput(h.outShape, "float32"), D = s.dataIdMap.get(A.dataId).id;
return wN(o, r.shape[0], r.shape[1], r.shape[2], i, f, m, g, b, y, v, P, x, k, I, $, R, E, D), A;
}
var ile = { kernelName: Fa, backendName: "wasm", setupFunc: ale, kernelFunc: ole };
var ule = Ht(Pa);
var lle = false;
var cle = Xt(bi, lle, "bool");
var dle = Ht(za, "float32");
function lg(e) {
let { inputs: t, attrs: n, backend: s } = e, { input: r } = t, { dim: a } = n, o = r.shape.length, i = r.shape.slice(), u = a;
return a < 0 && (w.assert(-(o + 1) <= a, () => `Axis must be in the interval [${-(o + 1)}, ${o}]`), u = o + a + 1), i.splice(u, 0, 1), yn({ inputs: { x: r }, backend: s, attrs: { shape: i } });
}
var ple = { kernelName: yi, backendName: "wasm", kernelFunc: lg };
function kN(e) {
let { attrs: { shape: t, value: n, dtype: s }, backend: r } = e, a = r.makeOutput(t, s);
return r.typedArrayFromHeap(a).fill(n), a;
}
var hle = { kernelName: vl, backendName: "wasm", kernelFunc: kN };
var SN;
function fle(e) {
SN = e.wasm.cwrap(xi, null, ["number", "number", "number", "number", "number", "number"]);
}
function mle(e) {
let { inputs: t, backend: n } = e, { image: s } = t, r = n.makeOutput(s.shape, s.dtype), a = n.dataIdMap.get(s.dataId).id, o = n.dataIdMap.get(r.dataId).id, [i, u, l, c] = s.shape;
return SN(a, i, u, l, c, o), r;
}
var gle = { kernelName: xi, backendName: "wasm", kernelFunc: mle, setupFunc: fle };
var ble = Ht(La);
var yle = false;
var vle = Xt(Ma, yle);
var IN;
function xle(e) {
IN = e.wasm.cwrap(Ba, null, ["number", "number", "number", "number", "number", "number", "number"]);
}
function wle(e) {
let { backend: t, inputs: n, attrs: s } = e, { varianceEpsilon: r } = s, { x: a, mean: o, variance: i, offset: u, scale: l } = n, c = t.dataIdMap.get(a.dataId).id, p = t.dataIdMap.get(o.dataId).id, d = t.dataIdMap.get(i.dataId).id, h = u != null ? t.dataIdMap.get(u.dataId).id : 0, f = l != null ? t.dataIdMap.get(l.dataId).id : 0, m = t.makeOutput(a.shape, a.dtype);
if (w.sizeFromShape(a.shape) === 0)
return m;
let g = t.dataIdMap.get(m.dataId).id;
return IN(c, p, d, h, f, r, g), m;
}
var kle = { kernelName: Ba, backendName: "wasm", setupFunc: xle, kernelFunc: wle };
var CN;
function Sle(e) {
CN = e.wasm.cwrap(ia, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Ile(e) {
let { inputs: t, attrs: n, backend: s } = e, { x: r, filter: a, bias: o, preluActivationWeights: i } = t, { strides: u, pad: l, dilations: c, dataFormat: p, dimRoundingMode: d, activation: h, leakyreluAlpha: f } = n, m = C.computeConv2DInfo(r.shape, a.shape, u, c, l, d), g = uh[h];
if (g == null)
throw new Error(`${h} activation not yet supported for FusedConv2D in the wasm backend.`);
let b = s.dataIdMap.get(r.dataId).id, y = s.dataIdMap.get(a.dataId).id, v = m.outChannels, x = 0;
if (o != null) {
let te = s.dataIdMap.get(o.dataId);
if (te.shape.length !== 1)
throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${te.shape.length}.`);
if (te.shape[0] !== v)
throw new Error(`FusedConv2D bias shape (${te.shape}) does not match the number of output channels (${v})`);
x = te.id;
}
let k = m.filterHeight, I = m.filterWidth, $ = m.padInfo.top, R = m.padInfo.right, E = m.padInfo.bottom, P = m.padInfo.left, A = m.dilationHeight, D = m.dilationWidth, T = m.strideHeight, L = m.strideWidth, W = m.inChannels, j = m.padInfo.type === "SAME" ? 1 : 0, Y = m.batchSize, X = m.inHeight, Z = m.inWidth;
if (p !== "NHWC")
throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);
let ne = s.makeOutput(m.outShape, "float32"), ee = s.dataIdMap.get(ne.dataId).id, se = i == null ? 0 : s.dataIdMap.get(i.dataId).id;
return CN(b, Y, X, Z, y, k, I, x, $, R, E, P, j, A, D, T, L, W, v, g, se, f || 0, ee), ne;
}
var Cle = { kernelName: ia, backendName: "wasm", setupFunc: Sle, kernelFunc: Ile };
var NN;
function Nle(e) {
NN = e.wasm.cwrap(ua, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Tle(e) {
let { inputs: t, attrs: n, backend: s } = e, { x: r, filter: a, bias: o, preluActivationWeights: i } = t, { strides: u, pad: l, dilations: c, dataFormat: p, dimRoundingMode: d, activation: h, leakyreluAlpha: f } = n, m = C.computeConv2DInfo(r.shape, a.shape, u, c, l, d, true), g = uh[h];
if (g == null)
throw new Error(`${h} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);
let b = s.dataIdMap.get(r.dataId).id, y = s.dataIdMap.get(a.dataId).id, v = m.outChannels, x = 0;
if (o != null) {
let te = s.dataIdMap.get(o.dataId);
if (te.shape.length !== 1)
throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${te.shape.length}.`);
if (te.shape[0] !== v)
throw new Error(`FusedDepthwiseConv2D bias shape (${te.shape}) does not match the number of output channels (${v})`);
x = te.id;
}
let k = m.filterHeight, I = m.filterWidth, $ = m.padInfo.top, R = m.padInfo.right, E = m.padInfo.bottom, P = m.padInfo.left, A = m.dilationHeight, D = m.dilationWidth, T = m.strideHeight, L = m.strideWidth, W = m.inChannels, j = m.padInfo.type === "SAME" ? 1 : 0, Y = m.batchSize, X = m.inHeight, Z = m.inWidth;
if (p !== "NHWC")
throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);
let ne = s.makeOutput(m.outShape, "float32"), ee = s.dataIdMap.get(ne.dataId).id, se = i == null ? 0 : s.dataIdMap.get(i.dataId).id;
return NN(b, Y, X, Z, y, k, I, x, $, R, E, P, j, A, D, T, L, W, v, g, se, f || 0, ee), ne;
}
var $le = { kernelName: ua, backendName: "wasm", setupFunc: Nle, kernelFunc: Tle };
var TN;
function _le(e) {
TN = e.wasm.cwrap(ki, null, ["number", "number", "number", "number", "number", "number", "array", "number"]);
}
function Ale(e) {
let { backend: t, inputs: n } = e, { params: s, indices: r } = n, [a, o, i, u] = qk.prepareAndValidate(s, r), l = t.makeOutput(a, s.dtype);
if (o === 0)
return l;
let c = r.shape, p = c[c.length - 1], h = t.dataIdMap.get(s.dataId).id, m = t.dataIdMap.get(r.dataId).id, g = new Uint8Array(new Int32Array(u).buffer), b = t.dataIdMap.get(l.dataId).id;
return TN(h, St[s.dtype], m, o, p, i, g, b), l;
}
var Ele = { kernelName: ki, backendName: "wasm", setupFunc: _le, kernelFunc: Ale };
var $N;
function Rle(e) {
$N = e.wasm.cwrap("Gather", null, ["number", "number", "array", "number", "number", "number", "array", "number"]);
}
function Dle(e) {
let { backend: t, inputs: n, attrs: s } = e, { x: r, indices: a } = n, { axis: o, batchDims: i } = s, u = w.parseAxisParam(o, r.shape)[0], l = t.readSync(a.dataId), c = r.shape[u];
for (let E = 0; E < l.length; ++E) {
let P = l[E];
w.assert(P <= c - 1 && P >= 0, () => `GatherV2: the index value ${P} is not in [0, ${c - 1}]`);
}
let p = C.segment_util.collectGatherOpShapeInfo(r, a, u, i), d = yn({ inputs: { x: r }, attrs: { shape: [p.batchSize, p.outerSize, p.dimSize, p.sliceSize] }, backend: t }), h = w.sizeFromShape(a.shape), f = yn({ inputs: { x: a }, attrs: { shape: [p.batchSize, h / p.batchSize] }, backend: t }), m = [p.batchSize, p.outerSize, h / p.batchSize, p.sliceSize], g = t.makeOutput(m, r.dtype);
if (w.sizeFromShape(r.shape) === 0)
return g;
let b = d.shape.length - 1, v = t.dataIdMap.get(d.dataId).id, k = t.dataIdMap.get(f.dataId).id, I = t.dataIdMap.get(g.dataId).id, $ = new Uint8Array(new Int32Array(w.computeStrides(d.shape)).buffer), R = new Uint8Array(new Int32Array(w.computeStrides(m)).buffer);
return $N(v, St[r.dtype], $, b, k, p.batchSize, R, I), t.disposeData(d.dataId), t.disposeData(f.dataId), g.shape = p.outputShape, g;
}
var Fle = { kernelName: wi, backendName: "wasm", setupFunc: Rle, kernelFunc: Dle };
var Ole = false;
var Ple = Xt(Si, Ole, "bool");
var zle = false;
var Lle = Xt(Va, zle, "bool");
var _N;
function Mle(e) {
_N = e.wasm.cwrap(Ua, null, ["number", "number", "number", "number"]);
}
function Ble(e) {
let { inputs: { x: t }, attrs: { alpha: n }, backend: s } = e, r = s.dataIdMap.get(t.dataId).id, a = s.makeOutput(t.shape, "float32");
if (w.sizeFromShape(t.shape) !== 0) {
let o = s.dataIdMap.get(a.dataId).id;
_N(r, St[t.dtype], n, o);
}
return a;
}
var Vle = { kernelName: Ua, backendName: "wasm", setupFunc: Mle, kernelFunc: Ble };
var Wle = false;
var Ule = Xt(Ii, Wle, "bool");
var Gle = false;
var Hle = Xt(Ci, Gle, "bool");
var qle = Ht(Ga);
var jle = false;
var Kle = Xt(Ni, jle, "bool");
var Xle = Ht(Ti);
var Yle = false;
var Qle = Xt(Il, Yle, "bool");
var Zle = false;
var Jle = Xt(K$, Zle, "bool");
var AN;
function ece(e) {
AN = e.wasm.cwrap(Ha, null, ["number", "number", "number", "number"]);
}
function tce(e) {
let { backend: t, inputs: n, attrs: s } = e, { reductionIndices: r, keepDims: a } = s, { x: o } = n, u = t.dataIdMap.get(o.dataId).id, l = o, { transposed: c, axes: p, originalAxes: d, inputWasTransposed: h } = Pr(o, r, t);
if (h) {
let v = t.dataIdMap.get(c.dataId).id;
l = c, u = v;
}
let f = l.shape.length;
C.assertAxesAreInnerMostDims("max", p, f);
let [m, g] = C.computeOutAndReduceShapes(l.shape, p), b = w.sizeFromShape(g), y = t.makeOutput(m, o.dtype);
if (w.sizeFromShape(l.shape) !== 0) {
let v = t.dataIdMap.get(y.dataId).id;
AN(u, St[o.dtype], b, v);
}
if (h && t.disposeData(c.dataId), a) {
let v = C.expandShapeToKeepDim(y.shape, d);
y.shape = v;
}
return y;
}
var nce = { kernelName: Ha, backendName: "wasm", setupFunc: ece, kernelFunc: tce };
var sce = false;
var rce = Xt(qa, sce);
var EN;
function ace(e) {
EN = e.wasm.cwrap(ja, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function oce(e) {
let { inputs: t, attrs: n, backend: s } = e, r = t.x, a = s.dataIdMap.get(r.dataId).id;
w.assert(r.dtype === "float32", () => `Error in MaxPool: only float32 input is supported. Got ${r.dtype}.`);
let { filterSize: o, strides: i, pad: u, dimRoundingMode: l } = n, c = C.computePool2DInfo(r.shape, o, i, 1, u, l), p = c.filterHeight, d = c.filterWidth, h = c.padInfo.top, f = c.padInfo.right, m = c.padInfo.bottom, g = c.padInfo.left, b = c.dilationHeight, y = c.dilationWidth, v = c.strideHeight, x = c.strideWidth, k = c.inChannels, I = c.outChannels;
if (c.dataFormat !== "channelsLast")
throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);
let $ = s.makeOutput(c.outShape, "float32"), R = s.dataIdMap.get($.dataId).id;
return EN(a, r.shape[0], r.shape[1], r.shape[2], p, d, h, f, m, g, b, y, v, x, k, I, R), $;
}
var ice = { kernelName: ja, backendName: "wasm", setupFunc: ace, kernelFunc: oce };
var RN;
function uce(e) {
RN = e.wasm.cwrap(Ka, null, ["number, number, number"]);
}
function lce(e) {
let { backend: t, inputs: n, attrs: s } = e, { axis: r, keepDims: a } = s, { x: o } = n, i = t.dataIdMap.get(o.dataId).id, u = i, l = o, { transposed: c, axes: p, originalAxes: d, inputWasTransposed: h } = Pr(o, r, t), f = p;
if (h) {
let x = t.dataIdMap.get(c.dataId).id;
x !== i && (l = c, u = x, f = C.getInnerMostAxes(f.length, l.shape.length));
}
C.assertAxesAreInnerMostDims("mean", f, l.shape.length);
let [m, g] = C.computeOutAndReduceShapes(l.shape, f), b = w.sizeFromShape(g), y = l;
l.dtype !== "float32" && (y = lc({ backend: t, inputs: { x: l }, attrs: { dtype: "float32" } }), u = t.dataIdMap.get(y.dataId).id);
let v = t.makeOutput(m, "float32");
if (w.sizeFromShape(l.shape) !== 0) {
let x = t.dataIdMap.get(v.dataId).id;
RN(u, b, x);
}
if (h && t.disposeData(c.dataId), a) {
let x = C.expandShapeToKeepDim(v.shape, d);
v.shape = x;
}
return l.dtype !== "float32" && t.disposeData(y.dataId), v;
}
var cce = { kernelName: Ka, backendName: "wasm", setupFunc: uce, kernelFunc: lce };
var DN;
function dce(e) {
DN = e.wasm.cwrap(Xa, null, ["number", "number", "number", "number"]);
}
function pce(e) {
let { backend: t, inputs: n, attrs: s } = e, { axis: r, keepDims: a } = s, { x: o } = n, i = t.dataIdMap.get(o.dataId).id, u = i, l = o, { transposed: c, axes: p, originalAxes: d, inputWasTransposed: h } = Pr(o, r, t);
if (h) {
let v = t.dataIdMap.get(c.dataId).id;
v !== i && (l = c, u = v);
}
let f = l.shape.length;
C.assertAxesAreInnerMostDims("min", p, f);
let [m, g] = C.computeOutAndReduceShapes(l.shape, p), b = w.sizeFromShape(g), y = t.makeOutput(m, l.dtype);
if (w.sizeFromShape(l.shape) !== 0) {
let v = t.dataIdMap.get(y.dataId).id;
DN(u, St[o.dtype], b, v);
}
if (h && t.disposeData(c.dataId), a) {
let v = C.expandShapeToKeepDim(y.shape, d);
y.shape = v;
}
return y;
}
var hce = { kernelName: Xa, backendName: "wasm", setupFunc: dce, kernelFunc: pce };
var fce = false;
var mce = Xt(Ya, fce);
var FN = ((e) => (e[e.reflect = 0] = "reflect", e[e.symmetric = 1] = "symmetric", e))(FN || {});
var ON;
function gce(e) {
ON = e.wasm.cwrap(Qa, null, ["number", "array", "number", "number", "array", "array", "number", "number"]);
}
function bce(e) {
let { inputs: { x: t }, backend: n, attrs: { paddings: s, mode: r } } = e, a = s.map((f, m) => f[0] + t.shape[m] + f[1]), o = n.dataIdMap.get(t.dataId).id, i = n.makeOutput(a, t.dtype), u = n.dataIdMap.get(i.dataId).id, l = new Uint8Array(new Int32Array(t.shape).buffer), c = s.map((f) => f[0]), p = s.map((f) => f[1]), d = new Uint8Array(new Int32Array(c).buffer), h = new Uint8Array(new Int32Array(p).buffer);
return ON(o, l, t.shape.length, St[t.dtype], d, h, FN[r], u), i;
}
var yce = { kernelName: Qa, backendName: "wasm", kernelFunc: bce, setupFunc: gce };
var vce = true;
var xce = Xt(Za, vce);
var wce = Ht($i);
function Uv(e, t) {
let n = new Int32Array(e.wasm.HEAPU8.buffer, t, 4), s = n[0], r = n[1], a = n[2], o = n[3];
return e.wasm._free(t), { pSelectedIndices: s, selectedSize: r, pSelectedScores: a, pValidOutputs: o };
}
var PN;
function kce(e) {
PN = e.wasm.cwrap(Ai, "number", ["number", "number", "number", "number", "number"]);
}
function Sce(e) {
let { backend: t, inputs: n, attrs: s } = e, { iouThreshold: r, maxOutputSize: a, scoreThreshold: o } = s, { boxes: i, scores: u } = n, l = t.dataIdMap.get(i.dataId).id, c = t.dataIdMap.get(u.dataId).id, p = PN(l, c, a, r, o), { pSelectedIndices: d, selectedSize: h, pSelectedScores: f, pValidOutputs: m } = Uv(t, p);
return t.wasm._free(f), t.wasm._free(m), t.makeOutput([h], "int32", d);
}
var Ice = { kernelName: Ai, backendName: "wasm", setupFunc: kce, kernelFunc: Sce };
var zN;
function Cce(e) {
zN = e.wasm.cwrap(Nl, "number", ["number", "number", "number", "number", "number", "bool"]);
}
function Nce(e) {
let { backend: t, inputs: n, attrs: s } = e, { iouThreshold: r, maxOutputSize: a, scoreThreshold: o, padToMaxOutputSize: i } = s, { boxes: u, scores: l } = n, c = t.dataIdMap.get(u.dataId).id, p = t.dataIdMap.get(l.dataId).id, d = zN(c, p, a, r, o, i), { pSelectedIndices: h, selectedSize: f, pSelectedScores: m, pValidOutputs: g } = Uv(t, d);
t.wasm._free(m);
let b = t.makeOutput([f], "int32", h), y = t.makeOutput([], "int32", g);
return [b, y];
}
var Tce = { kernelName: Nl, backendName: "wasm", setupFunc: Cce, kernelFunc: Nce };
var LN;
function $ce(e) {
LN = e.wasm.cwrap(Ei, "number", ["number", "number", "number", "number", "number", "number"]);
}
function _ce(e) {
let { backend: t, inputs: n, attrs: s } = e, { iouThreshold: r, maxOutputSize: a, scoreThreshold: o, softNmsSigma: i } = s, { boxes: u, scores: l } = n, c = t.dataIdMap.get(u.dataId).id, p = t.dataIdMap.get(l.dataId).id, d = LN(c, p, a, r, o, i), { pSelectedIndices: h, selectedSize: f, pSelectedScores: m, pValidOutputs: g } = Uv(t, d);
t.wasm._free(g);
let b = t.makeOutput([f], "int32", h), y = t.makeOutput([f], "float32", m);
return [b, y];
}
var Ace = { kernelName: Ei, backendName: "wasm", setupFunc: $ce, kernelFunc: _ce };
var Ece = false;
var Rce = Xt(_i, Ece, "bool");
var MN;
function Dce(e) {
MN = e.wasm.cwrap(Di, null, ["number", "number", "number", "number", "number"]);
}
function Fce(e) {
let { inputs: t, backend: n, attrs: s } = e, { indices: r } = t, { depth: a, onValue: o, offValue: i } = s, u = n.makeOutput([...r.shape, a], "int32"), l = n.dataIdMap.get(u.dataId).id, p = n.dataIdMap.get(r.dataId).id;
return MN(p, a, o, i, l), u;
}
var Oce = { kernelName: Di, backendName: "wasm", setupFunc: Dce, kernelFunc: Fce };
function Pce(e) {
let { inputs: { x: t }, backend: n } = e, s = n.makeOutput(t.shape, t.dtype);
return n.typedArrayFromHeap(s).fill(1), s;
}
var zce = { kernelName: Ri, backendName: "wasm", kernelFunc: Pce };
function Lce(e) {
let { inputs: t, backend: n, attrs: s } = e, { axis: r } = s;
if (t.length === 1)
return lg({ inputs: { input: t[0] }, backend: n, attrs: { dim: r } });
let a = t[0].shape, o = t[0].dtype;
t.forEach((c) => {
w.assertShapesMatch(a, c.shape, "All tensors passed to stack must have matching shapes"), w.assert(o === c.dtype, () => "All tensors passed to stack must have matching dtypes");
});
let i = [], u = t.map((c) => {
let p = lg({ inputs: { input: c }, backend: n, attrs: { dim: r } });
return i.push(p), p;
}), l = hN({ inputs: u, backend: n, attrs: { axis: r } });
return i.forEach((c) => n.disposeData(c.dataId)), l;
}
var Mce = { kernelName: Fi, backendName: "wasm", kernelFunc: Lce };
var BN;
function Bce(e) {
BN = e.wasm.cwrap(Ja, null, ["number", "array", "number", "number", "array", "array", "number", "number"]);
}
function Vce(e) {
let { inputs: { x: t }, backend: n, attrs: { paddings: s, constantValue: r } } = e, a = s.map((m, g) => m[0] + t.shape[g] + m[1]);
if (w.sizeFromShape(t.shape) === 0)
return kN({ backend: n, attrs: { shape: a, value: r, dtype: t.dtype } });
let o = n.dataIdMap.get(t.dataId).id, i = n.makeOutput(a, t.dtype), l = n.dataIdMap.get(i.dataId).id, c = new Uint8Array(new Int32Array(t.shape).buffer), p = s.map((m) => m[0]), d = s.map((m) => m[1]), h = new Uint8Array(new Int32Array(p).buffer), f = new Uint8Array(new Int32Array(d).buffer);
return BN(o, c, t.shape.length, St[t.dtype], h, f, r, l), i;
}
var VN = { kernelName: Ja, backendName: "wasm", kernelFunc: Vce, setupFunc: Bce };
var Wce = false;
var Uce = Xt(eo, Wce);
var WN;
function Gce(e) {
WN = e.wasm.cwrap(to, null, ["number", "number", "number"]);
}
function Hce(e) {
let { inputs: t, backend: n } = e, { x: s, alpha: r } = t, a = n.dataIdMap.get(s.dataId).id, o = n.dataIdMap.get(r.dataId).id, i = a, u = s, l = u;
u.dtype !== "float32" && (l = lc({ backend: n, inputs: { x: s }, attrs: { dtype: "float32" } }), i = n.dataIdMap.get(l.dataId).id);
let c = n.makeOutput(s.shape, "float32"), p = n.dataIdMap.get(c.dataId).id;
return WN(i, o, p), u.dtype !== "float32" && n.disposeData(l.dataId), c;
}
var qce = { kernelName: to, backendName: "wasm", setupFunc: Gce, kernelFunc: Hce };
var UN;
function jce(e) {
UN = e.wasm.cwrap(no, null, ["number", "number", "number", "number"]);
}
function Kce(e) {
let { backend: t, inputs: n, attrs: s } = e, { axis: r, keepDims: a } = s, { x: o } = n, i = t.dataIdMap.get(o.dataId).id, u = i, l = o, { transposed: c, axes: p, originalAxes: d, inputWasTransposed: h } = Pr(o, r, t), f = p;
if (h) {
let v = t.dataIdMap.get(c.dataId).id;
v !== i && (l = c, u = v, f = C.getInnerMostAxes(f.length, l.shape.length));
}
C.assertAxesAreInnerMostDims("prod", f, l.shape.length);
let [m, g] = C.computeOutAndReduceShapes(l.shape, f), b = w.sizeFromShape(g), y = t.makeOutput(m, l.dtype);
if (w.sizeFromShape(l.shape) !== 0) {
let v = t.dataIdMap.get(y.dataId).id;
UN(u, b, St[y.dtype], v);
}
if (h && t.disposeData(c.dataId), a) {
let v = C.expandShapeToKeepDim(y.shape, d);
y.shape = v;
}
return y;
}
var Xce = { kernelName: no, backendName: "wasm", setupFunc: jce, kernelFunc: Kce };
var Yce = (e) => {
let { backend: t, attrs: n } = e, { start: s, stop: r, step: a, dtype: o } = n, i = gv(s, r, a, o), u = t.makeOutput([i.length], o);
return t.typedArrayFromHeap(u).set(i), u;
};
var Qce = { kernelName: Tl, backendName: "wasm", kernelFunc: Yce };
var Zce = true;
var Jce = Xt(Oa, Zce);
var ede = Ht(so);
var tde = Ht(ao);
var GN;
function nde(e) {
GN = e.wasm.cwrap(ro, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function sde(e) {
let { backend: t, inputs: n, attrs: s } = e, { images: r } = n, { alignCorners: a, halfPixelCenters: o, size: i } = s, [u, l] = i, [c, p, d, h] = r.shape, f = [c, u, l, h], m = t.dataIdMap.get(r.dataId), g;
m.dtype !== "float32" && (g = lc({ backend: t, inputs: { x: r }, attrs: { dtype: "float32" } }), m = t.dataIdMap.get(g.dataId));
let b = m.id, y = t.makeOutput(f, "float32");
if (w.sizeFromShape(r.shape) === 0)
return y;
let v = t.dataIdMap.get(y.dataId).id;
return GN(b, c, p, d, h, u, l, a ? 1 : 0, o ? 1 : 0, v), g != null && t.disposeData(g.dataId), y;
}
var rde = { kernelName: ro, backendName: "wasm", setupFunc: nde, kernelFunc: sde };
var HN;
function ade(e) {
HN = e.wasm.cwrap(Pi, null, ["number", "array", "number", "array", "number", "number"]);
}
function ode(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { dims: a } = s, o = w.parseAxisParam(a, r.shape);
if (r.shape.length === 0)
return lh({ inputs: { x: r }, backend: n });
let i = n.makeOutput(r.shape, r.dtype), u = n.dataIdMap.get(r.dataId).id, l = n.dataIdMap.get(i.dataId).id, c = new Uint8Array(new Int32Array(o).buffer), p = new Uint8Array(new Int32Array(r.shape).buffer);
HN(u, c, o.length, p, r.shape.length, l);
let d = yn({ inputs: { x: i }, attrs: { shape: r.shape }, backend: n });
return n.disposeData(i.dataId), d;
}
var ide = { kernelName: Pi, backendName: "wasm", kernelFunc: ode, setupFunc: ade };
var qN;
function ude(e) {
qN = e.wasm.cwrap(Yi, null, ["number", "number", "number", "number", "number", "number", "number", "number", "array", "number", "number"]);
}
function lde(e) {
let { inputs: t, backend: n, attrs: s } = e, { image: r } = t, { radians: a, fillValue: o, center: i } = s, u = n.makeOutput(r.shape, r.dtype), l = n.dataIdMap.get(r.dataId).id, c = n.dataIdMap.get(u.dataId).id, [p, d, h, f] = r.shape, [m, g] = C.getImageCenter(i, d, h), b = o === 0, y = 255, v = typeof o == "number" ? [o, o, o, b ? 0 : y] : [...o, y], x = new Uint8Array(new Int32Array(v).buffer);
return qN(l, p, d, h, f, a, m, g, x, v.length, c), u;
}
var cde = { kernelName: Yi, backendName: "wasm", kernelFunc: lde, setupFunc: ude };
var dde = Ht(zi);
var pde = Ht(oo);
var jN;
function hde(e) {
jN = e.wasm.cwrap(Li, null, ["number", "number", "number", "number", "number", "number", "array", "number", "number"]);
}
function fde(e) {
let { backend: t, inputs: n, attrs: s } = e, { indices: r, updates: a } = n, { shape: o } = s, i = t.makeOutput(o, a.dtype);
if (w.sizeFromShape(o) === 0)
return i;
let { sliceRank: u, numUpdates: l, sliceSize: c, strides: p, outputSize: d } = Kk.calculateShapes(a, r, o), f = t.dataIdMap.get(r.dataId).id, g = t.dataIdMap.get(a.dataId).id, b = new Uint8Array(new Int32Array(p).buffer), y = t.dataIdMap.get(i.dataId).id;
return jN(f, g, St[a.dtype], u, l, c, b, d, y), i;
}
var mde = { kernelName: Li, backendName: "wasm", setupFunc: hde, kernelFunc: fde };
var KN;
function gde(e) {
KN = e.wasm.cwrap("SelectV2", null, ["number", "number", "number", "number", "number"]);
}
function bde(e) {
let { inputs: t, backend: n } = e, { condition: s, t: r, e: a } = t, o = n.dataIdMap.get(s.dataId).id, i = n.dataIdMap.get(r.dataId).id, u = n.dataIdMap.get(a.dataId).id, l = n.makeOutput(r.shape, r.dtype), c = n.dataIdMap.get(l.dataId).id, p = s.shape.length, d = r.shape.length, h = p === 0 || p > 1 || d === 1 ? 1 : w.sizeFromShape(r.shape.slice(1));
return KN(o, i, u, h, c), l;
}
var yde = { kernelName: Mi, backendName: "wasm", kernelFunc: bde, setupFunc: gde };
var XN;
function vde(e) {
XN = e.wasm.cwrap(uo, null, ["number", "number"]);
}
function xde(e) {
let { backend: t, inputs: { x: n } } = e, s = t.dataIdMap.get(n.dataId).id, r = t.makeOutput(n.shape, n.dtype), a = t.dataIdMap.get(r.dataId).id;
return w.sizeFromShape(r.shape) === 0 || XN(s, a), r;
}
var wde = { kernelName: "Sigmoid", backendName: "wasm", setupFunc: vde, kernelFunc: xde };
var kde = Ht(io);
var YN;
function Sde(e) {
YN = e.wasm.cwrap(po, null, ["number", "number", "number", "number"]);
}
function Ide(e) {
let { backend: t, inputs: { logits: n }, attrs: { dim: s } } = e, r = t.dataIdMap.get(n.dataId).id, a = t.makeOutput(n.shape, n.dtype), o = t.dataIdMap.get(a.dataId).id, i = n.shape[s], u = w.sizeFromShape(n.shape) / i;
return w.sizeFromShape(a.shape) === 0 || YN(r, o, i, u), a;
}
var Cde = { kernelName: po, backendName: "wasm", setupFunc: Sde, kernelFunc: Ide };
function Nde(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, { blockShape: a, paddings: o } = s, i = w.sizeFromShape(a), u = [[0, 0]];
u.push(...o);
for (let I = 1 + a.length; I < r.shape.length; ++I)
u.push([0, 0]);
let l = VN.kernelFunc({ inputs: { x: r }, backend: n, attrs: { paddings: u, constantValue: 0 } }), c = C.getReshaped(l.shape, a, i, false), p = C.getPermuted(c.length, a.length, false), d = C.getReshapedPermuted(l.shape, a, i, false), m = yn({ inputs: { x: l }, backend: n, attrs: { shape: c } }), y = Sr({ inputs: { x: m }, backend: n, attrs: { perm: p } }), k = yn({ inputs: { x: y }, backend: n, attrs: { shape: d } });
return n.disposeData(l.dataId), n.disposeData(m.dataId), n.disposeData(y.dataId), k;
}
var Tde = { kernelName: Wi, backendName: "wasm", kernelFunc: Nde };
var QN;
function $de(e) {
QN = e.wasm.cwrap("SparseFillEmptyRows", "number", ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function _de(e) {
let { backend: t, inputs: n } = e, { indices: s, values: r, denseShape: a, defaultValue: o } = n, i = s.shape[0], u = s.shape[1], l = t.readSync(a.dataId)[0], c = [i + l, u], p = t.dataIdMap.get(s.dataId).id, d = t.dataIdMap.get(r.dataId).id, h = t.dataIdMap.get(o.dataId).id, f = t.makeOutput(c, s.dtype), m = t.dataIdMap.get(f.dataId).id, g = t.makeOutput(c.slice(0, 1), r.dtype), b = t.dataIdMap.get(g.dataId).id, y = t.makeOutput([l], "bool"), v = t.dataIdMap.get(y.dataId).id, x = t.makeOutput([i], s.dtype), k = t.dataIdMap.get(x.dataId).id, I = t.makeOutput([4], "int32"), $ = t.dataIdMap.get(I.dataId).id, R = QN(p, d, St[r.dtype], i, l, u, h, m, b, v, k, $), E = t.readSync(I.dataId), P;
switch (E[0]) {
case 1: {
P = C.getSparseFillEmptyRowsIndicesDenseShapeMismatch(E[1]);
break;
}
case 2: {
P = C.getSparseFillEmptyRowsNegativeIndexErrorMessage(E[1], E[2]);
break;
}
case 3:
P = C.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(E[1], E[2], E[3]);
break;
default:
P = "";
}
if (t.disposeData(I.dataId), P)
throw t.disposeData(f.dataId), t.disposeData(g.dataId), t.disposeData(y.dataId), t.disposeData(x.dataId), new Error(P);
let A = f, D = g;
return R !== c[0] && (A = xa({ inputs: { x: f }, attrs: { begin: 0, size: [R, u] }, backend: t }), D = xa({ inputs: { x: g }, attrs: { begin: 0, size: R }, backend: t }), t.disposeData(f.dataId), t.disposeData(g.dataId)), [A, D, y, x];
}
var Ade = { kernelName: dp, backendName: "wasm", setupFunc: $de, kernelFunc: _de };
var ZN;
function Ede(e) {
ZN = e.wasm.cwrap(Dl, null, ["number", "number", "number", "number", "number", "number", "number"]);
}
function Rde(e) {
let { backend: t, inputs: n } = e, { inputIndices: s, inputShape: r, newShape: a } = n;
if (s.shape.length !== 2)
throw new Error(`Input indices should be a matrix but received shape
${s.shape}`);
if (r.shape.length !== 1)
throw new Error(`Input shape should be a vector but received shape
${r.shape}`);
if (a.shape.length !== 1)
throw new Error(`Target shape should be a vector but received shape ${a.shape}`);
let o = t.dataIdMap.get(s.dataId).id, i = t.dataIdMap.get(r.dataId).id, u = t.dataIdMap.get(a.dataId).id, l = s.shape[0], c = w.sizeFromShape(a.shape), p = t.makeOutput([l, c], s.dtype), d = t.dataIdMap.get(p.dataId).id, h = t.makeOutput([c], a.dtype), f = t.dataIdMap.get(h.dataId).id, m = t.makeOutput([3], "int32"), g = t.dataIdMap.get(m.dataId).id;
ZN(o, i, u, l, d, f, g);
let b = t.readSync(m.dataId), y;
switch (b[0]) {
case 0: {
y = C.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(b[1], b[2]);
break;
}
case 1: {
y = C.getSparseReshapeNegativeOutputDimErrorMessage(b[1], b[2]);
break;
}
case 2:
y = C.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();
break;
case 3: {
let v = Array.from(t.readSync(r.dataId)), x = Array.from(t.readSync(h.dataId));
y = C.getSparseReshapeInputOutputMultipleErrorMessage(v, x);
break;
}
case 4: {
let v = Array.from(t.readSync(r.dataId)), x = Array.from(t.readSync(h.dataId));
y = C.getSparseReshapeInputOutputMismatchErrorMessage(v, x);
break;
}
default:
y = "";
}
if (t.disposeData(m.dataId), y)
throw t.disposeData(p.dataId), t.disposeData(h.dataId), new Error(y);
return [p, h];
}
var Dde = { kernelName: Dl, backendName: "wasm", setupFunc: Ede, kernelFunc: Rde };
var JN;
function eT(e) {
JN = e.wasm.cwrap("SparseSegmentReduction", null, ["number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function tT(e, t) {
let { backend: n, inputs: s } = e, { data: r, indices: a, segmentIds: o } = s, i = a.shape[0], u = n.readSync(o.dataId, i - 1, i)[0], c = i > 0 ? u + 1 : 0;
if (c < 0)
throw new Error(C.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());
let p = r.shape.slice();
p[0] = c;
let d = n.dataIdMap.get(r.dataId).id, h = n.dataIdMap.get(a.dataId).id, f = n.dataIdMap.get(o.dataId).id, m = n.makeOutput(p, r.dtype), g = n.dataIdMap.get(m.dataId).id, b = n.makeOutput([4], "int32"), y = n.dataIdMap.get(b.dataId).id;
JN(d, St[r.dtype], r.shape[0], h, f, g, y, t, 0);
let v = n.readSync(b.dataId), x;
switch (v[0]) {
case 0: {
x = C.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();
break;
}
case 1: {
x = C.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();
break;
}
case 2:
x = C.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(v[1], v[2]);
break;
case 3:
x = C.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(v[1], v[2], v[3]);
break;
default:
x = "";
}
if (n.disposeData(b.dataId), x)
throw n.disposeData(m.dataId), new Error(x);
return m;
}
function Fde(e) {
return tT(e, true);
}
var Ode = { kernelName: pp, backendName: "wasm", setupFunc: eT, kernelFunc: Fde };
function Pde(e) {
return tT(e, false);
}
var zde = { kernelName: hp, backendName: "wasm", setupFunc: eT, kernelFunc: Pde };
function Lde(e) {
let { inputs: t, attrs: n, backend: s } = e, { x: r } = t, { numOrSizeSplits: a, axis: o } = n, i = w.parseAxisParam(o, r.shape)[0], u = C.prepareSplitSize(r, a, i), l = new Array(r.shape.length).fill(0), c = r.shape.slice();
return u.map((p) => {
let d = [...c];
d[i] = p;
let h = xa({ inputs: { x: r }, attrs: { begin: l, size: d }, backend: s });
return l[i] += p, h;
});
}
var Mde = { kernelName: Ui, backendName: "wasm", kernelFunc: Lde };
var Bde = Ht(lo);
var Vde = Ht(Fl);
var Wde = true;
var Ude = Xt(ho, Wde);
var nT;
function Gde(e) {
nT = e.wasm.cwrap(go, null, ["number", "number", "number", "number"]);
}
function Hde(e) {
let { backend: t, inputs: n, attrs: s } = e, { alpha: r } = s, { x: a } = n, o = t.dataIdMap.get(a.dataId).id, i = t.makeOutput(a.shape, a.dtype), u = t.dataIdMap.get(i.dataId).id;
return nT(o, r, St[a.dtype], u), i;
}
var qde = { kernelName: go, backendName: "wasm", setupFunc: Gde, kernelFunc: Hde };
var sT;
function jde(e) {
sT = e.wasm.cwrap(Gi, null, ["number", "array", "number", "array", "array", "array", "array", "array", "number", "number"]);
}
function Kde(e) {
let { backend: t, inputs: n, attrs: s } = e, { x: r } = n, { begin: a, end: o, strides: i, beginMask: u, endMask: l, ellipsisMask: c, newAxisMask: p, shrinkAxisMask: d } = s, { finalShapeSparse: h, finalShape: f, isIdentity: m, sliceDim0: g, isSimpleSlice: b, begin: y, end: v, strides: x } = kt.sliceInfo(r.shape, a, o, i, u, l, c, p, d), k;
if (m)
k = yn({ inputs: { x: r }, backend: t, attrs: { shape: f } });
else if (g || b) {
w.assert(r.shape.length >= 1, () => `Input must have rank at least 1, got: ${r.shape.length}`);
let I = kt.computeOutShape(y, v, x), $ = xa({ inputs: { x: r }, backend: t, attrs: { begin: y, size: I } });
k = yn({ inputs: { x: $ }, backend: t, attrs: { shape: f } }), t.disposeData($.dataId);
} else {
let I = t.makeOutput(h, "float32"), $ = t.dataIdMap.get(r.dataId).id, R = new Uint8Array(new Int32Array(w.computeStrides(r.shape)).buffer), E = new Uint8Array(new Int32Array(y).buffer), P = new Uint8Array(new Int32Array(v).buffer), A = new Uint8Array(new Int32Array(x).buffer), D = new Uint8Array(new Int32Array(h).buffer), T = new Uint8Array(new Int32Array(w.computeStrides(h)).buffer), L = t.dataIdMap.get(I.dataId).id;
sT($, R, r.shape.length, E, P, A, D, T, h.length, L), k = yn({ inputs: { x: I }, backend: t, attrs: { shape: f } }), t.disposeData(I.dataId);
}
return k;
}
var Xde = { kernelName: Gi, backendName: "wasm", setupFunc: jde, kernelFunc: Kde };
var Yde = true;
var Qde = Xt(fo, Yde);
var rT;
function Zde(e) {
rT = e.wasm.cwrap(co, null, ["number", "number", "number", "number"]);
}
function Jde(e) {
let { backend: t, inputs: n, attrs: s } = e, { axis: r, keepDims: a } = s, { x: o } = n, i = t.dataIdMap.get(o.dataId).id, u = i, l = o, { transposed: c, axes: p, originalAxes: d, inputWasTransposed: h } = Pr(o, r, t), f = p;
if (h) {
let v = t.dataIdMap.get(c.dataId).id;
v !== i && (l = c, u = v, f = C.getInnerMostAxes(f.length, l.shape.length));
}
C.assertAxesAreInnerMostDims("sum", f, l.shape.length);
let [m, g] = C.computeOutAndReduceShapes(l.shape, f), b = w.sizeFromShape(g), y = t.makeOutput(m, l.dtype);
if (w.sizeFromShape(l.shape) !== 0) {
let v = t.dataIdMap.get(y.dataId).id;
rT(u, b, St[y.dtype], v);
}
if (h && t.disposeData(c.dataId), a) {
let v = C.expandShapeToKeepDim(y.shape, d);
y.shape = v;
}
return y;
}
var epe = { kernelName: co, backendName: "wasm", setupFunc: Zde, kernelFunc: Jde };
var tpe = Ht(Hi);
var npe = Ht(mo);
var aT;
function spe(e) {
aT = e.wasm.cwrap(Tr, null, ["number", "array", "number", "array", "number", "number"]);
}
function rpe(e) {
let { inputs: t, backend: n, attrs: s } = e, { x: r } = t, a = n.dataIdMap.get(r.dataId).id, { reps: o } = s, i = new Array(r.shape.length);
for (let d = 0; d < i.length; d++)
i[d] = r.shape[d] * o[d];
let u = new Uint8Array(new Int32Array(r.shape).buffer), l = new Uint8Array(new Int32Array(i).buffer), c = n.makeOutput(i, r.dtype), p = n.dataIdMap.get(c.dataId).id;
return aT(a, u, r.shape.length, l, i.length, St[c.dtype], p), c;
}
var ape = { kernelName: Tr, backendName: "wasm", setupFunc: spe, kernelFunc: rpe };
var oT;
function ope(e) {
oT = e.wasm.cwrap(qi, null, ["number", "array", "number", "number", "number", "bool", "number", "number"]);
}
var ipe = ({ inputs: e, backend: t, attrs: n }) => {
let { x: s } = e, { k: r, sorted: a } = n, o = t.dataIdMap.get(s.dataId).id, i = new Uint8Array(new Int32Array(s.shape).buffer), u = s.shape.slice();
u[u.length - 1] = r;
let l = t.makeOutput(u, s.dtype), c = t.dataIdMap.get(l.dataId).id, p = t.makeOutput(u, "int32"), d = t.dataIdMap.get(p.dataId).id;
return oT(o, i, s.shape.length, St[s.dtype], r, a, c, d), [l, p];
};
var upe = { kernelName: qi, backendName: "wasm", setupFunc: ope, kernelFunc: ipe };
var iT;
function lpe(e) {
iT = e.wasm.cwrap(ji, null, ["number", "number", "bool", "number", "number", "number", "number", "number", "number", "array", "number", "number", "number", "number", "number"]);
}
function cpe(e) {
let { backend: t, inputs: n, attrs: s } = e, { image: r, transforms: a } = n, { interpolation: o, fillMode: i, fillValue: u, outputShape: l } = s, [c, p, d, h] = r.shape, [f, m] = l != null ? l : [p, d], g = [c, f, m, h], b = new Uint8Array(new Int32Array(w.computeStrides(r.shape)).buffer), y = t.makeOutput(g, r.dtype), v = t.dataIdMap.get(y.dataId).id, k = t.dataIdMap.get(r.dataId).id, $ = t.dataIdMap.get(a.dataId).id, R = o === "nearest" ? 1 : 2, E;
switch (i) {
case "constant":
E = 1;
break;
case "reflect":
E = 2;
break;
case "wrap":
E = 3;
break;
case "nearest":
E = 4;
break;
default:
E = 1;
break;
}
return iT(k, $, a.shape[0] > 1, c, f, m, h, d, p, b, r.shape.length - 1, R, E, u, v), y;
}
var dpe = { kernelName: ji, backendName: "wasm", setupFunc: lpe, kernelFunc: cpe };
function ppe(e) {
let { inputs: t, backend: n, attrs: s } = e, { value: r } = t, { axis: a } = s;
a < 0 && (a += r.shape.length);
let o = r.shape[a], i = r.shape.length, u = new Array(i - 1), l = 0;
for (let h = 0; h < i; h++)
h !== a && (u[l++] = r.shape[h]);
let c = new Array(o), p = new Array(i).fill(0), d = r.shape.slice();
d[a] = 1;
for (let h = 0; h < c.length; h++)
p[a] = h, c[h] = xa({ inputs: { x: r }, attrs: { begin: p, size: d }, backend: n });
return c.map(({ dataId: h, dtype: f }) => ({ dataId: h, dtype: f, shape: u }));
}
var hpe = { kernelName: Ki, backendName: "wasm", kernelFunc: ppe };
function fpe(e) {
let { inputs: { x: t }, backend: n } = e, s = n.makeOutput(t.shape, t.dtype);
return n.typedArrayFromHeap(s).fill(0), s;
}
var mpe = { kernelName: Xi, backendName: "wasm", kernelFunc: fpe };
var gpe = [Jie, eue, nue, aue, hue, gue, vue, kue, Nue, Rue, Due, Fue, zue, Lue, Vue, Gue, Hue, que, Xue, Zue, tle, rle, ile, ule, cle, dle, ple, hle, gle, ble, vle, kle, Cle, $le, Ele, Fle, Ple, Lle, oue, Vle, Ule, Hle, qle, Kle, Xle, Qle, Jle, nce, rce, ice, cce, hce, mce, yce, xce, wce, Ice, Tce, Ace, Rce, Oce, zce, Mce, VN, Uce, qce, Xce, Qce, Jce, ede, tde, Sue, rde, ide, cde, dde, pde, mde, yde, wde, kde, Aue, Cde, Tde, Ade, Dde, Ode, zde, Mde, Bde, Vde, Ude, qde, Xde, Qde, epe, tpe, npe, ape, upe, dpe, cue, hpe, mpe];
for (let e of gpe)
Ol(e);
var cg = K();
cg.registerFlag("WASM_HAS_SIMD_SUPPORT", async () => WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 9, 1, 7, 0, 65, 0, 253, 15, 26, 11])));
cg.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT", async () => {
if (cg.get("IS_NODE"))
return false;
try {
return new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)), WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11]));
} catch (e) {
return false;
}
});
var ek = wa(k$());
var bpe = `"use strict";var Module={};var ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads");var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",function(data){onmessage({data:data})});var fs=require("fs");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,"utf8"))},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+"
");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=((info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports});self.onmessage=(e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob==="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance})}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInit();try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(Module["keepRuntimeAlive"]()){Module["PThread"].setExitStatus(result)}else{Module["__emscripten_thread_exit"](result)}}catch(ex){if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["__emscripten_thread_exit"](ex.status)}}else{throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["__emscripten_thread_exit"](-1)}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else if(e.data.cmd==="processProxyingQueue"){if(Module["_pthread_self"]()){Module["_emscripten_proxy_execute_queue"](e.data.queue)}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}});`;
var ype = wa(S$());
var vpe = class extends il {
constructor(e) {
super(), this.wasm = e, this.dataIdNextNumber = 1, this.wasm.tfjs.initWithThreadsCount(uT), dg = this.wasm.tfjs.getThreadsCount(), this.dataIdMap = new Zd(this, ds());
}
write(e, t, n) {
let s = { id: this.dataIdNextNumber++ };
return this.move(s, e, t, n, 1), s;
}
numDataIds() {
return this.dataIdMap.numDataIds();
}
async time(e) {
let t = w.now();
return e(), { kernelMs: w.now() - t };
}
move(e, t, n, s, r) {
let a = this.dataIdNextNumber++;
if (s === "string") {
let l = t;
this.dataIdMap.set(e, { id: a, stringBytes: l, shape: n, dtype: s, memoryOffset: null, refCount: r });
return;
}
let o = w.sizeFromShape(n), i = o * w.bytesPerElement(s), u = this.wasm._malloc(i);
this.dataIdMap.set(e, { id: a, memoryOffset: u, shape: n, dtype: s, refCount: r }), this.wasm.tfjs.registerTensor(a, o, u), t != null && this.wasm.HEAPU8.set(new Uint8Array(t.buffer, t.byteOffset, i), u);
}
async read(e) {
return this.readSync(e);
}
readSync(e, t, n) {
let { memoryOffset: s, dtype: r, shape: a, stringBytes: o } = this.dataIdMap.get(e);
if (r === "string")
return (t == null || t === 0) && (n == null || n >= o.length) ? o : o.slice(t, n);
t = t || 0, n = n || w.sizeFromShape(a);
let i = w.bytesPerElement(r), u = this.wasm.HEAPU8.slice(s + t * i, s + n * i);
return kpe(u.buffer, r);
}
disposeData(e, t = false) {
if (this.dataIdMap.has(e)) {
let n = this.dataIdMap.get(e);
if (n.refCount--, !t && n.refCount > 0)
return false;
this.wasm._free(n.memoryOffset), this.wasm.tfjs.disposeData(n.id), this.dataIdMap.delete(e);
}
return true;
}
refCount(e) {
return this.dataIdMap.has(e) ? this.dataIdMap.get(e).refCount : 0;
}
incRef(e) {
let t = this.dataIdMap.get(e);
t != null && t.refCount++;
}
floatPrecision() {
return 32;
}
getMemoryOffset(e) {
return this.dataIdMap.get(e).memoryOffset;
}
dispose() {
this.wasm.tfjs.dispose(), "PThread" in this.wasm && this.wasm.PThread.terminateAllThreads(), this.wasm = null;
}
memory() {
return { unreliable: false };
}
makeOutput(e, t, n) {
let s;
if (n == null)
s = this.write(null, e, t);
else {
let r = this.dataIdNextNumber++;
s = { id: r }, this.dataIdMap.set(s, { id: r, memoryOffset: n, shape: e, dtype: t, refCount: 1 });
let a = w.sizeFromShape(e);
this.wasm.tfjs.registerTensor(r, a, n);
}
return { dataId: s, shape: e, dtype: t };
}
typedArrayFromHeap({ shape: e, dtype: t, dataId: n }) {
let s = this.wasm.HEAPU8.buffer, { memoryOffset: r } = this.dataIdMap.get(n), a = w.sizeFromShape(e);
switch (t) {
case "float32":
return new Float32Array(s, r, a);
case "int32":
return new Int32Array(s, r, a);
case "bool":
return new Uint8Array(s, r, a);
default:
throw new Error(`Unknown dtype ${t}`);
}
}
};
function xpe(e) {
return (t, n) => (w.fetch(e, { credentials: "same-origin" }).then((s) => {
s.ok || t.env.a(`failed to load wasm binary file at '${e}'`), s.arrayBuffer().then((r) => {
WebAssembly.instantiate(r, t).then((a) => {
n(a.instance, a.module);
});
});
}), {});
}
function tk(e, t, n) {
if (Xd != null)
return Xd;
let s = "tfjs-backend-wasm.wasm";
return e && t ? s = "tfjs-backend-wasm-threaded-simd.wasm" : e && (s = "tfjs-backend-wasm-simd.wasm"), Uu != null && Uu[s] != null ? Uu[s] : n + s;
}
async function wpe() {
let [e, t] = await Promise.all([K().getAsync("WASM_HAS_SIMD_SUPPORT"), K().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);
return new Promise((n, s) => {
let r = {};
r.locateFile = (i, u) => {
if (i.endsWith(".worker.js")) {
let l = bpe.replace(/\n/g, "\\n"), c = new Blob([l], { type: "application/javascript" });
return URL.createObjectURL(c);
}
return i.endsWith(".wasm") ? tk(e, t, Bu != null ? Bu : u) : u + i;
}, Gv && (r.instantiateWasm = xpe(tk(e, t, Bu != null ? Bu : "")));
let a = false;
r.onAbort = () => {
if (a || Gu)
return;
Gu = true, s({ message: "Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers" });
};
let o;
t && e && Xd == null ? (r.mainScriptUrlOrBlob = new Blob(["var WasmBackendModuleThreadedSimd = " + ek.default.toString()], { type: "text/javascript" }), o = (0, ek.default)(r)) : o = (0, ype.default)(r), o.then((i) => {
a = true, Gu = false;
let u = null;
i.tfjs = { init: i.cwrap("init", null, []), initWithThreadsCount: i.cwrap("init_with_threads_count", null, ["number"]), getThreadsCount: i.cwrap("get_threads_count", "number", []), registerTensor: i.cwrap("register_tensor", null, ["number", "number", "number"]), disposeData: i.cwrap("dispose_data", u, ["number"]), dispose: i.cwrap("dispose", u, []) }, n({ wasm: i });
});
});
}
function kpe(e, t) {
switch (t) {
case "float32":
return new Float32Array(e);
case "int32":
return new Int32Array(e);
case "bool":
return new Uint8Array(e);
default:
throw new Error(`Unknown dtype ${t}`);
}
}
var Spe = ["tfjs-backend-wasm.wasm", "tfjs-backend-wasm-simd.wasm", "tfjs-backend-wasm-threaded-simd.wasm"];
var Xd = null;
var Bu = null;
var Uu = {};
var Gu = false;
var Gv = false;
function Mhe(e, t = false) {
if (Wk("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."), Gu)
throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");
Xd = e, Gv = t;
}
function Bhe(e, t = false) {
if (Gu)
throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`");
if (typeof e == "string")
Bu = e;
else {
Uu = e;
let n = Spe.filter((s) => Uu[s] == null);
if (n.length > 0)
throw new Error(`There were no entries found for the following binaries: ${n.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`);
}
Gv = t;
}
var uT = -1;
var dg = -1;
function Vhe(e) {
uT = e;
}
function Whe() {
if (dg === -1)
throw new Error("WASM backend not initialized.");
return dg;
}
var Uhe = "0.0.0";
var Ipe = 2;
xp("wasm", async () => {
let { wasm: e } = await wpe();
return new vpe(e);
}, Ipe);
var sr = "3.18.0-20220602";
var Ghe = { tfjs: sr, "tfjs-core": sr, "tfjs-data": sr, "tfjs-layers": sr, "tfjs-converter": sr, "tfjs-backend-cpu": sr, "tfjs-backend-webgl": sr, "tfjs-backend-wasm": sr };
// src/image/imagefxshaders.ts
var vertexIdentity = `
precision highp float;
attribute vec2 pos;
attribute vec2 uv;
varying vec2 vUv;
uniform float flipY;
void main(void) {
vUv = uv;
gl_Position = vec4(pos.x, pos.y*flipY, 0.0, 1.);
}
`;
var colorMatrixWithAlpha = `
precision highp float;
varying vec2 vUv;
uniform sampler2D texture;
uniform float m[20];
void main(void) {
vec4 c = texture2D(texture, vUv);
gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[3] * c.a + m[4];
gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[8] * c.a + m[9];
gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[13] * c.a + m[14];
gl_FragColor.a = m[15] * c.r + m[16] * c.g + m[17] * c.b + m[18] * c.a + m[19];
}
`;
var colorMatrixWithoutAlpha = `
precision highp float;
varying vec2 vUv;
uniform sampler2D texture;
uniform float m[20];
void main(void) {
vec4 c = texture2D(texture, vUv);
gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[4];
gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[9];
gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[14];
gl_FragColor.a = c.a;
}
`;
var pixelate = `
precision highp float;
varying vec2 vUv;
uniform vec2 size;
uniform sampler2D texture;
vec2 pixelate(vec2 coord, vec2 size) {
return floor( coord / size ) * size;
}
void main(void) {
gl_FragColor = vec4(0.0);
vec2 coord = pixelate(vUv, size);
gl_FragColor += texture2D(texture, coord);
}
`;
var blur = `
precision highp float;
varying vec2 vUv;
uniform sampler2D texture;
uniform vec2 px;
void main(void) {
gl_FragColor = vec4(0.0);
gl_FragColor += texture2D(texture, vUv + vec2(-7.0*px.x, -7.0*px.y))*0.0044299121055113265;
gl_FragColor += texture2D(texture, vUv + vec2(-6.0*px.x, -6.0*px.y))*0.00895781211794;
gl_FragColor += texture2D(texture, vUv + vec2(-5.0*px.x, -5.0*px.y))*0.0215963866053;
gl_FragColor += texture2D(texture, vUv + vec2(-4.0*px.x, -4.0*px.y))*0.0443683338718;
gl_FragColor += texture2D(texture, vUv + vec2(-3.0*px.x, -3.0*px.y))*0.0776744219933;
gl_FragColor += texture2D(texture, vUv + vec2(-2.0*px.x, -2.0*px.y))*0.115876621105;
gl_FragColor += texture2D(texture, vUv + vec2(-1.0*px.x, -1.0*px.y))*0.147308056121;
gl_FragColor += texture2D(texture, vUv )*0.159576912161;
gl_FragColor += texture2D(texture, vUv + vec2( 1.0*px.x, 1.0*px.y))*0.147308056121;
gl_FragColor += texture2D(texture, vUv + vec2( 2.0*px.x, 2.0*px.y))*0.115876621105;
gl_FragColor += texture2D(texture, vUv + vec2( 3.0*px.x, 3.0*px.y))*0.0776744219933;
gl_FragColor += texture2D(texture, vUv + vec2( 4.0*px.x, 4.0*px.y))*0.0443683338718;
gl_FragColor += texture2D(texture, vUv + vec2( 5.0*px.x, 5.0*px.y))*0.0215963866053;
gl_FragColor += texture2D(texture, vUv + vec2( 6.0*px.x, 6.0*px.y))*0.00895781211794;
gl_FragColor += texture2D(texture, vUv + vec2( 7.0*px.x, 7.0*px.y))*0.0044299121055113265;
}
`;
var convolution = `
precision highp float;
varying vec2 vUv;
uniform sampler2D texture;
uniform vec2 px;
uniform float m[9];
void main(void) {
vec4 c11 = texture2D(texture, vUv - px); // top left
vec4 c12 = texture2D(texture, vec2(vUv.x, vUv.y - px.y)); // top center
vec4 c13 = texture2D(texture, vec2(vUv.x + px.x, vUv.y - px.y)); // top right
vec4 c21 = texture2D(texture, vec2(vUv.x - px.x, vUv.y) ); // mid left
vec4 c22 = texture2D(texture, vUv); // mid center
vec4 c23 = texture2D(texture, vec2(vUv.x + px.x, vUv.y) ); // mid right
vec4 c31 = texture2D(texture, vec2(vUv.x - px.x, vUv.y + px.y) ); // bottom left
vec4 c32 = texture2D(texture, vec2(vUv.x, vUv.y + px.y) ); // bottom center
vec4 c33 = texture2D(texture, vUv + px ); // bottom right
gl_FragColor =
c11 * m[0] + c12 * m[1] + c22 * m[2] +
c21 * m[3] + c22 * m[4] + c23 * m[5] +
c31 * m[6] + c32 * m[7] + c33 * m[8];
gl_FragColor.a = c22.a;
}
`;
// src/image/imagefx.ts
var collect = (source, prefix, collection) => {
const r = new RegExp("\\b" + prefix + " \\w+ (\\w+)", "ig");
source.replace(r, (match3, name) => {
collection[name] = 0;
return match3;
});
};
var GLProgram = class {
constructor(gl2, vertexSource, fragmentSource) {
__publicField(this, "uniform", {});
__publicField(this, "attribute", {});
__publicField(this, "gl");
__publicField(this, "id");
__publicField(this, "compile", (source, type) => {
const shader = this.gl.createShader(type);
if (!shader) {
log("filter: could not create shader");
return null;
}
this.gl.shaderSource(shader, source);
this.gl.compileShader(shader);
if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) {
log(`filter: gl compile failed: ${this.gl.getShaderInfoLog(shader)}`);
return null;
}
return shader;
});
this.gl = gl2;
const vertexShader = this.compile(vertexSource, this.gl.VERTEX_SHADER);
const fragmentShader = this.compile(fragmentSource, this.gl.FRAGMENT_SHADER);
this.id = this.gl.createProgram();
if (!vertexShader || !fragmentShader)
return;
if (!this.id) {
log("filter: could not create webgl program");
return;
}
this.gl.attachShader(this.id, vertexShader);
this.gl.attachShader(this.id, fragmentShader);
this.gl.linkProgram(this.id);
if (!this.gl.getProgramParameter(this.id, this.gl.LINK_STATUS)) {
log(`filter: gl link failed: ${this.gl.getProgramInfoLog(this.id)}`);
return;
}
this.gl.useProgram(this.id);
collect(vertexSource, "attribute", this.attribute);
for (const a in this.attribute)
this.attribute[a] = this.gl.getAttribLocation(this.id, a);
collect(vertexSource, "uniform", this.uniform);
collect(fragmentSource, "uniform", this.uniform);
for (const u in this.uniform)
this.uniform[u] = this.gl.getUniformLocation(this.id, u);
}
};
function GLImageFilter() {
let drawCount = 0;
let sourceTexture = null;
let lastInChain = false;
let currentFramebufferIndex = -1;
let tempFramebuffers = [null, null];
let filterChain = [];
let vertexBuffer = null;
let currentProgram = null;
const fxcanvas = canvas(100, 100);
const shaderProgramCache = {};
const DRAW = { INTERMEDIATE: 1 };
const gl2 = fxcanvas.getContext("webgl");
if (!gl2) {
log("filter: cannot get webgl context");
return;
}
this.gl = gl2;
function resize(width, height) {
if (width === fxcanvas.width && height === fxcanvas.height)
return;
fxcanvas.width = width;
fxcanvas.height = height;
if (!vertexBuffer) {
const vertices = new Float32Array([-1, -1, 0, 1, 1, -1, 1, 1, -1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 1, 1, 1, 1, 1, 0]);
vertexBuffer = gl2.createBuffer();
gl2.bindBuffer(gl2.ARRAY_BUFFER, vertexBuffer);
gl2.bufferData(gl2.ARRAY_BUFFER, vertices, gl2.STATIC_DRAW);
gl2.pixelStorei(gl2.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
}
gl2.viewport(0, 0, fxcanvas.width, fxcanvas.height);
tempFramebuffers = [null, null];
}
function createFramebufferTexture(width, height) {
const fbo = gl2.createFramebuffer();
gl2.bindFramebuffer(gl2.FRAMEBUFFER, fbo);
const renderbuffer = gl2.createRenderbuffer();
gl2.bindRenderbuffer(gl2.RENDERBUFFER, renderbuffer);
const texture = gl2.createTexture();
gl2.bindTexture(gl2.TEXTURE_2D, texture);
gl2.texImage2D(gl2.TEXTURE_2D, 0, gl2.RGBA, width, height, 0, gl2.RGBA, gl2.UNSIGNED_BYTE, null);
gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MAG_FILTER, gl2.LINEAR);
gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MIN_FILTER, gl2.LINEAR);
gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_S, gl2.CLAMP_TO_EDGE);
gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_T, gl2.CLAMP_TO_EDGE);
gl2.framebufferTexture2D(gl2.FRAMEBUFFER, gl2.COLOR_ATTACHMENT0, gl2.TEXTURE_2D, texture, 0);
gl2.bindTexture(gl2.TEXTURE_2D, null);
gl2.bindFramebuffer(gl2.FRAMEBUFFER, null);
return { fbo, texture };
}
function getTempFramebuffer(index2) {
tempFramebuffers[index2] = tempFramebuffers[index2] || createFramebufferTexture(fxcanvas.width, fxcanvas.height);
return tempFramebuffers[index2];
}
function draw(flags = 0) {
if (!currentProgram)
return;
let source = null;
let target = null;
let flipY = false;
if (drawCount === 0)
source = sourceTexture;
else
source = getTempFramebuffer(currentFramebufferIndex).texture || null;
drawCount++;
if (lastInChain && !(flags & DRAW.INTERMEDIATE)) {
target = null;
flipY = drawCount % 2 === 0;
} else {
currentFramebufferIndex = (currentFramebufferIndex + 1) % 2;
target = getTempFramebuffer(currentFramebufferIndex).fbo || null;
}
gl2.bindTexture(gl2.TEXTURE_2D, source);
gl2.bindFramebuffer(gl2.FRAMEBUFFER, target);
gl2.uniform1f(currentProgram.uniform["flipY"], flipY ? -1 : 1);
gl2.drawArrays(gl2.TRIANGLES, 0, 6);
}
function compileShader(fragmentSource) {
if (shaderProgramCache[fragmentSource]) {
currentProgram = shaderProgramCache[fragmentSource];
gl2.useProgram((currentProgram ? currentProgram.id : null) || null);
return currentProgram;
}
currentProgram = new GLProgram(gl2, vertexIdentity, fragmentSource);
if (!currentProgram) {
log("filter: could not get webgl program");
return null;
}
const floatSize = Float32Array.BYTES_PER_ELEMENT;
const vertSize = 4 * floatSize;
gl2.enableVertexAttribArray(currentProgram.attribute["pos"]);
gl2.vertexAttribPointer(currentProgram.attribute["pos"], 2, gl2.FLOAT, false, vertSize, 0 * floatSize);
gl2.enableVertexAttribArray(currentProgram.attribute["uv"]);
gl2.vertexAttribPointer(currentProgram.attribute["uv"], 2, gl2.FLOAT, false, vertSize, 2 * floatSize);
shaderProgramCache[fragmentSource] = currentProgram;
return currentProgram;
}
const filter = {
colorMatrix: (matrix) => {
const m = new Float32Array(matrix);
m[4] /= 255;
m[9] /= 255;
m[14] /= 255;
m[19] /= 255;
const shader = m[18] === 1 && m[3] === 0 && m[8] === 0 && m[13] === 0 && m[15] === 0 && m[16] === 0 && m[17] === 0 && m[19] === 0 ? colorMatrixWithoutAlpha : colorMatrixWithAlpha;
const program = compileShader(shader);
if (!program)
return;
gl2.uniform1fv(program.uniform["m"], m);
draw();
},
brightness: (brightness) => {
const b = (brightness || 0) + 1;
filter.colorMatrix([
b,
0,
0,
0,
0,
0,
b,
0,
0,
0,
0,
0,
b,
0,
0,
0,
0,
0,
1,
0
]);
},
saturation: (amount) => {
const x = (amount || 0) * 2 / 3 + 1;
const y = (x - 1) * -0.5;
filter.colorMatrix([
x,
y,
y,
0,
0,
y,
x,
y,
0,
0,
y,
y,
x,
0,
0,
0,
0,
0,
1,
0
]);
},
desaturate: () => {
filter.saturation(-1);
},
contrast: (amount) => {
const v = (amount || 0) + 1;
const o = -128 * (v - 1);
filter.colorMatrix([
v,
0,
0,
0,
o,
0,
v,
0,
0,
o,
0,
0,
v,
0,
o,
0,
0,
0,
1,
0
]);
},
negative: () => {
filter.contrast(-2);
},
hue: (rotation) => {
rotation = (rotation || 0) / 180 * Math.PI;
const cos = Math.cos(rotation);
const sin = Math.sin(rotation);
const lumR = 0.213;
const lumG = 0.715;
const lumB = 0.072;
filter.colorMatrix([
lumR + cos * (1 - lumR) + sin * -lumR,
lumG + cos * -lumG + sin * -lumG,
lumB + cos * -lumB + sin * (1 - lumB),
0,
0,
lumR + cos * -lumR + sin * 0.143,
lumG + cos * (1 - lumG) + sin * 0.14,
lumB + cos * -lumB + sin * -0.283,
0,
0,
lumR + cos * -lumR + sin * -(1 - lumR),
lumG + cos * -lumG + sin * lumG,
lumB + cos * (1 - lumB) + sin * lumB,
0,
0,
0,
0,
0,
1,
0
]);
},
desaturateLuminance: () => {
filter.colorMatrix([
0.2764723,
0.929708,
0.0938197,
0,
-37.1,
0.2764723,
0.929708,
0.0938197,
0,
-37.1,
0.2764723,
0.929708,
0.0938197,
0,
-37.1,
0,
0,
0,
1,
0
]);
},
sepia: () => {
filter.colorMatrix([
0.393,
0.7689999,
0.18899999,
0,
0,
0.349,
0.6859999,
0.16799999,
0,
0,
0.272,
0.5339999,
0.13099999,
0,
0,
0,
0,
0,
1,
0
]);
},
brownie: () => {
filter.colorMatrix([
0.5997023498159715,
0.34553243048391263,
-0.2708298674538042,
0,
47.43192855600873,
-0.037703249837783157,
0.8609577587992641,
0.15059552388459913,
0,
-36.96841498319127,
0.24113635128153335,
-0.07441037908422492,
0.44972182064877153,
0,
-7.562075277591283,
0,
0,
0,
1,
0
]);
},
vintagePinhole: () => {
filter.colorMatrix([
0.6279345635605994,
0.3202183420819367,
-0.03965408211312453,
0,
9.651285835294123,
0.02578397704808868,
0.6441188644374771,
0.03259127616149294,
0,
7.462829176470591,
0.0466055556782719,
-0.0851232987247891,
0.5241648018700465,
0,
5.159190588235296,
0,
0,
0,
1,
0
]);
},
kodachrome: () => {
filter.colorMatrix([
1.1285582396593525,
-0.3967382283601348,
-0.03992559172921793,
0,
63.72958762196502,
-0.16404339962244616,
1.0835251566291304,
-0.05498805115633132,
0,
24.732407896706203,
-0.16786010706155763,
-0.5603416277695248,
1.6014850761964943,
0,
35.62982807460946,
0,
0,
0,
1,
0
]);
},
technicolor: () => {
filter.colorMatrix([
1.9125277891456083,
-0.8545344976951645,
-0.09155508482755585,
0,
11.793603434377337,
-0.3087833385928097,
1.7658908555458428,
-0.10601743074722245,
0,
-70.35205161461398,
-0.231103377548616,
-0.7501899197440212,
1.847597816108189,
0,
30.950940869491138,
0,
0,
0,
1,
0
]);
},
polaroid: () => {
filter.colorMatrix([
1.438,
-0.062,
-0.062,
0,
0,
-0.122,
1.378,
-0.122,
0,
0,
-0.016,
-0.016,
1.483,
0,
0,
0,
0,
0,
1,
0
]);
},
shiftToBGR: () => {
filter.colorMatrix([
0,
0,
1,
0,
0,
0,
1,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
1,
0
]);
},
convolution: (matrix) => {
const m = new Float32Array(matrix);
const pixelSizeX = 1 / fxcanvas.width;
const pixelSizeY = 1 / fxcanvas.height;
const program = compileShader(convolution);
if (!program)
return;
gl2.uniform1fv(program.uniform["m"], m);
gl2.uniform2f(program.uniform["px"], pixelSizeX, pixelSizeY);
draw();
},
detectEdges: () => {
filter.convolution.call(this, [
0,
1,
0,
1,
-4,
1,
0,
1,
0
]);
},
sobelX: () => {
filter.convolution.call(this, [
-1,
0,
1,
-2,
0,
2,
-1,
0,
1
]);
},
sobelY: () => {
filter.convolution.call(this, [
-1,
-2,
-1,
0,
0,
0,
1,
2,
1
]);
},
sharpen: (amount) => {
const a = amount || 1;
filter.convolution.call(this, [
0,
-1 * a,
0,
-1 * a,
1 + 4 * a,
-1 * a,
0,
-1 * a,
0
]);
},
emboss: (size2) => {
const s = size2 || 1;
filter.convolution.call(this, [
-2 * s,
-1 * s,
0,
-1 * s,
1,
1 * s,
0,
1 * s,
2 * s
]);
},
blur: (size2) => {
const blurSizeX = size2 / 7 / fxcanvas.width;
const blurSizeY = size2 / 7 / fxcanvas.height;
const program = compileShader(blur);
if (!program)
return;
gl2.uniform2f(program.uniform["px"], 0, blurSizeY);
draw(DRAW.INTERMEDIATE);
gl2.uniform2f(program.uniform["px"], blurSizeX, 0);
draw();
},
pixelate: (size2) => {
const blurSizeX = size2 / fxcanvas.width;
const blurSizeY = size2 / fxcanvas.height;
const program = compileShader(pixelate);
if (!program)
return;
gl2.uniform2f(program.uniform["size"], blurSizeX, blurSizeY);
draw();
}
};
this.add = function(name) {
const args = Array.prototype.slice.call(arguments, 1);
const func = filter[name];
filterChain.push({ func, args });
};
this.reset = function() {
filterChain = [];
};
this.get = function() {
return filterChain;
};
this.apply = function(image) {
resize(image.width, image.height);
drawCount = 0;
if (!sourceTexture)
sourceTexture = gl2.createTexture();
gl2.bindTexture(gl2.TEXTURE_2D, sourceTexture);
gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_S, gl2.CLAMP_TO_EDGE);
gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_T, gl2.CLAMP_TO_EDGE);
gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MIN_FILTER, gl2.NEAREST);
gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MAG_FILTER, gl2.NEAREST);
gl2.texImage2D(gl2.TEXTURE_2D, 0, gl2.RGBA, gl2.RGBA, gl2.UNSIGNED_BYTE, image);
for (let i = 0; i < filterChain.length; i++) {
lastInChain = i === filterChain.length - 1;
const f = filterChain[i];
f.func.apply(this, f.args || []);
}
return fxcanvas;
};
this.draw = function(image) {
this.add("brightness", 0);
return this.apply(image);
};
}
// src/image/enhance.ts
async function histogramEqualization(inputImage) {
const squeeze = inputImage.shape.length === 4 ? br(inputImage) : inputImage;
const channels = Bn(squeeze, 3, 2);
const min = [Nm(channels[0]), Nm(channels[1]), Nm(channels[2])];
const max = [As(channels[0]), As(channels[1]), As(channels[2])];
const absMax = await Promise.all(max.map((channel) => channel.data()));
const maxValue = 0.99 * Math.max(absMax[0][0], absMax[1][0], absMax[2][0]);
const sub = [ge(channels[0], min[0]), ge(channels[1], min[1]), ge(channels[2], min[2])];
const range = [ge(max[0], min[0]), ge(max[1], min[1]), ge(max[2], min[2])];
const fact = [xe(maxValue, range[0]), xe(maxValue, range[1]), xe(maxValue, range[2])];
const enh = [V(sub[0], fact[0]), V(sub[1], fact[1]), V(sub[2], fact[2])];
const rgb2 = es([enh[0], enh[1], enh[2]], 2);
const reshape = U(rgb2, [1, squeeze.shape[0], squeeze.shape[1], 3]);
De([...channels, ...min, ...max, ...sub, ...range, ...fact, ...enh, rgb2, squeeze]);
return reshape;
}
// src/image/image.ts
var maxSize = 3840;
var inCanvas = null;
var outCanvas = null;
var tmpCanvas = null;
var fx2;
var last = {
inputSum: 0,
cacheDiff: 1,
sumMethod: 0,
inputTensor: void 0
};
function canvas(width, height) {
let c;
if (env.browser) {
if (env.worker) {
if (typeof OffscreenCanvas === "undefined")
throw new Error("canvas error: attempted to run in web worker but OffscreenCanvas is not supported");
c = new OffscreenCanvas(width, height);
} else {
if (typeof document === "undefined")
throw new Error("canvas error: attempted to run in browser but DOM is not defined");
c = document.createElement("canvas");
c.width = width;
c.height = height;
}
} else {
if (typeof env.Canvas !== "undefined")
c = new env.Canvas(width, height);
else if (typeof globalThis.Canvas !== "undefined")
c = new globalThis.Canvas(width, height);
}
return c;
}
function copy(input, output) {
const outputCanvas = output || canvas(input.width, input.height);
const ctx = outputCanvas.getContext("2d");
ctx.drawImage(input, 0, 0);
return outputCanvas;
}
async function process2(input, config3, getTensor = true) {
if (!input) {
if (config3.debug)
log("input error: input is missing");
return { tensor: null, canvas: null };
}
if (!(input instanceof et) && !(typeof Image !== "undefined" && input instanceof Image) && !(typeof env.Canvas !== "undefined" && input instanceof env.Canvas) && !(typeof globalThis.Canvas !== "undefined" && input instanceof globalThis.Canvas) && !(typeof ImageData !== "undefined" && input instanceof ImageData) && !(typeof ImageBitmap !== "undefined" && input instanceof ImageBitmap) && !(typeof HTMLImageElement !== "undefined" && input instanceof HTMLImageElement) && !(typeof HTMLMediaElement !== "undefined" && input instanceof HTMLMediaElement) && !(typeof HTMLVideoElement !== "undefined" && input instanceof HTMLVideoElement) && !(typeof HTMLCanvasElement !== "undefined" && input instanceof HTMLCanvasElement) && !(typeof OffscreenCanvas !== "undefined" && input instanceof OffscreenCanvas)) {
throw new Error("input error: type is not recognized");
}
if (input instanceof et) {
let tensor = null;
if (input["isDisposedInternal"])
throw new Error("input error: attempted to use tensor but it is disposed");
if (!input["shape"])
throw new Error("input error: attempted to use tensor without a shape");
if (input.shape.length === 3) {
if (input.shape[2] === 3) {
tensor = Pn(input, 0);
} else if (input.shape[2] === 4) {
const rgb2 = vb(input, [0, 0, 0], [-1, -1, 3]);
tensor = Pn(rgb2, 0);
De(rgb2);
}
} else if (input.shape.length === 4) {
if (input.shape[3] === 3) {
tensor = lr(input);
} else if (input.shape[3] === 4) {
tensor = Td(input, [0, 0, 0, 0], [-1, -1, -1, 3]);
}
}
if (tensor == null || tensor.shape.length !== 4 || tensor.shape[0] !== 1 || tensor.shape[3] !== 3)
throw new Error(`input error: attempted to use tensor with unrecognized shape: ${input["shape"]}`);
if (tensor.dtype === "int32") {
const cast = le(tensor, "float32");
De(tensor);
tensor = cast;
}
return { tensor, canvas: config3.filter.return ? outCanvas : null };
} else {
if (typeof input["readyState"] !== "undefined" && input["readyState"] <= 2) {
if (config3.debug)
log("input stream is not ready");
return { tensor: null, canvas: inCanvas };
}
const originalWidth = input["naturalWidth"] || input["videoWidth"] || input["width"] || input["shape"] && input["shape"][1] > 0;
const originalHeight = input["naturalHeight"] || input["videoHeight"] || input["height"] || input["shape"] && input["shape"][2] > 0;
if (!originalWidth || !originalHeight) {
if (config3.debug)
log("cannot determine input dimensions");
return { tensor: null, canvas: inCanvas };
}
let targetWidth = originalWidth;
let targetHeight = originalHeight;
if (targetWidth > maxSize) {
targetWidth = maxSize;
targetHeight = Math.trunc(targetWidth * originalHeight / originalWidth);
}
if (targetHeight > maxSize) {
targetHeight = maxSize;
targetWidth = Math.trunc(targetHeight * originalWidth / originalHeight);
}
if ((config3.filter.width || 0) > 0)
targetWidth = config3.filter.width;
else if ((config3.filter.height || 0) > 0)
targetWidth = originalWidth * ((config3.filter.height || 0) / originalHeight);
if ((config3.filter.height || 0) > 0)
targetHeight = config3.filter.height;
else if ((config3.filter.width || 0) > 0)
targetHeight = originalHeight * ((config3.filter.width || 0) / originalWidth);
if (!targetWidth || !targetHeight)
throw new Error("input error: cannot determine dimension");
if (!inCanvas || (inCanvas == null ? void 0 : inCanvas.width) !== targetWidth || (inCanvas == null ? void 0 : inCanvas.height) !== targetHeight)
inCanvas = canvas(targetWidth, targetHeight);
const inCtx = inCanvas.getContext("2d");
if (typeof ImageData !== "undefined" && input instanceof ImageData) {
inCtx.putImageData(input, 0, 0);
} else {
if (config3.filter.flip && typeof inCtx.translate !== "undefined") {
inCtx.translate(originalWidth, 0);
inCtx.scale(-1, 1);
inCtx.drawImage(input, 0, 0, originalWidth, originalHeight, 0, 0, inCanvas == null ? void 0 : inCanvas.width, inCanvas == null ? void 0 : inCanvas.height);
inCtx.setTransform(1, 0, 0, 1, 0, 0);
} else {
inCtx.drawImage(input, 0, 0, originalWidth, originalHeight, 0, 0, inCanvas == null ? void 0 : inCanvas.width, inCanvas == null ? void 0 : inCanvas.height);
}
}
if (!outCanvas || inCanvas.width !== outCanvas.width || (inCanvas == null ? void 0 : inCanvas.height) !== (outCanvas == null ? void 0 : outCanvas.height))
outCanvas = canvas(inCanvas.width, inCanvas.height);
if (config3.filter.enabled && env.webgl.supported) {
if (!fx2)
fx2 = env.browser ? new GLImageFilter() : null;
env.filter = !!fx2;
if (!fx2 || !fx2.add) {
if (config3.debug)
log("input process error: cannot initialize filters");
env.webgl.supported = false;
config3.filter.enabled = false;
copy(inCanvas, outCanvas);
} else {
fx2.reset();
if (config3.filter.brightness !== 0)
fx2.add("brightness", config3.filter.brightness);
if (config3.filter.contrast !== 0)
fx2.add("contrast", config3.filter.contrast);
if (config3.filter.sharpness !== 0)
fx2.add("sharpen", config3.filter.sharpness);
if (config3.filter.blur !== 0)
fx2.add("blur", config3.filter.blur);
if (config3.filter.saturation !== 0)
fx2.add("saturation", config3.filter.saturation);
if (config3.filter.hue !== 0)
fx2.add("hue", config3.filter.hue);
if (config3.filter.negative)
fx2.add("negative");
if (config3.filter.sepia)
fx2.add("sepia");
if (config3.filter.vintage)
fx2.add("brownie");
if (config3.filter.sepia)
fx2.add("sepia");
if (config3.filter.kodachrome)
fx2.add("kodachrome");
if (config3.filter.technicolor)
fx2.add("technicolor");
if (config3.filter.polaroid)
fx2.add("polaroid");
if (config3.filter.pixelate !== 0)
fx2.add("pixelate", config3.filter.pixelate);
if (fx2.get() > 0)
outCanvas = fx2.apply(inCanvas);
else
outCanvas = fx2.draw(inCanvas);
}
} else {
copy(inCanvas, outCanvas);
if (fx2)
fx2 = null;
env.filter = !!fx2;
}
if (!getTensor)
return { tensor: null, canvas: outCanvas };
if (!outCanvas)
throw new Error("canvas error: cannot create output");
let pixels;
let depth = 3;
if (typeof ImageData !== "undefined" && input instanceof ImageData || input["data"] && input["width"] && input["height"]) {
if (env.browser && Gk) {
pixels = Gk ? Gk.fromPixels(input) : null;
} else {
depth = input["data"].length / input["height"] / input["width"];
const arr = new Uint8Array(input["data"]["buffer"]);
pixels = ms(arr, [input["height"], input["width"], depth], "int32");
}
} else {
if (!tmpCanvas || outCanvas.width !== tmpCanvas.width || outCanvas.height !== tmpCanvas.height)
tmpCanvas = canvas(outCanvas.width, outCanvas.height);
if (Gk && env.browser) {
if (config3.backend === "webgl" || config3.backend === "humangl" || config3.backend === "webgpu") {
pixels = Gk.fromPixels(outCanvas);
} else {
tmpCanvas = copy(outCanvas);
pixels = Gk.fromPixels(tmpCanvas);
}
} else {
const tempCanvas = copy(outCanvas);
const tempCtx = tempCanvas.getContext("2d");
const tempData = tempCtx.getImageData(0, 0, targetWidth, targetHeight);
depth = tempData.data.length / targetWidth / targetHeight;
const arr = new Uint8Array(tempData.data.buffer);
pixels = ms(arr, [targetWidth, targetHeight, depth]);
}
}
if (depth === 4) {
const rgb2 = vb(pixels, [0, 0, 0], [-1, -1, 3]);
De(pixels);
pixels = rgb2;
}
if (!pixels)
throw new Error("input error: cannot create tensor");
const casted = le(pixels, "float32");
const tensor = config3.filter.equalization ? await histogramEqualization(casted) : Pn(casted, 0);
De([pixels, casted]);
return { tensor, canvas: config3.filter.return ? outCanvas : null };
}
}
async function skip(config3, input) {
let skipFrame = false;
if (config3.cacheSensitivity === 0 || !input.shape || input.shape.length !== 4 || input.shape[1] > 2048 || input.shape[2] > 2048)
return skipFrame;
if (!last.inputTensor) {
last.inputTensor = lr(input);
} else if (last.inputTensor.shape[1] !== input.shape[1] || last.inputTensor.shape[2] !== input.shape[2]) {
De(last.inputTensor);
last.inputTensor = lr(input);
} else {
const t = {};
t.diff = ge(input, last.inputTensor);
t.squared = V(t.diff, t.diff);
t.sum = ve(t.squared);
const diffSum = await t.sum.data();
const diffRelative = diffSum[0] / (input.shape[1] || 1) / (input.shape[2] || 1) / 255 / 3;
De([last.inputTensor, t.diff, t.squared, t.sum]);
last.inputTensor = lr(input);
skipFrame = diffRelative <= (config3.cacheSensitivity || 0);
}
return skipFrame;
}
async function compare(config3, input1, input2) {
const t = {};
if (!input1 || !input2 || input1.shape.length !== 4 || input1.shape.length !== input2.shape.length) {
if (!config3.debug)
log("invalid input tensor or tensor shapes do not match:", input1.shape, input2.shape);
return 0;
}
if (input1.shape[0] !== 1 || input2.shape[0] !== 1 || input1.shape[3] !== 3 || input2.shape[3] !== 3) {
if (!config3.debug)
log("input tensors must be of shape [1, height, width, 3]:", input1.shape, input2.shape);
return 0;
}
t.input1 = lr(input1);
t.input2 = input1.shape[1] !== input2.shape[1] || input1.shape[2] !== input2.shape[2] ? Kn.resizeBilinear(input2, [input1.shape[1], input1.shape[2]]) : lr(input2);
t.diff = ge(t.input1, t.input2);
t.squared = V(t.diff, t.diff);
t.sum = ve(t.squared);
const diffSum = await t.sum.data();
const diffRelative = diffSum[0] / (input1.shape[1] || 1) / (input1.shape[2] || 1) / 255 / 3;
De([t.input1, t.input2, t.diff, t.squared, t.sum]);
return diffRelative;
}
// src/util/env.ts
var Env = class {
constructor() {
__publicField(this, "browser");
__publicField(this, "node");
__publicField(this, "worker");
__publicField(this, "platform", "");
__publicField(this, "agent", "");
__publicField(this, "backends", []);
__publicField(this, "initial");
__publicField(this, "filter");
__publicField(this, "tfjs");
__publicField(this, "offscreen");
__publicField(this, "perfadd", false);
__publicField(this, "wasm", {
supported: void 0,
backend: void 0,
simd: void 0,
multithread: void 0
});
__publicField(this, "webgl", {
supported: void 0,
backend: void 0,
version: void 0,
renderer: void 0
});
__publicField(this, "webgpu", {
supported: void 0,
backend: void 0,
adapter: void 0
});
__publicField(this, "cpu", {
model: void 0,
flags: []
});
__publicField(this, "kernels", []);
__publicField(this, "Canvas");
__publicField(this, "Image");
__publicField(this, "ImageData");
this.browser = typeof navigator !== "undefined";
this.node = typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined";
this.tfjs = { version: Ghe["tfjs-core"] };
this.offscreen = typeof OffscreenCanvas !== "undefined";
this.initial = true;
this.worker = this.browser && this.offscreen ? typeof WorkerGlobalScope !== "undefined" : void 0;
if (typeof navigator !== "undefined") {
const raw = navigator.userAgent.match(/\(([^()]+)\)/g);
if (raw && raw[0]) {
const platformMatch = raw[0].match(/\(([^()]+)\)/g);
this.platform = platformMatch && platformMatch[0] ? platformMatch[0].replace(/\(|\)/g, "") : "";
this.agent = navigator.userAgent.replace(raw[0], "");
if (this.platform[1])
this.agent = this.agent.replace(raw[1], "");
this.agent = this.agent.replace(/ /g, " ");
}
} else if (typeof process !== "undefined") {
this.platform = `${process.platform} ${process.arch}`;
this.agent = `NodeJS ${process.version}`;
}
}
async updateBackend() {
this.backends = Object.keys(ds().registryFactory);
this.wasm.supported = typeof WebAssembly !== "undefined";
this.wasm.backend = this.backends.includes("wasm");
if (this.wasm.supported && this.wasm.backend && Mpe() === "wasm") {
this.wasm.simd = await K().getAsync("WASM_HAS_SIMD_SUPPORT");
this.wasm.multithread = await K().getAsync("WASM_HAS_MULTITHREAD_SUPPORT");
}
const c = canvas(100, 100);
const ctx = c ? c.getContext("webgl2") : void 0;
this.webgl.supported = typeof ctx !== "undefined";
this.webgl.backend = this.backends.includes("webgl");
if (this.webgl.supported && this.webgl.backend && (Mpe() === "webgl" || Mpe() === "humangl")) {
const gl2 = $A().gpgpu !== "undefined" ? await $A().getGPGPUContext().gl : null;
if (gl2) {
this.webgl.version = gl2.getParameter(gl2.VERSION);
this.webgl.renderer = gl2.getParameter(gl2.RENDERER);
}
}
this.webgpu.supported = this.browser && typeof navigator["gpu"] !== "undefined";
this.webgpu.backend = this.backends.includes("webgpu");
try {
if (this.webgpu.supported)
this.webgpu.adapter = (await navigator["gpu"].requestAdapter()).name;
} catch (e) {
this.webgpu.supported = false;
}
try {
this.kernels = cm(Mpe()).map((kernel) => kernel.kernelName.toLowerCase());
} catch (e) {
}
}
async updateCPU() {
const cpu = { model: "", flags: [] };
if (this.node && this.platform.startsWith("linux")) {
}
if (!this["cpu"])
Object.defineProperty(this, "cpu", { value: cpu });
else
this["cpu"] = cpu;
}
};
var env = new Env();
// src/tfjs/load.ts
var options = {
cacheModels: false,
verbose: true,
debug: false,
modelBasePath: ""
};
async function httpHandler(url, init2) {
if (options.debug)
log("load model fetch:", url, init2);
return fetch(url, init2);
}
function setModelLoadOptions(config3) {
options.cacheModels = config3.cacheModels;
options.verbose = config3.debug;
options.modelBasePath = config3.modelBasePath;
}
async function loadModel(modelPath) {
let modelUrl = join(options.modelBasePath, modelPath || "");
if (!modelUrl.toLowerCase().endsWith(".json"))
modelUrl += ".json";
const modelPathSegments = modelUrl.split("/");
const cachedModelName = "indexeddb://" + modelPathSegments[modelPathSegments.length - 1].replace(".json", "");
const cachedModels = await An.listModels();
const modelCached = options.cacheModels && Object.keys(cachedModels).includes(cachedModelName);
const tfLoadOptions = typeof fetch === "undefined" ? {} : { fetchFunc: (url, init2) => httpHandler(url, init2) };
const model18 = new P0(modelCached ? cachedModelName : modelUrl, tfLoadOptions);
let loaded = false;
try {
model18.findIOHandler();
if (options.debug)
log("model load handler:", model18.handler);
const artifacts = await model18.handler.load();
model18.loadSync(artifacts);
if (options.verbose)
log("load model:", model18["modelUrl"]);
loaded = true;
} catch (err) {
log("error loading model:", modelUrl, err);
}
if (loaded && options.cacheModels && !modelCached) {
try {
const saveResult = await model18.save(cachedModelName);
log("model saved:", cachedModelName, saveResult);
} catch (err) {
log("error saving model:", modelUrl, err);
}
}
return model18;
}
// package.json
var version = "2.8.0";
// src/models.ts
var models_exports = {};
__export(models_exports, {
Models: () => Models,
load: () => load19,
reset: () => reset,
validate: () => validate2
});
// src/gear/gear.ts
var model;
var last2 = [];
var raceNames = ["white", "black", "asian", "indian", "other"];
var ageWeights = [15, 23, 28, 35.5, 45.5, 55.5, 65];
var lastCount = 0;
var lastTime = 0;
var skipped = Number.MAX_SAFE_INTEGER;
async function load(config3) {
if (env.initial)
model = null;
if (!model)
model = await loadModel(config3.face["gear"]);
else if (config3.debug)
log("cached model:", model["modelUrl"]);
return model;
}
async function predict(image, config3, idx, count2) {
var _a2, _b2;
if (!model)
return { age: 0, gender: "unknown", genderScore: 0, race: [] };
const skipFrame = skipped < (((_a2 = config3.face["gear"]) == null ? void 0 : _a2.skipFrames) || 0);
const skipTime = (((_b2 = config3.face["gear"]) == null ? void 0 : _b2.skipTime) || 0) > now() - lastTime;
if (config3.skipAllowed && skipTime && skipFrame && lastCount === count2 && last2[idx]) {
skipped++;
return last2[idx];
}
skipped = 0;
return new Promise(async (resolve) => {
var _a3, _b3;
if (!(model == null ? void 0 : model.inputs[0].shape))
return;
const t = {};
const box = [[0, 0.1, 0.9, 0.9]];
t.resize = Kn.cropAndResize(image, box, [0], [model.inputs[0].shape[2], model.inputs[0].shape[1]]);
const obj = { age: 0, gender: "unknown", genderScore: 0, race: [] };
if ((_a3 = config3.face["gear"]) == null ? void 0 : _a3.enabled)
[t.age, t.gender, t.race] = model.execute(t.resize, ["age_output", "gender_output", "race_output"]);
const gender = await t.gender.data();
obj.gender = gender[0] > gender[1] ? "male" : "female";
obj.genderScore = Math.round(100 * (gender[0] > gender[1] ? gender[0] : gender[1])) / 100;
const race = await t.race.data();
for (let i = 0; i < race.length; i++) {
if (race[i] > (((_b3 = config3.face["gear"]) == null ? void 0 : _b3.minConfidence) || 0.2))
obj.race.push({ score: Math.round(100 * race[i]) / 100, race: raceNames[i] });
}
obj.race.sort((a, b) => b.score - a.score);
const ageDistribution = Array.from(await t.age.data());
const ageSorted = ageDistribution.map((a, i) => [ageWeights[i], a]).sort((a, b) => b[1] - a[1]);
let age = ageSorted[0][0];
for (let i = 1; i < ageSorted.length; i++)
age += ageSorted[i][1] * (ageSorted[i][0] - age);
obj.age = Math.round(10 * age) / 10;
Object.keys(t).forEach((tensor) => De(t[tensor]));
last2[idx] = obj;
lastCount = count2;
lastTime = now();
resolve(obj);
});
}
// src/tfjs/constants.ts
var constants = {
tf255: 255,
tf1: 1,
tf2: 2,
tf05: 0.5,
tf127: 127.5,
rgb: [0.2989, 0.587, 0.114]
};
function init() {
constants.tf255 = we(255, "float32");
constants.tf1 = we(1, "float32");
constants.tf2 = we(2, "float32");
constants.tf05 = we(0.5, "float32");
constants.tf127 = we(127.5, "float32");
constants.rgb = Zt([0.2989, 0.587, 0.114], "float32");
}
// src/gear/ssrnet-age.ts
var model2;
var last3 = [];
var lastCount2 = 0;
var lastTime2 = 0;
var skipped2 = Number.MAX_SAFE_INTEGER;
async function load2(config3) {
if (env.initial)
model2 = null;
if (!model2)
model2 = await loadModel(config3.face["ssrnet"].modelPathAge);
else if (config3.debug)
log("cached model:", model2["modelUrl"]);
return model2;
}
async function predict2(image, config3, idx, count2) {
var _a2, _b2, _c, _d2;
if (!model2)
return { age: 0 };
const skipFrame = skipped2 < (((_a2 = config3.face["ssrnet"]) == null ? void 0 : _a2.skipFrames) || 0);
const skipTime = (((_b2 = config3.face["ssrnet"]) == null ? void 0 : _b2.skipTime) || 0) > now() - lastTime2;
if (config3.skipAllowed && skipFrame && skipTime && lastCount2 === count2 && ((_c = last3[idx]) == null ? void 0 : _c.age) && ((_d2 = last3[idx]) == null ? void 0 : _d2.age) > 0) {
skipped2++;
return last3[idx];
}
skipped2 = 0;
return new Promise(async (resolve) => {
if (!(model2 == null ? void 0 : model2.inputs) || !model2.inputs[0] || !model2.inputs[0].shape)
return;
const t = {};
t.resize = Kn.resizeBilinear(image, [model2.inputs[0].shape[2], model2.inputs[0].shape[1]], false);
t.enhance = V(t.resize, constants.tf255);
const obj = { age: 0 };
if (config3.face["ssrnet"].enabled)
t.age = model2.execute(t.enhance);
if (t.age) {
const data = await t.age.data();
obj.age = Math.trunc(10 * data[0]) / 10;
}
Object.keys(t).forEach((tensor) => De(t[tensor]));
last3[idx] = obj;
lastCount2 = count2;
lastTime2 = now();
resolve(obj);
});
}
// src/gear/ssrnet-gender.ts
var model3;
var last4 = [];
var lastCount3 = 0;
var lastTime3 = 0;
var skipped3 = Number.MAX_SAFE_INTEGER;
var rgb = [0.2989, 0.587, 0.114];
async function load3(config3) {
if (env.initial)
model3 = null;
if (!model3)
model3 = await loadModel(config3.face["ssrnet"].modelPathGender);
else if (config3.debug)
log("cached model:", model3["modelUrl"]);
return model3;
}
async function predict3(image, config3, idx, count2) {
var _a2, _b2, _c, _d2;
if (!model3)
return { gender: "unknown", genderScore: 0 };
const skipFrame = skipped3 < (((_a2 = config3.face["ssrnet"]) == null ? void 0 : _a2.skipFrames) || 0);
const skipTime = (((_b2 = config3.face["ssrnet"]) == null ? void 0 : _b2.skipTime) || 0) > now() - lastTime3;
if (config3.skipAllowed && skipFrame && skipTime && lastCount3 === count2 && ((_c = last4[idx]) == null ? void 0 : _c.gender) && ((_d2 = last4[idx]) == null ? void 0 : _d2.genderScore) > 0) {
skipped3++;
return last4[idx];
}
skipped3 = 0;
return new Promise(async (resolve) => {
if (!(model3 == null ? void 0 : model3.inputs[0].shape))
return;
const t = {};
t.resize = Kn.resizeBilinear(image, [model3.inputs[0].shape[2], model3.inputs[0].shape[1]], false);
t.enhance = q(() => {
const [red, green, blue] = Bn(t.resize, 3, 3);
const redNorm = V(red, rgb[0]);
const greenNorm = V(green, rgb[1]);
const blueNorm = V(blue, rgb[2]);
const grayscale = gE([redNorm, greenNorm, blueNorm]);
const normalize = V(ge(grayscale, constants.tf05), 2);
return normalize;
});
const obj = { gender: "unknown", genderScore: 0 };
if (config3.face["ssrnet"].enabled)
t.gender = model3.execute(t.enhance);
const data = await t.gender.data();
obj.gender = data[0] > data[1] ? "female" : "male";
obj.genderScore = data[0] > data[1] ? Math.trunc(100 * data[0]) / 100 : Math.trunc(100 * data[1]) / 100;
Object.keys(t).forEach((tensor) => De(t[tensor]));
last4[idx] = obj;
lastCount3 = count2;
lastTime3 = now();
resolve(obj);
});
}
// src/face/antispoof.ts
var model4;
var cached = [];
var skipped4 = Number.MAX_SAFE_INTEGER;
var lastCount4 = 0;
var lastTime4 = 0;
async function load4(config3) {
var _a2;
if (env.initial)
model4 = null;
if (!model4)
model4 = await loadModel((_a2 = config3.face.antispoof) == null ? void 0 : _a2.modelPath);
else if (config3.debug)
log("cached model:", model4["modelUrl"]);
return model4;
}
async function predict4(image, config3, idx, count2) {
var _a2, _b2;
if (!model4)
return 0;
const skipTime = (((_a2 = config3.face.antispoof) == null ? void 0 : _a2.skipTime) || 0) > now() - lastTime4;
const skipFrame = skipped4 < (((_b2 = config3.face.antispoof) == null ? void 0 : _b2.skipFrames) || 0);
if (config3.skipAllowed && skipTime && skipFrame && lastCount4 === count2 && cached[idx]) {
skipped4++;
return cached[idx];
}
skipped4 = 0;
return new Promise(async (resolve) => {
const resize = Kn.resizeBilinear(image, [(model4 == null ? void 0 : model4.inputs[0].shape) ? model4.inputs[0].shape[2] : 0, (model4 == null ? void 0 : model4.inputs[0].shape) ? model4.inputs[0].shape[1] : 0], false);
const res = model4 == null ? void 0 : model4.execute(resize);
const num = (await res.data())[0];
cached[idx] = Math.round(100 * num) / 100;
lastCount4 = count2;
lastTime4 = now();
De([resize, res]);
resolve(cached[idx]);
});
}
// src/face/facemeshcoords.ts
var meshAnnotations = {
silhouette: [
10,
338,
297,
332,
284,
251,
389,
356,
454,
323,
361,
288,
397,
365,
379,
378,
400,
377,
152,
148,
176,
149,
150,
136,
172,
58,
132,
93,
234,
127,
162,
21,
54,
103,
67,
109
],
lipsUpperOuter: [185, 40, 39, 37, 0, 267, 269, 270, 409],
lipsLowerOuter: [61, 146, 91, 181, 84, 17, 314, 405, 321, 375, 291],
lipsUpperInner: [191, 80, 81, 82, 13, 312, 311, 310, 415],
lipsLowerInner: [78, 95, 88, 178, 87, 14, 317, 402, 318, 324, 308],
lipsLowerSemiOuter: [76, 77, 90, 180, 85, 16, 315, 404, 320, 307, 306],
lipsUpperSemiOuter: [184, 74, 73, 72, 11, 302, 303, 304, 408],
lipsLowerSemiInner: [62, 96, 89, 179, 86, 15, 316, 403, 319, 325, 292],
lipsUpperSemiInner: [183, 42, 41, 38, 12, 268, 271, 272, 407],
rightEyeUpper0: [246, 161, 160, 159, 158, 157, 173],
rightEyeLower0: [33, 7, 163, 144, 145, 153, 154, 155, 133],
rightEyeUpper1: [247, 30, 29, 27, 28, 56, 190],
rightEyeLower1: [130, 25, 110, 24, 23, 22, 26, 112, 243],
rightEyeUpper2: [113, 225, 224, 223, 222, 221, 189],
rightEyeLower2: [226, 31, 228, 229, 230, 231, 232, 233, 244],
rightEyeLower3: [143, 111, 117, 118, 119, 120, 121, 128, 245],
rightEyebrowUpper: [156, 70, 63, 105, 66, 107, 55, 193],
rightEyebrowLower: [35, 124, 46, 53, 52, 65],
rightEyeIris: [473, 474, 475, 476, 477],
leftEyeUpper0: [466, 388, 387, 386, 385, 384, 398],
leftEyeLower0: [263, 249, 390, 373, 374, 380, 381, 382, 362],
leftEyeUpper1: [467, 260, 259, 257, 258, 286, 414],
leftEyeLower1: [359, 255, 339, 254, 253, 252, 256, 341, 463],
leftEyeUpper2: [342, 445, 444, 443, 442, 441, 413],
leftEyeLower2: [446, 261, 448, 449, 450, 451, 452, 453, 464],
leftEyeLower3: [372, 340, 346, 347, 348, 349, 350, 357, 465],
leftEyebrowUpper: [383, 300, 293, 334, 296, 336, 285, 417],
leftEyebrowLower: [265, 353, 276, 283, 282, 295],
leftEyeIris: [468, 469, 470, 471, 472],
midwayBetweenEyes: [168],
noseTip: [1],
noseBottom: [2],
noseRightCorner: [98],
noseLeftCorner: [327],
rightCheek: [205],
leftCheek: [425]
};
var meshLandmarks = {
count: 468,
mouth: 13,
symmetryLine: [13, meshAnnotations["midwayBetweenEyes"][0]]
};
var blazeFaceLandmarks = {
leftEye: 0,
rightEye: 1,
nose: 2,
mouth: 3,
leftEar: 4,
rightEar: 5,
symmetryLine: [3, 2]
};
var irisIndices = [
{ key: "EyeUpper0", indices: [9, 10, 11, 12, 13, 14, 15] },
{ key: "EyeUpper1", indices: [25, 26, 27, 28, 29, 30, 31] },
{ key: "EyeUpper2", indices: [41, 42, 43, 44, 45, 46, 47] },
{ key: "EyeLower0", indices: [0, 1, 2, 3, 4, 5, 6, 7, 8] },
{ key: "EyeLower1", indices: [16, 17, 18, 19, 20, 21, 22, 23, 24] },
{ key: "EyeLower2", indices: [32, 33, 34, 35, 36, 37, 38, 39, 40] },
{ key: "EyeLower3", indices: [54, 55, 56, 57, 58, 59, 60, 61, 62] },
{ key: "EyebrowUpper", indices: [63, 64, 65, 66, 67, 68, 69, 70] },
{ key: "EyebrowLower", indices: [48, 49, 50, 51, 52, 53] }
];
var UV468 = [
[0.499976992607117, 0.652534008026123],
[0.500025987625122, 0.547487020492554],
[0.499974012374878, 0.602371990680695],
[0.482113003730774, 0.471979022026062],
[0.500150978565216, 0.527155995368958],
[0.499909996986389, 0.498252987861633],
[0.499523013830185, 0.40106201171875],
[0.289712011814117, 0.380764007568359],
[0.499954998493195, 0.312398016452789],
[0.499987006187439, 0.269918978214264],
[0.500023007392883, 0.107050001621246],
[0.500023007392883, 0.666234016418457],
[0.5000159740448, 0.679224014282227],
[0.500023007392883, 0.692348003387451],
[0.499976992607117, 0.695277988910675],
[0.499976992607117, 0.70593398809433],
[0.499976992607117, 0.719385027885437],
[0.499976992607117, 0.737019002437592],
[0.499967992305756, 0.781370997428894],
[0.499816000461578, 0.562981009483337],
[0.473773002624512, 0.573909997940063],
[0.104906998574734, 0.254140973091125],
[0.365929991006851, 0.409575998783112],
[0.338757991790771, 0.41302502155304],
[0.311120003461838, 0.409460008144379],
[0.274657994508743, 0.389131009578705],
[0.393361985683441, 0.403706014156342],
[0.345234006643295, 0.344011008739471],
[0.370094001293182, 0.346076011657715],
[0.319321990013123, 0.347265005111694],
[0.297903001308441, 0.353591024875641],
[0.24779200553894, 0.410809993743896],
[0.396889001131058, 0.842755019664764],
[0.280097991228104, 0.375599980354309],
[0.106310002505779, 0.399955987930298],
[0.2099249958992, 0.391353011131287],
[0.355807989835739, 0.534406006336212],
[0.471751004457474, 0.65040397644043],
[0.474155008792877, 0.680191993713379],
[0.439785003662109, 0.657229006290436],
[0.414617002010345, 0.66654098033905],
[0.450374007225037, 0.680860996246338],
[0.428770989179611, 0.682690978050232],
[0.374971002340317, 0.727805018424988],
[0.486716985702515, 0.547628998756409],
[0.485300987958908, 0.527395009994507],
[0.257764995098114, 0.314490020275116],
[0.401223003864288, 0.455172002315521],
[0.429818987846375, 0.548614978790283],
[0.421351999044418, 0.533740997314453],
[0.276895999908447, 0.532056987285614],
[0.483370006084442, 0.499586999416351],
[0.33721199631691, 0.282882988452911],
[0.296391993761063, 0.293242990970612],
[0.169294998049736, 0.193813979625702],
[0.447580009698868, 0.302609980106354],
[0.392390012741089, 0.353887975215912],
[0.354490011930466, 0.696784019470215],
[0.067304998636246, 0.730105042457581],
[0.442739009857178, 0.572826027870178],
[0.457098007202148, 0.584792017936707],
[0.381974011659622, 0.694710969924927],
[0.392388999462128, 0.694203019142151],
[0.277076005935669, 0.271932005882263],
[0.422551989555359, 0.563233017921448],
[0.385919004678726, 0.281364023685455],
[0.383103013038635, 0.255840003490448],
[0.331431001424789, 0.119714021682739],
[0.229923993349075, 0.232002973556519],
[0.364500999450684, 0.189113974571228],
[0.229622006416321, 0.299540996551514],
[0.173287004232407, 0.278747975826263],
[0.472878992557526, 0.666198015213013],
[0.446828007698059, 0.668527007102966],
[0.422762006521225, 0.673889994621277],
[0.445307999849319, 0.580065965652466],
[0.388103008270264, 0.693961024284363],
[0.403039008378983, 0.706539988517761],
[0.403629004955292, 0.693953037261963],
[0.460041999816895, 0.557139039039612],
[0.431158006191254, 0.692366003990173],
[0.452181994915009, 0.692366003990173],
[0.475387006998062, 0.692366003990173],
[0.465828001499176, 0.779190003871918],
[0.472328990697861, 0.736225962638855],
[0.473087012767792, 0.717857003211975],
[0.473122000694275, 0.704625964164734],
[0.473033010959625, 0.695277988910675],
[0.427942007780075, 0.695277988910675],
[0.426479011774063, 0.703539967536926],
[0.423162013292313, 0.711845993995667],
[0.4183090031147, 0.720062971115112],
[0.390094995498657, 0.639572978019714],
[0.013953999616206, 0.560034036636353],
[0.499913990497589, 0.58014702796936],
[0.413199990987778, 0.69539999961853],
[0.409626007080078, 0.701822996139526],
[0.468080013990402, 0.601534962654114],
[0.422728985548019, 0.585985004901886],
[0.463079988956451, 0.593783974647522],
[0.37211999297142, 0.47341400384903],
[0.334562003612518, 0.496073007583618],
[0.411671012639999, 0.546965003013611],
[0.242175996303558, 0.14767599105835],
[0.290776997804642, 0.201445996761322],
[0.327338010072708, 0.256527006626129],
[0.399509996175766, 0.748921036720276],
[0.441727995872498, 0.261676013469696],
[0.429764986038208, 0.187834024429321],
[0.412198007106781, 0.108901023864746],
[0.288955003023148, 0.398952007293701],
[0.218936994671822, 0.435410976409912],
[0.41278201341629, 0.398970007896423],
[0.257135003805161, 0.355440020561218],
[0.427684992551804, 0.437960982322693],
[0.448339998722076, 0.536936044692993],
[0.178560003638268, 0.45755398273468],
[0.247308000922203, 0.457193970680237],
[0.286267012357712, 0.467674970626831],
[0.332827985286713, 0.460712015628815],
[0.368755996227264, 0.447206974029541],
[0.398963987827301, 0.432654976844788],
[0.476410001516342, 0.405806005001068],
[0.189241006970406, 0.523923993110657],
[0.228962004184723, 0.348950982093811],
[0.490725994110107, 0.562400996685028],
[0.404670000076294, 0.485132992267609],
[0.019469000399113, 0.401564002037048],
[0.426243007183075, 0.420431017875671],
[0.396993011236191, 0.548797011375427],
[0.266469985246658, 0.376977026462555],
[0.439121007919312, 0.51895797252655],
[0.032313998788595, 0.644356966018677],
[0.419054001569748, 0.387154996395111],
[0.462783008813858, 0.505746960639954],
[0.238978996872902, 0.779744982719421],
[0.198220998048782, 0.831938028335571],
[0.107550002634525, 0.540755033493042],
[0.183610007166862, 0.740257024765015],
[0.134409993886948, 0.333683013916016],
[0.385764002799988, 0.883153975009918],
[0.490967005491257, 0.579378008842468],
[0.382384985685349, 0.508572995662689],
[0.174399003386497, 0.397670984268188],
[0.318785011768341, 0.39623498916626],
[0.343364000320435, 0.400596976280212],
[0.396100014448166, 0.710216999053955],
[0.187885001301765, 0.588537991046906],
[0.430987000465393, 0.944064974784851],
[0.318993002176285, 0.898285031318665],
[0.266247987747192, 0.869701027870178],
[0.500023007392883, 0.190576016902924],
[0.499976992607117, 0.954452991485596],
[0.366169989109039, 0.398822009563446],
[0.393207013607025, 0.39553701877594],
[0.410373002290726, 0.391080021858215],
[0.194993004202843, 0.342101991176605],
[0.388664990663528, 0.362284004688263],
[0.365961998701096, 0.355970978736877],
[0.343364000320435, 0.355356991291046],
[0.318785011768341, 0.35834002494812],
[0.301414996385574, 0.363156020641327],
[0.058132998645306, 0.319076001644135],
[0.301414996385574, 0.387449026107788],
[0.499987989664078, 0.618434011936188],
[0.415838003158569, 0.624195992946625],
[0.445681989192963, 0.566076993942261],
[0.465844005346298, 0.620640993118286],
[0.49992299079895, 0.351523995399475],
[0.288718998432159, 0.819945991039276],
[0.335278987884521, 0.852819979190826],
[0.440512001514435, 0.902418971061707],
[0.128294005990028, 0.791940987110138],
[0.408771991729736, 0.373893976211548],
[0.455606997013092, 0.451801002025604],
[0.499877005815506, 0.908990025520325],
[0.375436991453171, 0.924192011356354],
[0.11421000212431, 0.615022003650665],
[0.448662012815475, 0.695277988910675],
[0.4480200111866, 0.704632043838501],
[0.447111994028091, 0.715808033943176],
[0.444831997156143, 0.730794012546539],
[0.430011987686157, 0.766808986663818],
[0.406787008047104, 0.685672998428345],
[0.400738000869751, 0.681069016456604],
[0.392399996519089, 0.677703022956848],
[0.367855995893478, 0.663918972015381],
[0.247923001646996, 0.601333022117615],
[0.452769994735718, 0.420849978923798],
[0.43639200925827, 0.359887003898621],
[0.416164010763168, 0.368713974952698],
[0.413385987281799, 0.692366003990173],
[0.228018000721931, 0.683571994304657],
[0.468268007040024, 0.352671027183533],
[0.411361992359161, 0.804327011108398],
[0.499989002943039, 0.469825029373169],
[0.479153990745544, 0.442654013633728],
[0.499974012374878, 0.439637005329132],
[0.432112008333206, 0.493588984012604],
[0.499886006116867, 0.866917014122009],
[0.49991300702095, 0.821729004383087],
[0.456548988819122, 0.819200992584229],
[0.344549000263214, 0.745438992977142],
[0.37890899181366, 0.574010014533997],
[0.374292999505997, 0.780184984207153],
[0.319687992334366, 0.570737957954407],
[0.357154995203018, 0.604269981384277],
[0.295284003019333, 0.621580958366394],
[0.447750002145767, 0.862477004528046],
[0.410986006259918, 0.508723020553589],
[0.31395098567009, 0.775308012962341],
[0.354128003120422, 0.812552988529205],
[0.324548006057739, 0.703992962837219],
[0.189096003770828, 0.646299958229065],
[0.279776990413666, 0.71465802192688],
[0.1338230073452, 0.682700991630554],
[0.336768001317978, 0.644733011722565],
[0.429883986711502, 0.466521978378296],
[0.455527991056442, 0.548622965812683],
[0.437114000320435, 0.558896005153656],
[0.467287987470627, 0.529924988746643],
[0.414712011814117, 0.335219979286194],
[0.37704598903656, 0.322777986526489],
[0.344107985496521, 0.320150971412659],
[0.312875986099243, 0.32233202457428],
[0.283526003360748, 0.333190023899078],
[0.241245999932289, 0.382785975933075],
[0.102986000478268, 0.468762993812561],
[0.267612010240555, 0.424560010433197],
[0.297879010438919, 0.433175981044769],
[0.333433985710144, 0.433878004550934],
[0.366427004337311, 0.426115989685059],
[0.396012008190155, 0.416696012020111],
[0.420121014118195, 0.41022801399231],
[0.007561000064015, 0.480777025222778],
[0.432949006557465, 0.569517970085144],
[0.458638995885849, 0.479089021682739],
[0.473466008901596, 0.545744001865387],
[0.476087987422943, 0.563830018043518],
[0.468472003936768, 0.555056989192963],
[0.433990985155106, 0.582361996173859],
[0.483518004417419, 0.562983989715576],
[0.482482999563217, 0.57784903049469],
[0.42645001411438, 0.389798998832703],
[0.438998997211456, 0.39649498462677],
[0.450067013502121, 0.400434017181396],
[0.289712011814117, 0.368252992630005],
[0.276670008897781, 0.363372981548309],
[0.517862021923065, 0.471948027610779],
[0.710287988185883, 0.380764007568359],
[0.526226997375488, 0.573909997940063],
[0.895093023777008, 0.254140973091125],
[0.634069979190826, 0.409575998783112],
[0.661242008209229, 0.41302502155304],
[0.688880026340485, 0.409460008144379],
[0.725341975688934, 0.389131009578705],
[0.606630027294159, 0.40370500087738],
[0.654766023159027, 0.344011008739471],
[0.629905998706818, 0.346076011657715],
[0.680678009986877, 0.347265005111694],
[0.702096998691559, 0.353591024875641],
[0.75221198797226, 0.410804986953735],
[0.602918028831482, 0.842862963676453],
[0.719901978969574, 0.375599980354309],
[0.893692970275879, 0.399959981441498],
[0.790081977844238, 0.391354024410248],
[0.643998026847839, 0.534487962722778],
[0.528249025344849, 0.65040397644043],
[0.525849997997284, 0.680191040039062],
[0.560214996337891, 0.657229006290436],
[0.585384011268616, 0.66654098033905],
[0.549625992774963, 0.680860996246338],
[0.57122802734375, 0.682691991329193],
[0.624852001667023, 0.72809898853302],
[0.513050019741058, 0.547281980514526],
[0.51509702205658, 0.527251958847046],
[0.742246985435486, 0.314507007598877],
[0.598631024360657, 0.454979002475739],
[0.570338010787964, 0.548575043678284],
[0.578631997108459, 0.533622980117798],
[0.723087012767792, 0.532054007053375],
[0.516445994377136, 0.499638974666595],
[0.662801027297974, 0.282917976379395],
[0.70362401008606, 0.293271005153656],
[0.830704987049103, 0.193813979625702],
[0.552385985851288, 0.302568018436432],
[0.607609987258911, 0.353887975215912],
[0.645429015159607, 0.696707010269165],
[0.932694971561432, 0.730105042457581],
[0.557260990142822, 0.572826027870178],
[0.542901992797852, 0.584792017936707],
[0.6180260181427, 0.694710969924927],
[0.607590973377228, 0.694203019142151],
[0.722943007946014, 0.271963000297546],
[0.577413976192474, 0.563166975975037],
[0.614082992076874, 0.281386971473694],
[0.616907000541687, 0.255886018276215],
[0.668509006500244, 0.119913995265961],
[0.770092010498047, 0.232020974159241],
[0.635536015033722, 0.189248979091644],
[0.77039098739624, 0.299556016921997],
[0.826722025871277, 0.278755009174347],
[0.527121007442474, 0.666198015213013],
[0.553171992301941, 0.668527007102966],
[0.577238023281097, 0.673889994621277],
[0.554691970348358, 0.580065965652466],
[0.611896991729736, 0.693961024284363],
[0.59696102142334, 0.706539988517761],
[0.596370995044708, 0.693953037261963],
[0.539958000183105, 0.557139039039612],
[0.568841993808746, 0.692366003990173],
[0.547818005084991, 0.692366003990173],
[0.52461302280426, 0.692366003990173],
[0.534089982509613, 0.779141008853912],
[0.527670979499817, 0.736225962638855],
[0.526912987232208, 0.717857003211975],
[0.526877999305725, 0.704625964164734],
[0.526966989040375, 0.695277988910675],
[0.572058022022247, 0.695277988910675],
[0.573521018028259, 0.703539967536926],
[0.57683801651001, 0.711845993995667],
[0.581691026687622, 0.720062971115112],
[0.609944999217987, 0.639909982681274],
[0.986046016216278, 0.560034036636353],
[0.5867999792099, 0.69539999961853],
[0.590372025966644, 0.701822996139526],
[0.531915009021759, 0.601536989212036],
[0.577268004417419, 0.585934996604919],
[0.536915004253387, 0.593786001205444],
[0.627542972564697, 0.473352015018463],
[0.665585994720459, 0.495950996875763],
[0.588353991508484, 0.546862006187439],
[0.757824003696442, 0.14767599105835],
[0.709249973297119, 0.201507985591888],
[0.672684013843536, 0.256581008434296],
[0.600408971309662, 0.74900496006012],
[0.55826598405838, 0.261672019958496],
[0.570303976535797, 0.187870979309082],
[0.588165998458862, 0.109044015407562],
[0.711045026779175, 0.398952007293701],
[0.781069993972778, 0.435405015945435],
[0.587247014045715, 0.398931980133057],
[0.742869973182678, 0.355445981025696],
[0.572156012058258, 0.437651991844177],
[0.55186802148819, 0.536570012569427],
[0.821442008018494, 0.457556009292603],
[0.752701997756958, 0.457181990146637],
[0.71375697851181, 0.467626988887787],
[0.66711300611496, 0.460672974586487],
[0.631101012229919, 0.447153985500336],
[0.6008620262146, 0.432473003864288],
[0.523481011390686, 0.405627012252808],
[0.810747981071472, 0.523926019668579],
[0.771045982837677, 0.348959028720856],
[0.509127020835876, 0.562718033790588],
[0.595292985439301, 0.485023975372314],
[0.980530977249146, 0.401564002037048],
[0.573499977588654, 0.420000016689301],
[0.602994978427887, 0.548687994480133],
[0.733529984951019, 0.376977026462555],
[0.560611009597778, 0.519016981124878],
[0.967685997486115, 0.644356966018677],
[0.580985009670258, 0.387160003185272],
[0.537728011608124, 0.505385041236877],
[0.760966002941132, 0.779752969741821],
[0.801778972148895, 0.831938028335571],
[0.892440974712372, 0.54076099395752],
[0.816350996494293, 0.740260004997253],
[0.865594983100891, 0.333687007427216],
[0.614073991775513, 0.883246004581451],
[0.508952975273132, 0.579437971115112],
[0.617941975593567, 0.508316040039062],
[0.825608015060425, 0.397674977779388],
[0.681214988231659, 0.39623498916626],
[0.656635999679565, 0.400596976280212],
[0.603900015354156, 0.710216999053955],
[0.81208598613739, 0.588539004325867],
[0.56801301240921, 0.944564998149872],
[0.681007981300354, 0.898285031318665],
[0.733752012252808, 0.869701027870178],
[0.633830010890961, 0.398822009563446],
[0.606792986392975, 0.39553701877594],
[0.589659988880157, 0.391062021255493],
[0.805015981197357, 0.342108011245728],
[0.611334979534149, 0.362284004688263],
[0.634037971496582, 0.355970978736877],
[0.656635999679565, 0.355356991291046],
[0.681214988231659, 0.35834002494812],
[0.698584973812103, 0.363156020641327],
[0.941866993904114, 0.319076001644135],
[0.698584973812103, 0.387449026107788],
[0.584177017211914, 0.624107003211975],
[0.554318010807037, 0.566076993942261],
[0.534153997898102, 0.62064003944397],
[0.711217999458313, 0.819975018501282],
[0.664629995822906, 0.852871000766754],
[0.559099972248077, 0.902631998062134],
[0.871706008911133, 0.791940987110138],
[0.591234028339386, 0.373893976211548],
[0.544341027736664, 0.451583981513977],
[0.624562978744507, 0.924192011356354],
[0.88577002286911, 0.615028977394104],
[0.551338016986847, 0.695277988910675],
[0.551980018615723, 0.704632043838501],
[0.552887976169586, 0.715808033943176],
[0.555167973041534, 0.730794012546539],
[0.569944024085999, 0.767035007476807],
[0.593203008174896, 0.685675978660583],
[0.599261999130249, 0.681069016456604],
[0.607599973678589, 0.677703022956848],
[0.631937980651855, 0.663500010967255],
[0.752032995223999, 0.601315021514893],
[0.547226011753082, 0.420395016670227],
[0.563543975353241, 0.359827995300293],
[0.583841025829315, 0.368713974952698],
[0.586614012718201, 0.692366003990173],
[0.771915018558502, 0.683578014373779],
[0.531597018241882, 0.352482974529266],
[0.588370978832245, 0.804440975189209],
[0.52079701423645, 0.442565023899078],
[0.567984998226166, 0.493479013442993],
[0.543282985687256, 0.819254994392395],
[0.655317008495331, 0.745514988899231],
[0.621008992195129, 0.574018001556396],
[0.625559985637665, 0.78031200170517],
[0.680198013782501, 0.570719003677368],
[0.64276397228241, 0.604337990283966],
[0.704662978649139, 0.621529996395111],
[0.552012026309967, 0.862591981887817],
[0.589071989059448, 0.508637011051178],
[0.685944974422455, 0.775357007980347],
[0.645735025405884, 0.812640011310577],
[0.675342977046967, 0.703978002071381],
[0.810858011245728, 0.646304965019226],
[0.72012197971344, 0.714666962623596],
[0.866151988506317, 0.682704985141754],
[0.663187026977539, 0.644596993923187],
[0.570082008838654, 0.466325998306274],
[0.544561982154846, 0.548375964164734],
[0.562758982181549, 0.558784961700439],
[0.531987011432648, 0.530140042304993],
[0.585271000862122, 0.335177004337311],
[0.622952997684479, 0.32277899980545],
[0.655896008014679, 0.320163011550903],
[0.687132000923157, 0.322345972061157],
[0.716481983661652, 0.333200991153717],
[0.758756995201111, 0.382786989212036],
[0.897013008594513, 0.468769013881683],
[0.732392013072968, 0.424547016620636],
[0.70211398601532, 0.433162987232208],
[0.66652500629425, 0.433866024017334],
[0.633504986763, 0.426087975502014],
[0.603875994682312, 0.416586995124817],
[0.579657971858978, 0.409945011138916],
[0.992439985275269, 0.480777025222778],
[0.567192018032074, 0.569419980049133],
[0.54136598110199, 0.478899002075195],
[0.526564002037048, 0.546118021011353],
[0.523913025856018, 0.563830018043518],
[0.531529009342194, 0.555056989192963],
[0.566035985946655, 0.582329034805298],
[0.51631098985672, 0.563053965568542],
[0.5174720287323, 0.577877044677734],
[0.573594987392426, 0.389806985855103],
[0.560697972774506, 0.395331978797913],
[0.549755990505219, 0.399751007556915],
[0.710287988185883, 0.368252992630005],
[0.723330020904541, 0.363372981548309]
];
var TRI468 = [
127,
34,
139,
11,
0,
37,
232,
231,
120,
72,
37,
39,
128,
121,
47,
232,
121,
128,
104,
69,
67,
175,
171,
148,
157,
154,
155,
118,
50,
101,
73,
39,
40,
9,
151,
108,
48,
115,
131,
194,
204,
211,
74,
40,
185,
80,
42,
183,
40,
92,
186,
230,
229,
118,
202,
212,
214,
83,
18,
17,
76,
61,
146,
160,
29,
30,
56,
157,
173,
106,
204,
194,
135,
214,
192,
203,
165,
98,
21,
71,
68,
51,
45,
4,
144,
24,
23,
77,
146,
91,
205,
50,
187,
201,
200,
18,
91,
106,
182,
90,
91,
181,
85,
84,
17,
206,
203,
36,
148,
171,
140,
92,
40,
39,
193,
189,
244,
159,
158,
28,
247,
246,
161,
236,
3,
196,
54,
68,
104,
193,
168,
8,
117,
228,
31,
189,
193,
55,
98,
97,
99,
126,
47,
100,
166,
79,
218,
155,
154,
26,
209,
49,
131,
135,
136,
150,
47,
126,
217,
223,
52,
53,
45,
51,
134,
211,
170,
140,
67,
69,
108,
43,
106,
91,
230,
119,
120,
226,
130,
247,
63,
53,
52,
238,
20,
242,
46,
70,
156,
78,
62,
96,
46,
53,
63,
143,
34,
227,
173,
155,
133,
123,
117,
111,
44,
125,
19,
236,
134,
51,
216,
206,
205,
154,
153,
22,
39,
37,
167,
200,
201,
208,
36,
142,
100,
57,
212,
202,
20,
60,
99,
28,
158,
157,
35,
226,
113,
160,
159,
27,
204,
202,
210,
113,
225,
46,
43,
202,
204,
62,
76,
77,
137,
123,
116,
41,
38,
72,
203,
129,
142,
64,
98,
240,
49,
102,
64,
41,
73,
74,
212,
216,
207,
42,
74,
184,
169,
170,
211,
170,
149,
176,
105,
66,
69,
122,
6,
168,
123,
147,
187,
96,
77,
90,
65,
55,
107,
89,
90,
180,
101,
100,
120,
63,
105,
104,
93,
137,
227,
15,
86,
85,
129,
102,
49,
14,
87,
86,
55,
8,
9,
100,
47,
121,
145,
23,
22,
88,
89,
179,
6,
122,
196,
88,
95,
96,
138,
172,
136,
215,
58,
172,
115,
48,
219,
42,
80,
81,
195,
3,
51,
43,
146,
61,
171,
175,
199,
81,
82,
38,
53,
46,
225,
144,
163,
110,
246,
33,
7,
52,
65,
66,
229,
228,
117,
34,
127,
234,
107,
108,
69,
109,
108,
151,
48,
64,
235,
62,
78,
191,
129,
209,
126,
111,
35,
143,
163,
161,
246,
117,
123,
50,
222,
65,
52,
19,
125,
141,
221,
55,
65,
3,
195,
197,
25,
7,
33,
220,
237,
44,
70,
71,
139,
122,
193,
245,
247,
130,
33,
71,
21,
162,
153,
158,
159,
170,
169,
150,
188,
174,
196,
216,
186,
92,
144,
160,
161,
2,
97,
167,
141,
125,
241,
164,
167,
37,
72,
38,
12,
145,
159,
160,
38,
82,
13,
63,
68,
71,
226,
35,
111,
158,
153,
154,
101,
50,
205,
206,
92,
165,
209,
198,
217,
165,
167,
97,
220,
115,
218,
133,
112,
243,
239,
238,
241,
214,
135,
169,
190,
173,
133,
171,
208,
32,
125,
44,
237,
86,
87,
178,
85,
86,
179,
84,
85,
180,
83,
84,
181,
201,
83,
182,
137,
93,
132,
76,
62,
183,
61,
76,
184,
57,
61,
185,
212,
57,
186,
214,
207,
187,
34,
143,
156,
79,
239,
237,
123,
137,
177,
44,
1,
4,
201,
194,
32,
64,
102,
129,
213,
215,
138,
59,
166,
219,
242,
99,
97,
2,
94,
141,
75,
59,
235,
24,
110,
228,
25,
130,
226,
23,
24,
229,
22,
23,
230,
26,
22,
231,
112,
26,
232,
189,
190,
243,
221,
56,
190,
28,
56,
221,
27,
28,
222,
29,
27,
223,
30,
29,
224,
247,
30,
225,
238,
79,
20,
166,
59,
75,
60,
75,
240,
147,
177,
215,
20,
79,
166,
187,
147,
213,
112,
233,
244,
233,
128,
245,
128,
114,
188,
114,
217,
174,
131,
115,
220,
217,
198,
236,
198,
131,
134,
177,
132,
58,
143,
35,
124,
110,
163,
7,
228,
110,
25,
356,
389,
368,
11,
302,
267,
452,
350,
349,
302,
303,
269,
357,
343,
277,
452,
453,
357,
333,
332,
297,
175,
152,
377,
384,
398,
382,
347,
348,
330,
303,
304,
270,
9,
336,
337,
278,
279,
360,
418,
262,
431,
304,
408,
409,
310,
415,
407,
270,
409,
410,
450,
348,
347,
422,
430,
434,
313,
314,
17,
306,
307,
375,
387,
388,
260,
286,
414,
398,
335,
406,
418,
364,
367,
416,
423,
358,
327,
251,
284,
298,
281,
5,
4,
373,
374,
253,
307,
320,
321,
425,
427,
411,
421,
313,
18,
321,
405,
406,
320,
404,
405,
315,
16,
17,
426,
425,
266,
377,
400,
369,
322,
391,
269,
417,
465,
464,
386,
257,
258,
466,
260,
388,
456,
399,
419,
284,
332,
333,
417,
285,
8,
346,
340,
261,
413,
441,
285,
327,
460,
328,
355,
371,
329,
392,
439,
438,
382,
341,
256,
429,
420,
360,
364,
394,
379,
277,
343,
437,
443,
444,
283,
275,
440,
363,
431,
262,
369,
297,
338,
337,
273,
375,
321,
450,
451,
349,
446,
342,
467,
293,
334,
282,
458,
461,
462,
276,
353,
383,
308,
324,
325,
276,
300,
293,
372,
345,
447,
382,
398,
362,
352,
345,
340,
274,
1,
19,
456,
248,
281,
436,
427,
425,
381,
256,
252,
269,
391,
393,
200,
199,
428,
266,
330,
329,
287,
273,
422,
250,
462,
328,
258,
286,
384,
265,
353,
342,
387,
259,
257,
424,
431,
430,
342,
353,
276,
273,
335,
424,
292,
325,
307,
366,
447,
345,
271,
303,
302,
423,
266,
371,
294,
455,
460,
279,
278,
294,
271,
272,
304,
432,
434,
427,
272,
407,
408,
394,
430,
431,
395,
369,
400,
334,
333,
299,
351,
417,
168,
352,
280,
411,
325,
319,
320,
295,
296,
336,
319,
403,
404,
330,
348,
349,
293,
298,
333,
323,
454,
447,
15,
16,
315,
358,
429,
279,
14,
15,
316,
285,
336,
9,
329,
349,
350,
374,
380,
252,
318,
402,
403,
6,
197,
419,
318,
319,
325,
367,
364,
365,
435,
367,
397,
344,
438,
439,
272,
271,
311,
195,
5,
281,
273,
287,
291,
396,
428,
199,
311,
271,
268,
283,
444,
445,
373,
254,
339,
263,
466,
249,
282,
334,
296,
449,
347,
346,
264,
447,
454,
336,
296,
299,
338,
10,
151,
278,
439,
455,
292,
407,
415,
358,
371,
355,
340,
345,
372,
390,
249,
466,
346,
347,
280,
442,
443,
282,
19,
94,
370,
441,
442,
295,
248,
419,
197,
263,
255,
359,
440,
275,
274,
300,
383,
368,
351,
412,
465,
263,
467,
466,
301,
368,
389,
380,
374,
386,
395,
378,
379,
412,
351,
419,
436,
426,
322,
373,
390,
388,
2,
164,
393,
370,
462,
461,
164,
0,
267,
302,
11,
12,
374,
373,
387,
268,
12,
13,
293,
300,
301,
446,
261,
340,
385,
384,
381,
330,
266,
425,
426,
423,
391,
429,
355,
437,
391,
327,
326,
440,
457,
438,
341,
382,
362,
459,
457,
461,
434,
430,
394,
414,
463,
362,
396,
369,
262,
354,
461,
457,
316,
403,
402,
315,
404,
403,
314,
405,
404,
313,
406,
405,
421,
418,
406,
366,
401,
361,
306,
408,
407,
291,
409,
408,
287,
410,
409,
432,
436,
410,
434,
416,
411,
264,
368,
383,
309,
438,
457,
352,
376,
401,
274,
275,
4,
421,
428,
262,
294,
327,
358,
433,
416,
367,
289,
455,
439,
462,
370,
326,
2,
326,
370,
305,
460,
455,
254,
449,
448,
255,
261,
446,
253,
450,
449,
252,
451,
450,
256,
452,
451,
341,
453,
452,
413,
464,
463,
441,
413,
414,
258,
442,
441,
257,
443,
442,
259,
444,
443,
260,
445,
444,
467,
342,
445,
459,
458,
250,
289,
392,
290,
290,
328,
460,
376,
433,
435,
250,
290,
392,
411,
416,
433,
341,
463,
464,
453,
464,
465,
357,
465,
412,
343,
412,
399,
360,
363,
440,
437,
399,
456,
420,
456,
363,
401,
435,
288,
372,
383,
353,
339,
255,
249,
448,
261,
255,
133,
243,
190,
133,
155,
112,
33,
246,
247,
33,
130,
25,
398,
384,
286,
362,
398,
414,
362,
463,
341,
263,
359,
467,
263,
249,
255,
466,
467,
260,
75,
60,
166,
238,
239,
79,
162,
127,
139,
72,
11,
37,
121,
232,
120,
73,
72,
39,
114,
128,
47,
233,
232,
128,
103,
104,
67,
152,
175,
148,
173,
157,
155,
119,
118,
101,
74,
73,
40,
107,
9,
108,
49,
48,
131,
32,
194,
211,
184,
74,
185,
191,
80,
183,
185,
40,
186,
119,
230,
118,
210,
202,
214,
84,
83,
17,
77,
76,
146,
161,
160,
30,
190,
56,
173,
182,
106,
194,
138,
135,
192,
129,
203,
98,
54,
21,
68,
5,
51,
4,
145,
144,
23,
90,
77,
91,
207,
205,
187,
83,
201,
18,
181,
91,
182,
180,
90,
181,
16,
85,
17,
205,
206,
36,
176,
148,
140,
165,
92,
39,
245,
193,
244,
27,
159,
28,
30,
247,
161,
174,
236,
196,
103,
54,
104,
55,
193,
8,
111,
117,
31,
221,
189,
55,
240,
98,
99,
142,
126,
100,
219,
166,
218,
112,
155,
26,
198,
209,
131,
169,
135,
150,
114,
47,
217,
224,
223,
53,
220,
45,
134,
32,
211,
140,
109,
67,
108,
146,
43,
91,
231,
230,
120,
113,
226,
247,
105,
63,
52,
241,
238,
242,
124,
46,
156,
95,
78,
96,
70,
46,
63,
116,
143,
227,
116,
123,
111,
1,
44,
19,
3,
236,
51,
207,
216,
205,
26,
154,
22,
165,
39,
167,
199,
200,
208,
101,
36,
100,
43,
57,
202,
242,
20,
99,
56,
28,
157,
124,
35,
113,
29,
160,
27,
211,
204,
210,
124,
113,
46,
106,
43,
204,
96,
62,
77,
227,
137,
116,
73,
41,
72,
36,
203,
142,
235,
64,
240,
48,
49,
64,
42,
41,
74,
214,
212,
207,
183,
42,
184,
210,
169,
211,
140,
170,
176,
104,
105,
69,
193,
122,
168,
50,
123,
187,
89,
96,
90,
66,
65,
107,
179,
89,
180,
119,
101,
120,
68,
63,
104,
234,
93,
227,
16,
15,
85,
209,
129,
49,
15,
14,
86,
107,
55,
9,
120,
100,
121,
153,
145,
22,
178,
88,
179,
197,
6,
196,
89,
88,
96,
135,
138,
136,
138,
215,
172,
218,
115,
219,
41,
42,
81,
5,
195,
51,
57,
43,
61,
208,
171,
199,
41,
81,
38,
224,
53,
225,
24,
144,
110,
105,
52,
66,
118,
229,
117,
227,
34,
234,
66,
107,
69,
10,
109,
151,
219,
48,
235,
183,
62,
191,
142,
129,
126,
116,
111,
143,
7,
163,
246,
118,
117,
50,
223,
222,
52,
94,
19,
141,
222,
221,
65,
196,
3,
197,
45,
220,
44,
156,
70,
139,
188,
122,
245,
139,
71,
162,
145,
153,
159,
149,
170,
150,
122,
188,
196,
206,
216,
92,
163,
144,
161,
164,
2,
167,
242,
141,
241,
0,
164,
37,
11,
72,
12,
144,
145,
160,
12,
38,
13,
70,
63,
71,
31,
226,
111,
157,
158,
154,
36,
101,
205,
203,
206,
165,
126,
209,
217,
98,
165,
97,
237,
220,
218,
237,
239,
241,
210,
214,
169,
140,
171,
32,
241,
125,
237,
179,
86,
178,
180,
85,
179,
181,
84,
180,
182,
83,
181,
194,
201,
182,
177,
137,
132,
184,
76,
183,
185,
61,
184,
186,
57,
185,
216,
212,
186,
192,
214,
187,
139,
34,
156,
218,
79,
237,
147,
123,
177,
45,
44,
4,
208,
201,
32,
98,
64,
129,
192,
213,
138,
235,
59,
219,
141,
242,
97,
97,
2,
141,
240,
75,
235,
229,
24,
228,
31,
25,
226,
230,
23,
229,
231,
22,
230,
232,
26,
231,
233,
112,
232,
244,
189,
243,
189,
221,
190,
222,
28,
221,
223,
27,
222,
224,
29,
223,
225,
30,
224,
113,
247,
225,
99,
60,
240,
213,
147,
215,
60,
20,
166,
192,
187,
213,
243,
112,
244,
244,
233,
245,
245,
128,
188,
188,
114,
174,
134,
131,
220,
174,
217,
236,
236,
198,
134,
215,
177,
58,
156,
143,
124,
25,
110,
7,
31,
228,
25,
264,
356,
368,
0,
11,
267,
451,
452,
349,
267,
302,
269,
350,
357,
277,
350,
452,
357,
299,
333,
297,
396,
175,
377,
381,
384,
382,
280,
347,
330,
269,
303,
270,
151,
9,
337,
344,
278,
360,
424,
418,
431,
270,
304,
409,
272,
310,
407,
322,
270,
410,
449,
450,
347,
432,
422,
434,
18,
313,
17,
291,
306,
375,
259,
387,
260,
424,
335,
418,
434,
364,
416,
391,
423,
327,
301,
251,
298,
275,
281,
4,
254,
373,
253,
375,
307,
321,
280,
425,
411,
200,
421,
18,
335,
321,
406,
321,
320,
405,
314,
315,
17,
423,
426,
266,
396,
377,
369,
270,
322,
269,
413,
417,
464,
385,
386,
258,
248,
456,
419,
298,
284,
333,
168,
417,
8,
448,
346,
261,
417,
413,
285,
326,
327,
328,
277,
355,
329,
309,
392,
438,
381,
382,
256,
279,
429,
360,
365,
364,
379,
355,
277,
437,
282,
443,
283,
281,
275,
363,
395,
431,
369,
299,
297,
337,
335,
273,
321,
348,
450,
349,
359,
446,
467,
283,
293,
282,
250,
458,
462,
300,
276,
383,
292,
308,
325,
283,
276,
293,
264,
372,
447,
346,
352,
340,
354,
274,
19,
363,
456,
281,
426,
436,
425,
380,
381,
252,
267,
269,
393,
421,
200,
428,
371,
266,
329,
432,
287,
422,
290,
250,
328,
385,
258,
384,
446,
265,
342,
386,
387,
257,
422,
424,
430,
445,
342,
276,
422,
273,
424,
306,
292,
307,
352,
366,
345,
268,
271,
302,
358,
423,
371,
327,
294,
460,
331,
279,
294,
303,
271,
304,
436,
432,
427,
304,
272,
408,
395,
394,
431,
378,
395,
400,
296,
334,
299,
6,
351,
168,
376,
352,
411,
307,
325,
320,
285,
295,
336,
320,
319,
404,
329,
330,
349,
334,
293,
333,
366,
323,
447,
316,
15,
315,
331,
358,
279,
317,
14,
316,
8,
285,
9,
277,
329,
350,
253,
374,
252,
319,
318,
403,
351,
6,
419,
324,
318,
325,
397,
367,
365,
288,
435,
397,
278,
344,
439,
310,
272,
311,
248,
195,
281,
375,
273,
291,
175,
396,
199,
312,
311,
268,
276,
283,
445,
390,
373,
339,
295,
282,
296,
448,
449,
346,
356,
264,
454,
337,
336,
299,
337,
338,
151,
294,
278,
455,
308,
292,
415,
429,
358,
355,
265,
340,
372,
388,
390,
466,
352,
346,
280,
295,
442,
282,
354,
19,
370,
285,
441,
295,
195,
248,
197,
457,
440,
274,
301,
300,
368,
417,
351,
465,
251,
301,
389,
385,
380,
386,
394,
395,
379,
399,
412,
419,
410,
436,
322,
387,
373,
388,
326,
2,
393,
354,
370,
461,
393,
164,
267,
268,
302,
12,
386,
374,
387,
312,
268,
13,
298,
293,
301,
265,
446,
340,
380,
385,
381,
280,
330,
425,
322,
426,
391,
420,
429,
437,
393,
391,
326,
344,
440,
438,
458,
459,
461,
364,
434,
394,
428,
396,
262,
274,
354,
457,
317,
316,
402,
316,
315,
403,
315,
314,
404,
314,
313,
405,
313,
421,
406,
323,
366,
361,
292,
306,
407,
306,
291,
408,
291,
287,
409,
287,
432,
410,
427,
434,
411,
372,
264,
383,
459,
309,
457,
366,
352,
401,
1,
274,
4,
418,
421,
262,
331,
294,
358,
435,
433,
367,
392,
289,
439,
328,
462,
326,
94,
2,
370,
289,
305,
455,
339,
254,
448,
359,
255,
446,
254,
253,
449,
253,
252,
450,
252,
256,
451,
256,
341,
452,
414,
413,
463,
286,
441,
414,
286,
258,
441,
258,
257,
442,
257,
259,
443,
259,
260,
444,
260,
467,
445,
309,
459,
250,
305,
289,
290,
305,
290,
460,
401,
376,
435,
309,
250,
392,
376,
411,
433,
453,
341,
464,
357,
453,
465,
343,
357,
412,
437,
343,
399,
344,
360,
440,
420,
437,
456,
360,
420,
363,
361,
401,
288,
265,
372,
353,
390,
339,
249,
339,
448,
255
];
var VTX68 = [
127,
234,
132,
58,
172,
150,
149,
148,
152,
377,
378,
379,
397,
288,
361,
454,
356,
70,
63,
105,
66,
107,
336,
296,
334,
293,
300,
168,
6,
195,
4,
98,
97,
2,
326,
327,
33,
160,
158,
133,
153,
144,
362,
385,
387,
263,
373,
380,
57,
40,
37,
0,
267,
270,
287,
321,
314,
17,
84,
91,
78,
81,
13,
311,
308,
402,
14,
178
];
var VTX33 = [33, 133, 362, 263, 1, 62, 308, 159, 145, 386, 374, 6, 102, 331, 2, 13, 14, 70, 105, 107, 336, 334, 300, 54, 10, 284, 50, 280, 234, 454, 58, 288, 152];
var VTX7 = [33, 133, 362, 263, 1, 78, 308];
var UV68 = VTX68.map((x) => UV468[x]);
var UV33 = VTX33.map((x) => UV468[x]);
var UV7 = VTX7.map((x) => UV468[x]);
function connectionsToIndices(connections) {
const indices = connections.map((connection) => connection[0]);
indices.push(connections[connections.length - 1][1]);
return indices;
}
var pairsLips = [
[61, 146],
[146, 91],
[91, 181],
[181, 84],
[84, 17],
[17, 314],
[314, 405],
[405, 321],
[321, 375],
[375, 291],
[61, 185],
[185, 40],
[40, 39],
[39, 37],
[37, 0],
[0, 267],
[267, 269],
[269, 270],
[270, 409],
[409, 291],
[78, 95],
[95, 88],
[88, 178],
[178, 87],
[87, 14],
[14, 317],
[317, 402],
[402, 318],
[318, 324],
[324, 308],
[78, 191],
[191, 80],
[80, 81],
[81, 82],
[82, 13],
[13, 312],
[312, 311],
[311, 310],
[310, 415],
[415, 308]
];
var pairsLeftEye = [[263, 249], [249, 390], [390, 373], [373, 374], [374, 380], [380, 381], [381, 382], [382, 362], [263, 466], [466, 388], [388, 387], [387, 386], [386, 385], [385, 384], [384, 398], [398, 362]];
var pairsLeftEyebrow = [[276, 283], [283, 282], [282, 295], [295, 285], [300, 293], [293, 334], [334, 296], [296, 336]];
var pairsLeftIris = [[474, 475], [475, 476], [476, 477], [477, 474]];
var pairsRightEye = [[33, 7], [7, 163], [163, 144], [144, 145], [145, 153], [153, 154], [154, 155], [155, 133], [33, 246], [246, 161], [161, 160], [160, 159], [159, 158], [158, 157], [157, 173], [173, 133]];
var pairsRightEyebrow = [[46, 53], [53, 52], [52, 65], [65, 55], [70, 63], [63, 105], [105, 66], [66, 107]];
var pairsRightIris = [[469, 470], [470, 471], [471, 472], [472, 469]];
var pairsFaceContour = [
[10, 338],
[338, 297],
[297, 332],
[332, 284],
[284, 251],
[251, 389],
[389, 356],
[356, 454],
[454, 323],
[323, 361],
[361, 288],
[288, 397],
[397, 365],
[365, 379],
[379, 378],
[378, 400],
[400, 377],
[377, 152],
[152, 148],
[148, 176],
[176, 149],
[149, 150],
[150, 136],
[136, 172],
[172, 58],
[58, 132],
[132, 93],
[93, 234],
[234, 127],
[127, 162],
[162, 21],
[21, 54],
[54, 103],
[103, 67],
[67, 109],
[109, 10]
];
var contourKeypoints = {
lips: connectionsToIndices(pairsLips),
leftEye: connectionsToIndices(pairsLeftEye),
leftEyebrow: connectionsToIndices(pairsLeftEyebrow),
leftIris: connectionsToIndices(pairsLeftIris),
rightEye: connectionsToIndices(pairsRightEye),
rightEyebrow: connectionsToIndices(pairsRightEyebrow),
rightIris: connectionsToIndices(pairsRightIris),
faceOval: connectionsToIndices(pairsFaceContour)
};
// src/face/facemeshutil.ts
var getBoxSize = (box) => [Math.abs(box.endPoint[0] - box.startPoint[0]), Math.abs(box.endPoint[1] - box.startPoint[1])];
var getBoxCenter = (box) => [box.startPoint[0] + (box.endPoint[0] - box.startPoint[0]) / 2, box.startPoint[1] + (box.endPoint[1] - box.startPoint[1]) / 2, 1];
var clampBox = (box, input) => box ? [
Math.trunc(Math.max(0, box.startPoint[0])),
Math.trunc(Math.max(0, box.startPoint[1])),
Math.trunc(Math.min(input.shape[2] || 0, box.endPoint[0]) - Math.max(0, box.startPoint[0])),
Math.trunc(Math.min(input.shape[1] || 0, box.endPoint[1]) - Math.max(0, box.startPoint[1]))
] : [0, 0, 0, 0];
var getRawBox = (box, input) => box ? [
box.startPoint[0] / (input.shape[2] || 0),
box.startPoint[1] / (input.shape[1] || 0),
(box.endPoint[0] - box.startPoint[0]) / (input.shape[2] || 0),
(box.endPoint[1] - box.startPoint[1]) / (input.shape[1] || 0)
] : [0, 0, 0, 0];
var scaleBoxCoordinates = (box, factor) => {
const startPoint = [box.startPoint[0] * factor[0], box.startPoint[1] * factor[1]];
const endPoint = [box.endPoint[0] * factor[0], box.endPoint[1] * factor[1]];
return { startPoint, endPoint, landmarks: box.landmarks, confidence: box.confidence };
};
var cutAndResize = (box, image, cropSize) => {
const h = image.shape[1];
const w10 = image.shape[2];
const cutBox = [box.startPoint[1] / h, box.startPoint[0] / w10, box.endPoint[1] / h, box.endPoint[0] / w10];
const crop = Kn.cropAndResize(image, [cutBox], [0], cropSize);
const norm = xe(crop, constants.tf255);
De(crop);
return norm;
};
var enlargeBox = (box, factor) => {
const center = getBoxCenter(box);
const size2 = getBoxSize(box);
const halfSize = [factor * size2[0] / 2, factor * size2[1] / 2];
return { startPoint: [center[0] - halfSize[0], center[1] - halfSize[1]], endPoint: [center[0] + halfSize[0], center[1] + halfSize[1]], landmarks: box.landmarks, confidence: box.confidence };
};
var squarifyBox = (box) => {
const centers = getBoxCenter(box);
const size2 = getBoxSize(box);
const halfSize = Math.max(...size2) / 2;
return { startPoint: [Math.round(centers[0] - halfSize), Math.round(centers[1] - halfSize)], endPoint: [Math.round(centers[0] + halfSize), Math.round(centers[1] + halfSize)], landmarks: box.landmarks, confidence: box.confidence };
};
var calculateLandmarksBoundingBox = (landmarks) => {
const x = landmarks.map((d) => d[0]);
const y = landmarks.map((d) => d[1]);
return { startPoint: [Math.min(...x), Math.min(...y)], endPoint: [Math.max(...x), Math.max(...y)], landmarks };
};
var fixedRotationMatrix = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
var normalizeRadians = (angle) => angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));
var computeRotation = (point1, point2) => normalizeRadians(Math.PI / 2 - Math.atan2(-(point2[1] - point1[1]), point2[0] - point1[0]));
var buildTranslationMatrix = (x, y) => [[1, 0, x], [0, 1, y], [0, 0, 1]];
var dot = (v12, v22) => {
let product = 0;
for (let i = 0; i < v12.length; i++)
product += v12[i] * v22[i];
return product;
};
var getColumnFrom2DArr = (arr, columnIndex) => {
const column = [];
for (let i = 0; i < arr.length; i++)
column.push(arr[i][columnIndex]);
return column;
};
var multiplyTransformMatrices = (mat1, mat2) => {
const product = [];
const size2 = mat1.length;
for (let row = 0; row < size2; row++) {
product.push([]);
for (let col = 0; col < size2; col++)
product[row].push(dot(mat1[row], getColumnFrom2DArr(mat2, col)));
}
return product;
};
var buildRotationMatrix = (rotation, center) => {
const cosA = Math.cos(rotation);
const sinA = Math.sin(rotation);
const rotationMatrix = [[cosA, -sinA, 0], [sinA, cosA, 0], [0, 0, 1]];
const translationMatrix = buildTranslationMatrix(center[0], center[1]);
const translationTimesRotation = multiplyTransformMatrices(translationMatrix, rotationMatrix);
const negativeTranslationMatrix = buildTranslationMatrix(-center[0], -center[1]);
return multiplyTransformMatrices(translationTimesRotation, negativeTranslationMatrix);
};
var invertTransformMatrix = (matrix) => {
const rotationComponent = [[matrix[0][0], matrix[1][0]], [matrix[0][1], matrix[1][1]]];
const translationComponent = [matrix[0][2], matrix[1][2]];
const invertedTranslation = [-dot(rotationComponent[0], translationComponent), -dot(rotationComponent[1], translationComponent)];
return [rotationComponent[0].concat(invertedTranslation[0]), rotationComponent[1].concat(invertedTranslation[1]), [0, 0, 1]];
};
var rotatePoint = (homogeneousCoordinate, rotationMatrix) => [dot(homogeneousCoordinate, rotationMatrix[0]), dot(homogeneousCoordinate, rotationMatrix[1])];
function generateAnchors(inputSize10) {
const spec = inputSize10 === 192 ? { strides: [4], anchors: [1] } : { strides: [inputSize10 / 16, inputSize10 / 8], anchors: [2, 6] };
const anchors3 = [];
for (let i = 0; i < spec.strides.length; i++) {
const stride = spec.strides[i];
const gridRows = Math.floor((inputSize10 + stride - 1) / stride);
const gridCols = Math.floor((inputSize10 + stride - 1) / stride);
const anchorsNum = spec.anchors[i];
for (let gridY = 0; gridY < gridRows; gridY++) {
const anchorY = stride * (gridY + 0.5);
for (let gridX = 0; gridX < gridCols; gridX++) {
const anchorX = stride * (gridX + 0.5);
for (let n = 0; n < anchorsNum; n++)
anchors3.push([anchorX, anchorY]);
}
}
}
return anchors3;
}
function transformRawCoords(coordsRaw, box, angle, rotationMatrix, inputSize10) {
const boxSize = getBoxSize(box);
const coordsScaled = coordsRaw.map((coord) => [
boxSize[0] / inputSize10 * (coord[0] - inputSize10 / 2),
boxSize[1] / inputSize10 * (coord[1] - inputSize10 / 2),
coord[2] || 0
]);
const largeAngle = angle && angle !== 0 && Math.abs(angle) > 0.2;
const coordsRotationMatrix = largeAngle ? buildRotationMatrix(angle, [0, 0]) : fixedRotationMatrix;
const coordsRotated = largeAngle ? coordsScaled.map((coord) => [...rotatePoint(coord, coordsRotationMatrix), coord[2]]) : coordsScaled;
const inverseRotationMatrix = largeAngle ? invertTransformMatrix(rotationMatrix) : fixedRotationMatrix;
const boxCenter = getBoxCenter(box);
const offsets = [dot(boxCenter, inverseRotationMatrix[0]), dot(boxCenter, inverseRotationMatrix[1])];
return coordsRotated.map((coord) => [
Math.trunc(coord[0] + offsets[0]),
Math.trunc(coord[1] + offsets[1]),
Math.trunc(coord[2] || 0)
]);
}
function correctFaceRotation(rotate, box, input, inputSize10) {
const symmetryLine = box.landmarks.length >= meshLandmarks.count ? meshLandmarks.symmetryLine : blazeFaceLandmarks.symmetryLine;
let angle = 0;
let rotationMatrix = fixedRotationMatrix;
let face4;
if (rotate && env.kernels.includes("rotatewithoffset")) {
angle = computeRotation(box.landmarks[symmetryLine[0]], box.landmarks[symmetryLine[1]]);
const largeAngle = angle && angle !== 0 && Math.abs(angle) > 0.2;
if (largeAngle) {
const center = getBoxCenter(box);
const centerRaw = [center[0] / input.shape[2], center[1] / input.shape[1]];
const rotated = Kn.rotateWithOffset(input, angle, 0, centerRaw);
rotationMatrix = buildRotationMatrix(-angle, center);
face4 = cutAndResize(box, rotated, [inputSize10, inputSize10]);
De(rotated);
} else {
face4 = cutAndResize(box, input, [inputSize10, inputSize10]);
}
} else {
face4 = cutAndResize(box, input, [inputSize10, inputSize10]);
}
return [angle, rotationMatrix, face4];
}
var findFaceCenter = (mesh) => {
const x = mesh.map((m) => m[0]);
const y = mesh.map((m) => m[1]);
return [Math.min(...x) + (Math.max(...x) - Math.min(...x)) / 2, Math.min(...y) + (Math.max(...y) - Math.min(...y)) / 2];
};
var calculateFaceBox = (mesh, previousBox) => {
const center = findFaceCenter(mesh);
const boxSize = getBoxSize(previousBox);
const calculatedBox = {
startPoint: [center[0] - boxSize[0] / 2, center[1] - boxSize[1] / 2],
endPoint: [center[0] + boxSize[0] / 2, center[1] + boxSize[1] / 2]
};
return calculatedBox;
};
// src/face/blazeface.ts
var keypointsCount = 6;
var faceBoxScaleFactor = 1.4;
var model5;
var anchors = null;
var inputSize = 0;
var inputSizeT = null;
var size = () => inputSize;
async function load5(config3) {
var _a2;
if (env.initial)
model5 = null;
if (!model5)
model5 = await loadModel((_a2 = config3.face.detector) == null ? void 0 : _a2.modelPath);
else if (config3.debug)
log("cached model:", model5["modelUrl"]);
inputSize = model5.inputs[0].shape ? model5.inputs[0].shape[2] : 0;
inputSizeT = we(inputSize, "int32");
anchors = Zo(generateAnchors(inputSize));
return model5;
}
function decodeBounds(boxOutputs) {
const t = {};
t.boxStarts = qe(boxOutputs, [0, 1], [-1, 2]);
t.centers = oe(t.boxStarts, anchors);
t.boxSizes = qe(boxOutputs, [0, 3], [-1, 2]);
t.boxSizesNormalized = xe(t.boxSizes, inputSizeT);
t.centersNormalized = xe(t.centers, inputSizeT);
t.halfBoxSize = xe(t.boxSizesNormalized, constants.tf2);
t.starts = ge(t.centersNormalized, t.halfBoxSize);
t.ends = oe(t.centersNormalized, t.halfBoxSize);
t.startNormalized = V(t.starts, inputSizeT);
t.endNormalized = V(t.ends, inputSizeT);
const boxes = dR([t.startNormalized, t.endNormalized], 1);
Object.keys(t).forEach((tensor) => De(t[tensor]));
return boxes;
}
async function getBoxes(inputImage, config3) {
var _a2, _b2, _c, _d2;
if (!inputImage || inputImage["isDisposedInternal"] || inputImage.shape.length !== 4 || inputImage.shape[1] < 1 || inputImage.shape[2] < 1)
return [];
const t = {};
t.resized = Kn.resizeBilinear(inputImage, [inputSize, inputSize]);
t.div = xe(t.resized, constants.tf127);
t.normalized = ge(t.div, constants.tf05);
const res = model5 == null ? void 0 : model5.execute(t.normalized);
if (Array.isArray(res) && res.length > 2) {
const sorted = res.sort((a, b) => a.size - b.size);
t.concat384 = Ft([sorted[0], sorted[2]], 2);
t.concat512 = Ft([sorted[1], sorted[3]], 2);
t.concat = Ft([t.concat512, t.concat384], 1);
t.batch = br(t.concat, 0);
} else if (Array.isArray(res)) {
t.batch = br(res[0]);
} else {
t.batch = br(res);
}
De(res);
t.boxes = decodeBounds(t.batch);
t.logits = qe(t.batch, [0, 0], [-1, 1]);
t.sigmoid = qs(t.logits);
t.scores = br(t.sigmoid);
t.nms = await Kn.nonMaxSuppressionAsync(t.boxes, t.scores, ((_a2 = config3.face.detector) == null ? void 0 : _a2.maxDetected) || 0, ((_b2 = config3.face.detector) == null ? void 0 : _b2.iouThreshold) || 0, ((_c = config3.face.detector) == null ? void 0 : _c.minConfidence) || 0);
const nms = await t.nms.array();
const boxes = [];
const scores = await t.scores.data();
for (let i = 0; i < nms.length; i++) {
const confidence = scores[nms[i]];
if (confidence > (((_d2 = config3.face.detector) == null ? void 0 : _d2.minConfidence) || 0)) {
const b = {};
b.bbox = qe(t.boxes, [nms[i], 0], [1, -1]);
b.slice = qe(t.batch, [nms[i], keypointsCount - 1], [1, -1]);
b.squeeze = br(b.slice);
b.landmarks = U(b.squeeze, [keypointsCount, -1]);
const points = await b.bbox.data();
const rawBox = {
startPoint: [points[0], points[1]],
endPoint: [points[2], points[3]],
landmarks: await b.landmarks.array(),
confidence
};
const scaledBox = scaleBoxCoordinates(rawBox, [(inputImage.shape[2] || 0) / inputSize, (inputImage.shape[1] || 0) / inputSize]);
const enlargedBox = enlargeBox(scaledBox, config3.face["scale"] || faceBoxScaleFactor);
const squaredBox = squarifyBox(enlargedBox);
boxes.push(squaredBox);
Object.keys(b).forEach((tensor) => De(b[tensor]));
}
}
Object.keys(t).forEach((tensor) => De(t[tensor]));
return boxes;
}
// src/body/blazeposecoords.ts
var blazeposecoords_exports = {};
__export(blazeposecoords_exports, {
connected: () => connected,
kpt: () => kpt
});
var kpt = [
"nose",
"leftEyeInside",
"leftEye",
"leftEyeOutside",
"rightEyeInside",
"rightEye",
"rightEyeOutside",
"leftEar",
"rightEar",
"leftMouth",
"rightMouth",
"leftShoulder",
"rightShoulder",
"leftElbow",
"rightElbow",
"leftWrist",
"rightWrist",
"leftPinky",
"rightPinky",
"leftIndex",
"rightIndex",
"leftThumb",
"rightThumb",
"leftHip",
"rightHip",
"leftKnee",
"rightKnee",
"leftAnkle",
"rightAnkle",
"leftHeel",
"rightHeel",
"leftFoot",
"rightFoot",
"bodyCenter",
"bodyTop",
"leftPalm",
"leftHand",
"rightPalm",
"rightHand"
];
var connected = {
shoulders: ["leftShoulder", "rightShoulder"],
hips: ["rightHip", "leftHip"],
mouth: ["leftMouth", "rightMouth"],
leftLegUpper: ["leftHip", "leftKnee"],
leftLegLower: ["leftKnee", "leftAnkle"],
leftFoot: ["leftAnkle", "leftHeel", "leftFoot"],
leftTorso: ["leftShoulder", "leftHip"],
leftArmUpper: ["leftShoulder", "leftElbow"],
leftArmLower: ["leftElbow", "leftWrist"],
leftHand: ["leftWrist", "leftPalm"],
leftHandPinky: ["leftPalm", "leftPinky"],
leftHandIndex: ["leftPalm", "leftIndex"],
leftHandThumb: ["leftPalm", "leftThumb"],
leftEyeOutline: ["leftEyeInside", "leftEyeOutside"],
rightLegUpper: ["rightHip", "rightKnee"],
rightLegLower: ["rightKnee", "rightAnkle"],
rightFoot: ["rightAnkle", "rightHeel", "rightFoot"],
rightTorso: ["rightShoulder", "rightHip"],
rightArmUpper: ["rightShoulder", "rightElbow"],
rightArmLower: ["rightElbow", "rightWrist"],
rightHand: ["rightWrist", "rightPalm"],
rightHandPinky: ["rightPalm", "rightPinky"],
rightHandIndex: ["rightPalm", "rightIndex"],
rightHandThumb: ["rightPalm", "rightThumb"],
rightEyeOutline: ["rightEyeInside", "rightEyeOutside"]
};
// src/body/blazeposedetector.ts
var inputSize2 = 224;
var anchorTensor;
var numLayers = 5;
var strides = [8, 16, 32, 32, 32];
async function createAnchors() {
const anchors3 = [];
let layerId = 0;
while (layerId < numLayers) {
let anchorCount = 0;
let lastSameStrideLayer = layerId;
while (lastSameStrideLayer < strides.length && strides[lastSameStrideLayer] === strides[layerId]) {
anchorCount += 2;
lastSameStrideLayer++;
}
const stride = strides[layerId];
const featureMapHeight = Math.ceil(inputSize2 / stride);
const featureMapWidth = Math.ceil(inputSize2 / stride);
for (let y = 0; y < featureMapHeight; ++y) {
for (let x = 0; x < featureMapWidth; ++x) {
for (let anchorId = 0; anchorId < anchorCount; ++anchorId) {
anchors3.push({ x: (x + 0.5) / featureMapWidth, y: (y + 0.5) / featureMapHeight });
}
}
}
layerId = lastSameStrideLayer;
}
anchorTensor = { x: Zt(anchors3.map((a) => a.x)), y: Zt(anchors3.map((a) => a.y)) };
}
// src/util/box.ts
function calc(keypoints, outputSize2 = [1, 1]) {
const coords = [keypoints.map((pt2) => pt2[0]), keypoints.map((pt2) => pt2[1])];
const min = [Math.min(...coords[0]), Math.min(...coords[1])];
const max = [Math.max(...coords[0]), Math.max(...coords[1])];
const box = [min[0], min[1], max[0] - min[0], max[1] - min[1]];
const boxRaw = [box[0] / outputSize2[0], box[1] / outputSize2[1], box[2] / outputSize2[0], box[3] / outputSize2[1]];
return { box, boxRaw };
}
function square(keypoints, outputSize2 = [1, 1]) {
const coords = [keypoints.map((pt2) => pt2[0]), keypoints.map((pt2) => pt2[1])];
const min = [Math.min(...coords[0]), Math.min(...coords[1])];
const max = [Math.max(...coords[0]), Math.max(...coords[1])];
const center = [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2];
const dist = Math.max(center[0] - min[0], center[1] - min[1], -center[0] + max[0], -center[1] + max[1]);
const box = [Math.trunc(center[0] - dist), Math.trunc(center[1] - dist), Math.trunc(2 * dist), Math.trunc(2 * dist)];
const boxRaw = [box[0] / outputSize2[0], box[1] / outputSize2[1], box[2] / outputSize2[0], box[3] / outputSize2[1]];
return { box, boxRaw };
}
function scale(box, scaleFact) {
const dist = [box[2] * scaleFact, box[3] * scaleFact];
const newBox = [
box[0] - (dist[0] - box[2]) / 2,
box[1] - (dist[1] - box[3]) / 2,
dist[0],
dist[1]
];
return newBox;
}
// src/body/blazepose.ts
var env2 = { initial: true };
var models = { detector: null, landmarks: null };
var inputSize3 = { detector: [224, 224], landmarks: [256, 256] };
var skipped5 = Number.MAX_SAFE_INTEGER;
var outputNodes = {
landmarks: ["ld_3d", "activation_segmentation", "activation_heatmap", "world_3d", "output_poseflag"],
detector: []
};
var cache = null;
var cropBox;
var padding = [[0, 0], [0, 0], [0, 0], [0, 0]];
var lastTime5 = 0;
var sigmoid = (x) => 1 - 1 / (1 + Math.exp(x));
async function loadDetect(config3) {
if (env2.initial)
models.detector = null;
if (!models.detector && config3.body["detector"] && config3.body["detector"]["modelPath"] || "") {
models.detector = await loadModel(config3.body["detector"]["modelPath"]);
const inputs = Object.values(models.detector.modelSignature["inputs"]);
inputSize3.detector[0] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[1].size) : 0;
inputSize3.detector[1] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : 0;
} else if (config3.debug && models.detector)
log("cached model:", models.detector["modelUrl"]);
await createAnchors();
return models.detector;
}
async function loadPose(config3) {
if (env2.initial)
models.landmarks = null;
if (!models.landmarks) {
models.landmarks = await loadModel(config3.body.modelPath);
const inputs = Object.values(models.landmarks.modelSignature["inputs"]);
inputSize3.landmarks[0] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[1].size) : 0;
inputSize3.landmarks[1] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : 0;
} else if (config3.debug)
log("cached model:", models.landmarks["modelUrl"]);
return models.landmarks;
}
async function prepareImage(input, size2) {
const t = {};
if (!input.shape || !input.shape[1] || !input.shape[2])
return input;
let final;
if (cropBox) {
t.cropped = Kn.cropAndResize(input, [cropBox], [0], [input.shape[1], input.shape[2]]);
}
if (input.shape[1] !== input.shape[2]) {
const height = [
input.shape[2] > input.shape[1] ? Math.trunc((input.shape[2] - input.shape[1]) / 2) : 0,
input.shape[2] > input.shape[1] ? Math.trunc((input.shape[2] - input.shape[1]) / 2) : 0
];
const width = [
input.shape[1] > input.shape[2] ? Math.trunc((input.shape[1] - input.shape[2]) / 2) : 0,
input.shape[1] > input.shape[2] ? Math.trunc((input.shape[1] - input.shape[2]) / 2) : 0
];
padding = [
[0, 0],
height,
width,
[0, 0]
];
t.pad = bo(t.cropped || input, padding);
t.resize = Kn.resizeBilinear(t.pad, [size2, size2]);
final = xe(t.resize, constants.tf255);
} else if (input.shape[1] !== size2) {
t.resize = Kn.resizeBilinear(t.cropped || input, [size2, size2]);
final = xe(t.resize, constants.tf255);
} else {
final = xe(t.cropped || input, constants.tf255);
}
Object.keys(t).forEach((tensor) => De(t[tensor]));
return final;
}
function rescaleKeypoints(keypoints, outputSize2) {
for (const kpt4 of keypoints) {
kpt4.position = [
Math.trunc(kpt4.position[0] * (outputSize2[0] + padding[2][0] + padding[2][1]) / outputSize2[0] - padding[2][0]),
Math.trunc(kpt4.position[1] * (outputSize2[1] + padding[1][0] + padding[1][1]) / outputSize2[1] - padding[1][0]),
kpt4.position[2]
];
kpt4.positionRaw = [kpt4.position[0] / outputSize2[0], kpt4.position[1] / outputSize2[1], 2 * kpt4.position[2] / (outputSize2[0] + outputSize2[1])];
}
if (cropBox) {
for (const kpt4 of keypoints) {
kpt4.positionRaw = [
kpt4.positionRaw[0] + cropBox[1],
kpt4.positionRaw[1] + cropBox[0],
kpt4.positionRaw[2]
];
kpt4.position = [
Math.trunc(kpt4.positionRaw[0] * outputSize2[0]),
Math.trunc(kpt4.positionRaw[1] * outputSize2[1]),
kpt4.positionRaw[2]
];
}
}
return keypoints;
}
async function fixKeypoints(keypoints) {
const leftPalm = keypoints.find((k) => k.part === "leftPalm");
const leftWrist = keypoints.find((k) => k.part === "leftWrist");
const leftIndex = keypoints.find((k) => k.part === "leftIndex");
leftPalm.position[2] = ((leftWrist.position[2] || 0) + (leftIndex.position[2] || 0)) / 2;
const rightPalm = keypoints.find((k) => k.part === "rightPalm");
const rightWrist = keypoints.find((k) => k.part === "rightWrist");
const rightIndex = keypoints.find((k) => k.part === "rightIndex");
rightPalm.position[2] = ((rightWrist.position[2] || 0) + (rightIndex.position[2] || 0)) / 2;
}
async function detectLandmarks(input, config3, outputSize2) {
var _a2;
const t = {};
[t.ld, t.segmentation, t.heatmap, t.world, t.poseflag] = (_a2 = models.landmarks) == null ? void 0 : _a2.execute(input, outputNodes.landmarks);
const poseScore = (await t.poseflag.data())[0];
const points = await t.ld.data();
const distances = await t.world.data();
Object.keys(t).forEach((tensor) => De(t[tensor]));
const keypointsRelative = [];
const depth = 5;
for (let i = 0; i < points.length / depth; i++) {
const score = sigmoid(points[depth * i + 3]);
const presence = sigmoid(points[depth * i + 4]);
const adjScore = Math.trunc(100 * score * presence * poseScore) / 100;
const positionRaw = [points[depth * i + 0] / inputSize3.landmarks[0], points[depth * i + 1] / inputSize3.landmarks[1], points[depth * i + 2] + 0];
const position = [Math.trunc(outputSize2[0] * positionRaw[0]), Math.trunc(outputSize2[1] * positionRaw[1]), positionRaw[2]];
const distance2 = [distances[depth * i + 0], distances[depth * i + 1], distances[depth * i + 2] + 0];
keypointsRelative.push({ part: kpt[i], positionRaw, position, distance: distance2, score: adjScore });
}
if (poseScore < (config3.body.minConfidence || 0))
return null;
fixKeypoints(keypointsRelative);
const keypoints = rescaleKeypoints(keypointsRelative, outputSize2);
const kpts = keypoints.map((k) => k.position);
const boxes = calc(kpts, [outputSize2[0], outputSize2[1]]);
const annotations2 = {};
for (const [name, indexes] of Object.entries(connected)) {
const pt2 = [];
for (let i = 0; i < indexes.length - 1; i++) {
const pt0 = keypoints.find((kpt4) => kpt4.part === indexes[i]);
const pt1 = keypoints.find((kpt4) => kpt4.part === indexes[i + 1]);
if (pt0 && pt1)
pt2.push([pt0.position, pt1.position]);
}
annotations2[name] = pt2;
}
const body4 = { id: 0, score: Math.trunc(100 * poseScore) / 100, box: boxes.box, boxRaw: boxes.boxRaw, keypoints, annotations: annotations2 };
return body4;
}
async function predict5(input, config3) {
const outputSize2 = [input.shape[2] || 0, input.shape[1] || 0];
const skipTime = (config3.body.skipTime || 0) > now() - lastTime5;
const skipFrame = skipped5 < (config3.body.skipFrames || 0);
if (config3.skipAllowed && skipTime && skipFrame && cache !== null) {
skipped5++;
} else {
const t = {};
t.landmarks = await prepareImage(input, 256);
cache = await detectLandmarks(t.landmarks, config3, outputSize2);
Object.keys(t).forEach((tensor) => De(t[tensor]));
lastTime5 = now();
skipped5 = 0;
}
return cache ? [cache] : [];
}
// src/object/labels.ts
var labels = [
{ class: 1, label: "person" },
{ class: 2, label: "bicycle" },
{ class: 3, label: "car" },
{ class: 4, label: "motorcycle" },
{ class: 5, label: "airplane" },
{ class: 6, label: "bus" },
{ class: 7, label: "train" },
{ class: 8, label: "truck" },
{ class: 9, label: "boat" },
{ class: 10, label: "traffic light" },
{ class: 11, label: "fire hydrant" },
{ class: 12, label: "stop sign" },
{ class: 13, label: "parking meter" },
{ class: 14, label: "bench" },
{ class: 15, label: "bird" },
{ class: 16, label: "cat" },
{ class: 17, label: "dog" },
{ class: 18, label: "horse" },
{ class: 19, label: "sheep" },
{ class: 20, label: "cow" },
{ class: 21, label: "elephant" },
{ class: 22, label: "bear" },
{ class: 23, label: "zebra" },
{ class: 24, label: "giraffe" },
{ class: 25, label: "backpack" },
{ class: 26, label: "umbrella" },
{ class: 27, label: "handbag" },
{ class: 28, label: "tie" },
{ class: 29, label: "suitcase" },
{ class: 30, label: "frisbee" },
{ class: 31, label: "skis" },
{ class: 32, label: "snowboard" },
{ class: 33, label: "sports ball" },
{ class: 34, label: "kite" },
{ class: 35, label: "baseball bat" },
{ class: 36, label: "baseball glove" },
{ class: 37, label: "skateboard" },
{ class: 38, label: "surfboard" },
{ class: 39, label: "tennis racket" },
{ class: 40, label: "bottle" },
{ class: 41, label: "wine glass" },
{ class: 42, label: "cup" },
{ class: 43, label: "fork" },
{ class: 44, label: "knife" },
{ class: 45, label: "spoon" },
{ class: 46, label: "bowl" },
{ class: 47, label: "banana" },
{ class: 48, label: "apple" },
{ class: 49, label: "sandwich" },
{ class: 50, label: "orange" },
{ class: 51, label: "broccoli" },
{ class: 52, label: "carrot" },
{ class: 53, label: "hot dog" },
{ class: 54, label: "pizza" },
{ class: 55, label: "donut" },
{ class: 56, label: "cake" },
{ class: 57, label: "chair" },
{ class: 58, label: "couch" },
{ class: 59, label: "potted plant" },
{ class: 60, label: "bed" },
{ class: 61, label: "dining table" },
{ class: 62, label: "toilet" },
{ class: 63, label: "tv" },
{ class: 64, label: "laptop" },
{ class: 65, label: "mouse" },
{ class: 66, label: "remote" },
{ class: 67, label: "keyboard" },
{ class: 68, label: "cell phone" },
{ class: 69, label: "microwave" },
{ class: 70, label: "oven" },
{ class: 71, label: "toaster" },
{ class: 72, label: "sink" },
{ class: 73, label: "refrigerator" },
{ class: 74, label: "book" },
{ class: 75, label: "clock" },
{ class: 76, label: "vase" },
{ class: 77, label: "scissors" },
{ class: 78, label: "teddy bear" },
{ class: 79, label: "hair drier" },
{ class: 80, label: "toothbrush" }
];
// src/object/centernet.ts
var model6;
var inputSize4 = 0;
var last5 = [];
var lastTime6 = 0;
var skipped6 = Number.MAX_SAFE_INTEGER;
async function load6(config3) {
if (env.initial)
model6 = null;
if (!model6) {
model6 = await loadModel(config3.object.modelPath);
const inputs = Object.values(model6.modelSignature["inputs"]);
inputSize4 = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : 0;
} else if (config3.debug)
log("cached model:", model6["modelUrl"]);
return model6;
}
async function process3(res, outputShape, config3) {
if (!res)
return [];
const t = {};
const results = [];
const detections = await res.array();
t.squeeze = br(res);
const arr = Bn(t.squeeze, 6, 1);
t.stack = es([arr[1], arr[0], arr[3], arr[2]], 1);
t.boxes = br(t.stack);
t.scores = br(arr[4]);
t.classes = br(arr[5]);
De([res, ...arr]);
t.nms = await Kn.nonMaxSuppressionAsync(t.boxes, t.scores, config3.object.maxDetected, config3.object.iouThreshold, config3.object.minConfidence || 0);
const nms = await t.nms.data();
let i = 0;
for (const id2 of Array.from(nms)) {
const score = Math.trunc(100 * detections[0][id2][4]) / 100;
const classVal = detections[0][id2][5];
const label = labels[classVal].label;
const [x, y] = [
detections[0][id2][0] / inputSize4,
detections[0][id2][1] / inputSize4
];
const boxRaw = [
x,
y,
detections[0][id2][2] / inputSize4 - x,
detections[0][id2][3] / inputSize4 - y
];
const box = [
Math.trunc(boxRaw[0] * outputShape[0]),
Math.trunc(boxRaw[1] * outputShape[1]),
Math.trunc(boxRaw[2] * outputShape[0]),
Math.trunc(boxRaw[3] * outputShape[1])
];
results.push({ id: i++, score, class: classVal, label, box, boxRaw });
}
Object.keys(t).forEach((tensor) => De(t[tensor]));
return results;
}
async function predict6(input, config3) {
const skipTime = (config3.object.skipTime || 0) > now() - lastTime6;
const skipFrame = skipped6 < (config3.object.skipFrames || 0);
if (config3.skipAllowed && skipTime && skipFrame && last5.length > 0) {
skipped6++;
return last5;
}
skipped6 = 0;
return new Promise(async (resolve) => {
const outputSize2 = [input.shape[2] || 0, input.shape[1] || 0];
const resize = Kn.resizeBilinear(input, [inputSize4, inputSize4]);
const objectT = config3.object.enabled ? model6 == null ? void 0 : model6.execute(resize, ["tower_0/detections"]) : null;
lastTime6 = now();
De(resize);
const obj = await process3(objectT, outputSize2, config3);
last5 = obj;
resolve(obj);
});
}
// src/body/efficientposecoords.ts
var efficientposecoords_exports = {};
__export(efficientposecoords_exports, {
connected: () => connected2,
kpt: () => kpt2
});
var kpt2 = [
"head",
"neck",
"rightShoulder",
"rightElbow",
"rightWrist",
"chest",
"leftShoulder",
"leftElbow",
"leftWrist",
"bodyCenter",
"rightHip",
"rightKnee",
"rightAnkle",
"leftHip",
"leftKnee",
"leftAnkle"
];
var connected2 = {
leftLeg: ["leftHip", "leftKnee", "leftAnkle"],
rightLeg: ["rightHip", "rightKnee", "rightAnkle"],
torso: ["leftShoulder", "rightShoulder", "rightHip", "leftHip", "leftShoulder"],
leftArm: ["leftShoulder", "leftElbow", "leftWrist"],
rightArm: ["rightShoulder", "rightElbow", "rightWrist"],
head: []
};
// src/body/efficientpose.ts
var model7;
var lastTime7 = 0;
var cache2 = { id: 0, keypoints: [], box: [0, 0, 0, 0], boxRaw: [0, 0, 0, 0], score: 0, annotations: {} };
var skipped7 = Number.MAX_SAFE_INTEGER;
async function load7(config3) {
if (env.initial)
model7 = null;
if (!model7)
model7 = await loadModel(config3.body.modelPath);
else if (config3.debug)
log("cached model:", model7["modelUrl"]);
return model7;
}
async function max2d(inputs, minScore) {
const [width, height] = inputs.shape;
const reshaped = U(inputs, [height * width]);
const max = As(reshaped, 0);
const newScore = (await max.data())[0];
De([reshaped, max]);
if (newScore > minScore) {
const coordinates = Yu(reshaped, 0);
const mod = XD(coordinates, width);
const x = (await mod.data())[0];
const div = xe(coordinates, we(width, "int32"));
const y = (await div.data())[0];
De([mod, div]);
return [x, y, newScore];
}
return [0, 0, newScore];
}
async function predict7(image, config3) {
const skipTime = (config3.body.skipTime || 0) > now() - lastTime7;
const skipFrame = skipped7 < (config3.body.skipFrames || 0);
if (config3.skipAllowed && skipTime && skipFrame && Object.keys(cache2.keypoints).length > 0) {
skipped7++;
return [cache2];
}
skipped7 = 0;
return new Promise(async (resolve) => {
var _a2;
const tensor = q(() => {
if (!(model7 == null ? void 0 : model7.inputs[0].shape))
return null;
const resize = Kn.resizeBilinear(image, [model7.inputs[0].shape[2], model7.inputs[0].shape[1]], false);
const enhance2 = V(resize, constants.tf2);
const norm = ge(enhance2, constants.tf1);
return norm;
});
let resT;
if (config3.body.enabled)
resT = model7 == null ? void 0 : model7.execute(tensor);
lastTime7 = now();
De(tensor);
if (resT) {
cache2.keypoints.length = 0;
const squeeze = resT.squeeze();
De(resT);
const stack = squeeze.unstack(2);
De(squeeze);
for (let id2 = 0; id2 < stack.length; id2++) {
const [x10, y10, partScore] = await max2d(stack[id2], config3.body.minConfidence);
if (partScore > (((_a2 = config3.body) == null ? void 0 : _a2.minConfidence) || 0)) {
cache2.keypoints.push({
score: Math.round(100 * partScore) / 100,
part: kpt2[id2],
positionRaw: [
x10 / model7.inputs[0].shape[2],
y10 / model7.inputs[0].shape[1]
],
position: [
Math.round(image.shape[2] * x10 / model7.inputs[0].shape[2]),
Math.round(image.shape[1] * y10 / model7.inputs[0].shape[1])
]
});
}
}
stack.forEach((s) => De(s));
}
cache2.score = cache2.keypoints.reduce((prev, curr) => curr.score > prev ? curr.score : prev, 0);
const x = cache2.keypoints.map((a) => a.position[0]);
const y = cache2.keypoints.map((a) => a.position[1]);
cache2.box = [
Math.min(...x),
Math.min(...y),
Math.max(...x) - Math.min(...x),
Math.max(...y) - Math.min(...y)
];
const xRaw = cache2.keypoints.map((a) => a.positionRaw[0]);
const yRaw = cache2.keypoints.map((a) => a.positionRaw[1]);
cache2.boxRaw = [
Math.min(...xRaw),
Math.min(...yRaw),
Math.max(...xRaw) - Math.min(...xRaw),
Math.max(...yRaw) - Math.min(...yRaw)
];
for (const [name, indexes] of Object.entries(connected2)) {
const pt2 = [];
for (let i = 0; i < indexes.length - 1; i++) {
const pt0 = cache2.keypoints.find((kpt4) => kpt4.part === indexes[i]);
const pt1 = cache2.keypoints.find((kpt4) => kpt4.part === indexes[i + 1]);
if (pt0 && pt1 && pt0.score > (config3.body.minConfidence || 0) && pt1.score > (config3.body.minConfidence || 0))
pt2.push([pt0.position, pt1.position]);
}
cache2.annotations[name] = pt2;
}
resolve([cache2]);
});
}
// src/gear/emotion.ts
var annotations = ["angry", "disgust", "fear", "happy", "sad", "surprise", "neutral"];
var model8;
var last6 = [];
var lastCount5 = 0;
var lastTime8 = 0;
var skipped8 = Number.MAX_SAFE_INTEGER;
async function load8(config3) {
var _a2;
if (env.initial)
model8 = null;
if (!model8)
model8 = await loadModel((_a2 = config3.face.emotion) == null ? void 0 : _a2.modelPath);
else if (config3.debug)
log("cached model:", model8["modelUrl"]);
return model8;
}
async function predict8(image, config3, idx, count2) {
var _a2, _b2;
if (!model8)
return [];
const skipFrame = skipped8 < (((_a2 = config3.face.emotion) == null ? void 0 : _a2.skipFrames) || 0);
const skipTime = (((_b2 = config3.face.emotion) == null ? void 0 : _b2.skipTime) || 0) > now() - lastTime8;
if (config3.skipAllowed && skipTime && skipFrame && lastCount5 === count2 && last6[idx] && last6[idx].length > 0) {
skipped8++;
return last6[idx];
}
skipped8 = 0;
return new Promise(async (resolve) => {
var _a3, _b3;
const obj = [];
if ((_a3 = config3.face.emotion) == null ? void 0 : _a3.enabled) {
const t = {};
const inputSize10 = (model8 == null ? void 0 : model8.inputs[0].shape) ? model8.inputs[0].shape[2] : 0;
t.resize = Kn.resizeBilinear(image, [inputSize10, inputSize10], false);
t.channels = V(t.resize, constants.rgb);
t.grayscale = ve(t.channels, 3, true);
t.grayscaleSub = ge(t.grayscale, constants.tf05);
t.grayscaleMul = V(t.grayscaleSub, constants.tf2);
t.emotion = model8 == null ? void 0 : model8.execute(t.grayscaleMul);
lastTime8 = now();
const data = await t.emotion.data();
for (let i = 0; i < data.length; i++) {
if (data[i] > (((_b3 = config3.face.emotion) == null ? void 0 : _b3.minConfidence) || 0))
obj.push({ score: Math.min(0.99, Math.trunc(100 * data[i]) / 100), emotion: annotations[i] });
}
obj.sort((a, b) => b.score - a.score);
Object.keys(t).forEach((tensor) => De(t[tensor]));
}
last6[idx] = obj;
lastCount5 = count2;
resolve(obj);
});
}
// src/face/mobilefacenet.ts
var model9;
var last7 = [];
var lastCount6 = 0;
var lastTime9 = 0;
var skipped9 = Number.MAX_SAFE_INTEGER;
async function load9(config3) {
if (env.initial)
model9 = null;
if (!model9)
model9 = await loadModel(config3.face["mobilefacenet"].modelPath);
else if (config3.debug)
log("cached model:", model9["modelUrl"]);
return model9;
}
async function predict9(input, config3, idx, count2) {
var _a2, _b2;
if (!model9)
return [];
const skipFrame = skipped9 < (((_a2 = config3.face["embedding"]) == null ? void 0 : _a2.skipFrames) || 0);
const skipTime = (((_b2 = config3.face["embedding"]) == null ? void 0 : _b2.skipTime) || 0) > now() - lastTime9;
if (config3.skipAllowed && skipTime && skipFrame && lastCount6 === count2 && last7[idx]) {
skipped9++;
return last7[idx];
}
return new Promise(async (resolve) => {
var _a3;
let data = [];
if (((_a3 = config3.face["embedding"]) == null ? void 0 : _a3.enabled) && (model9 == null ? void 0 : model9.inputs[0].shape)) {
const t = {};
t.crop = Kn.resizeBilinear(input, [model9.inputs[0].shape[2], model9.inputs[0].shape[1]], false);
t.data = model9 == null ? void 0 : model9.execute(t.crop);
const output = await t.data.data();
data = Array.from(output);
}
last7[idx] = data;
lastCount6 = count2;
lastTime9 = now();
resolve(data);
});
}
// src/face/iris.ts
var model10;
var inputSize5 = 0;
var irisEnlarge = 2.3;
var leftOutline = meshAnnotations["leftEyeLower0"];
var rightOutline = meshAnnotations["rightEyeLower0"];
var eyeLandmarks = {
leftBounds: [leftOutline[0], leftOutline[leftOutline.length - 1]],
rightBounds: [rightOutline[0], rightOutline[rightOutline.length - 1]]
};
var irisLandmarks = {
upperCenter: 3,
lowerCenter: 4,
index: 71,
numCoordinates: 76
};
async function load10(config3) {
var _a2;
if (env.initial)
model10 = null;
if (!model10)
model10 = await loadModel((_a2 = config3.face.iris) == null ? void 0 : _a2.modelPath);
else if (config3.debug)
log("cached model:", model10["modelUrl"]);
inputSize5 = model10.inputs[0].shape ? model10.inputs[0].shape[2] : 0;
if (inputSize5 === -1)
inputSize5 = 64;
return model10;
}
function replaceIrisCoords(rawCoords, newCoords, prefix, keys) {
for (let i = 0; i < irisIndices.length; i++) {
const { key, indices } = irisIndices[i];
const originalIndices = meshAnnotations[`${prefix}${key}`];
if (!keys || keys.includes(key)) {
for (let j = 0; j < indices.length; j++) {
const index2 = indices[j];
rawCoords[originalIndices[j]] = [
newCoords[index2][0],
newCoords[index2][1],
(newCoords[index2][2] + rawCoords[originalIndices[j]][2]) / 2
];
}
}
}
}
var getLeftToRightEyeDepthDifference = (rawCoords) => {
const leftEyeZ = rawCoords[eyeLandmarks.leftBounds[0]][2];
const rightEyeZ = rawCoords[eyeLandmarks.rightBounds[0]][2];
return leftEyeZ - rightEyeZ;
};
var getEyeBox = (rawCoords, face4, eyeInnerCornerIndex, eyeOuterCornerIndex, meshSize, flip = false) => {
const box = squarifyBox(enlargeBox(calculateLandmarksBoundingBox([rawCoords[eyeInnerCornerIndex], rawCoords[eyeOuterCornerIndex]]), irisEnlarge));
const boxSize = getBoxSize(box);
let crop = Kn.cropAndResize(face4, [[
box.startPoint[1] / meshSize,
box.startPoint[0] / meshSize,
box.endPoint[1] / meshSize,
box.endPoint[0] / meshSize
]], [0], [inputSize5, inputSize5]);
if (flip && env.kernels.includes("flipleftright")) {
const flipped = Kn.flipLeftRight(crop);
De(crop);
crop = flipped;
}
return { box, boxSize, crop };
};
var getEyeCoords = (eyeData, eyeBox, eyeBoxSize, flip = false) => {
const eyeRawCoords = [];
for (let i = 0; i < irisLandmarks.numCoordinates; i++) {
const x = eyeData[i * 3];
const y = eyeData[i * 3 + 1];
const z10 = eyeData[i * 3 + 2];
eyeRawCoords.push([
(flip ? 1 - x / inputSize5 : x / inputSize5) * eyeBoxSize[0] + eyeBox.startPoint[0],
y / inputSize5 * eyeBoxSize[1] + eyeBox.startPoint[1],
z10
]);
}
return { rawCoords: eyeRawCoords, iris: eyeRawCoords.slice(irisLandmarks.index) };
};
var getAdjustedIrisCoords = (rawCoords, irisCoords, direction) => {
const upperCenterZ = rawCoords[meshAnnotations[`${direction}EyeUpper0`][irisLandmarks.upperCenter]][2];
const lowerCenterZ = rawCoords[meshAnnotations[`${direction}EyeLower0`][irisLandmarks.lowerCenter]][2];
const averageZ = (upperCenterZ + lowerCenterZ) / 2;
return irisCoords.map((coord, i) => {
let z10 = averageZ;
if (i === 2) {
z10 = upperCenterZ;
} else if (i === 4) {
z10 = lowerCenterZ;
}
return [coord[0], coord[1], z10];
});
};
async function augmentIris(rawCoords, face4, config3, meshSize) {
if (!model10) {
if (config3.debug)
log("face mesh iris detection requested, but model is not loaded");
return rawCoords;
}
const { box: leftEyeBox, boxSize: leftEyeBoxSize, crop: leftEyeCrop } = getEyeBox(rawCoords, face4, eyeLandmarks.leftBounds[0], eyeLandmarks.leftBounds[1], meshSize, true);
const { box: rightEyeBox, boxSize: rightEyeBoxSize, crop: rightEyeCrop } = getEyeBox(rawCoords, face4, eyeLandmarks.rightBounds[0], eyeLandmarks.rightBounds[1], meshSize, true);
const combined = Ft([leftEyeCrop, rightEyeCrop]);
De(leftEyeCrop);
De(rightEyeCrop);
const eyePredictions = model10.execute(combined);
De(combined);
const eyePredictionsData = await eyePredictions.data();
De(eyePredictions);
const leftEyeData = eyePredictionsData.slice(0, irisLandmarks.numCoordinates * 3);
const { rawCoords: leftEyeRawCoords, iris: leftIrisRawCoords } = getEyeCoords(leftEyeData, leftEyeBox, leftEyeBoxSize, true);
const rightEyeData = eyePredictionsData.slice(irisLandmarks.numCoordinates * 3);
const { rawCoords: rightEyeRawCoords, iris: rightIrisRawCoords } = getEyeCoords(rightEyeData, rightEyeBox, rightEyeBoxSize, false);
const leftToRightEyeDepthDifference = getLeftToRightEyeDepthDifference(rawCoords);
if (Math.abs(leftToRightEyeDepthDifference) < 30) {
replaceIrisCoords(rawCoords, leftEyeRawCoords, "left", null);
replaceIrisCoords(rawCoords, rightEyeRawCoords, "right", null);
} else if (leftToRightEyeDepthDifference < 1) {
replaceIrisCoords(rawCoords, leftEyeRawCoords, "left", ["EyeUpper0", "EyeLower0"]);
} else {
replaceIrisCoords(rawCoords, rightEyeRawCoords, "right", ["EyeUpper0", "EyeLower0"]);
}
const adjustedLeftIrisCoords = getAdjustedIrisCoords(rawCoords, leftIrisRawCoords, "left");
const adjustedRightIrisCoords = getAdjustedIrisCoords(rawCoords, rightIrisRawCoords, "right");
const newCoords = rawCoords.concat(adjustedLeftIrisCoords).concat(adjustedRightIrisCoords);
return newCoords;
}
// src/face/constants.ts
var LIPS_CONNECTIONS = [
[61, 146],
[146, 91],
[91, 181],
[181, 84],
[84, 17],
[17, 314],
[314, 405],
[405, 321],
[321, 375],
[375, 291],
[61, 185],
[185, 40],
[40, 39],
[39, 37],
[37, 0],
[0, 267],
[267, 269],
[269, 270],
[270, 409],
[409, 291],
[78, 95],
[95, 88],
[88, 178],
[178, 87],
[87, 14],
[14, 317],
[317, 402],
[402, 318],
[318, 324],
[324, 308],
[78, 191],
[191, 80],
[80, 81],
[81, 82],
[82, 13],
[13, 312],
[312, 311],
[311, 310],
[310, 415],
[415, 308]
];
var LEFT_EYE_CONNECTIONS = [[263, 249], [249, 390], [390, 373], [373, 374], [374, 380], [380, 381], [381, 382], [382, 362], [263, 466], [466, 388], [388, 387], [387, 386], [386, 385], [385, 384], [384, 398], [398, 362]];
var LEFT_EYEBROW_CONNECTIONS = [[276, 283], [283, 282], [282, 295], [295, 285], [300, 293], [293, 334], [334, 296], [296, 336]];
var LEFT_IRIS_CONNECTIONS = [[474, 475], [475, 476], [476, 477], [477, 474]];
var RIGHT_EYE_CONNECTIONS = [[33, 7], [7, 163], [163, 144], [144, 145], [145, 153], [153, 154], [154, 155], [155, 133], [33, 246], [246, 161], [161, 160], [160, 159], [159, 158], [158, 157], [157, 173], [173, 133]];
var RIGHT_EYEBROW_CONNECTIONS = [[46, 53], [53, 52], [52, 65], [65, 55], [70, 63], [63, 105], [105, 66], [66, 107]];
var RIGHT_IRIS_CONNECTIONS = [[469, 470], [470, 471], [471, 472], [472, 469]];
var FACE_OVAL_CONNECTIONS = [
[10, 338],
[338, 297],
[297, 332],
[332, 284],
[284, 251],
[251, 389],
[389, 356],
[356, 454],
[454, 323],
[323, 361],
[361, 288],
[288, 397],
[397, 365],
[365, 379],
[379, 378],
[378, 400],
[400, 377],
[377, 152],
[152, 148],
[148, 176],
[176, 149],
[149, 150],
[150, 136],
[136, 172],
[172, 58],
[58, 132],
[132, 93],
[93, 234],
[234, 127],
[127, 162],
[162, 21],
[21, 54],
[54, 103],
[103, 67],
[67, 109],
[109, 10]
];
function connectionsToIndices2(connections) {
const indices = connections.map((connection) => connection[0]);
indices.push(connections[connections.length - 1][1]);
return indices;
}
var MEDIAPIPE_FACE_MESH_KEYPOINTS_BY_CONTOUR = {
lips: connectionsToIndices2(LIPS_CONNECTIONS),
leftEye: connectionsToIndices2(LEFT_EYE_CONNECTIONS),
leftEyebrow: connectionsToIndices2(LEFT_EYEBROW_CONNECTIONS),
leftIris: connectionsToIndices2(LEFT_IRIS_CONNECTIONS),
rightEye: connectionsToIndices2(RIGHT_EYE_CONNECTIONS),
rightEyebrow: connectionsToIndices2(RIGHT_EYEBROW_CONNECTIONS),
rightIris: connectionsToIndices2(RIGHT_IRIS_CONNECTIONS),
faceOval: connectionsToIndices2(FACE_OVAL_CONNECTIONS)
};
var indexLabelPairs = Object.entries(MEDIAPIPE_FACE_MESH_KEYPOINTS_BY_CONTOUR).map(([label, indices]) => indices.map((index2) => [index2, label])).flat();
var MEDIAPIPE_FACE_MESH_KEYPOINTS = new Map(indexLabelPairs);
var LANDMARKS_REFINEMENT_LIPS_CONFIG = [
61,
146,
91,
181,
84,
17,
314,
405,
321,
375,
291,
185,
40,
39,
37,
0,
267,
269,
270,
409,
78,
95,
88,
178,
87,
14,
317,
402,
318,
324,
308,
191,
80,
81,
82,
13,
312,
311,
310,
415,
76,
77,
90,
180,
85,
16,
315,
404,
320,
307,
306,
184,
74,
73,
72,
11,
302,
303,
304,
408,
62,
96,
89,
179,
86,
15,
316,
403,
319,
325,
292,
183,
42,
41,
38,
12,
268,
271,
272,
407
];
var LANDMARKS_REFINEMENT_LEFT_EYE_CONFIG = [
33,
7,
163,
144,
145,
153,
154,
155,
133,
246,
161,
160,
159,
158,
157,
173,
130,
25,
110,
24,
23,
22,
26,
112,
243,
247,
30,
29,
27,
28,
56,
190,
226,
31,
228,
229,
230,
231,
232,
233,
244,
113,
225,
224,
223,
222,
221,
189,
35,
124,
46,
53,
52,
65,
143,
111,
117,
118,
119,
120,
121,
128,
245,
156,
70,
63,
105,
66,
107,
55,
193
];
var LANDMARKS_REFINEMENT_RIGHT_EYE_CONFIG = [
263,
249,
390,
373,
374,
380,
381,
382,
362,
466,
388,
387,
386,
385,
384,
398,
359,
255,
339,
254,
253,
252,
256,
341,
463,
467,
260,
259,
257,
258,
286,
414,
446,
261,
448,
449,
450,
451,
452,
453,
464,
342,
445,
444,
443,
442,
441,
413,
265,
353,
276,
283,
282,
295,
372,
340,
346,
347,
348,
349,
350,
357,
465,
383,
300,
293,
334,
296,
336,
285,
417
];
// src/face/attention.ts
async function augment(rawCoords, results) {
const t = {
lips: await results.filter((r) => r.size === 160)[0].data(),
irisL: await results.filter((r) => r.size === 10)[0].data(),
eyeL: await results.filter((r) => r.size === 142)[0].data(),
irisR: await results.filter((r) => r.size === 10)[1].data(),
eyeR: await results.filter((r) => r.size === 142)[1].data()
};
const irisLDepth = LANDMARKS_REFINEMENT_LEFT_EYE_CONFIG.reduce((prev, curr) => prev += rawCoords[curr][2], 0) / LANDMARKS_REFINEMENT_LEFT_EYE_CONFIG.length;
for (let i = 0; i < t.irisL.length / 2; i++)
rawCoords.push([t.irisL[2 * i + 0], t.irisL[2 * i + 1], irisLDepth]);
const irisRDepth = LANDMARKS_REFINEMENT_RIGHT_EYE_CONFIG.reduce((prev, curr) => prev += rawCoords[curr][2], 0) / LANDMARKS_REFINEMENT_RIGHT_EYE_CONFIG.length;
for (let i = 0; i < t.irisR.length / 2; i++)
rawCoords.push([t.irisR[2 * i + 0], t.irisR[2 * i + 1], irisRDepth]);
for (let i = 0; i < t.eyeL.length / 2; i++)
rawCoords[LANDMARKS_REFINEMENT_LEFT_EYE_CONFIG[i]] = [t.eyeL[2 * i + 0], t.eyeL[2 * i + 1], rawCoords[LANDMARKS_REFINEMENT_LEFT_EYE_CONFIG[i]][2]];
for (let i = 0; i < t.eyeR.length / 2; i++)
rawCoords[LANDMARKS_REFINEMENT_RIGHT_EYE_CONFIG[i]] = [t.eyeR[2 * i + 0], t.eyeR[2 * i + 1], rawCoords[LANDMARKS_REFINEMENT_RIGHT_EYE_CONFIG[i]][2]];
for (let i = 0; i < t.lips.length / 2; i++)
rawCoords[LANDMARKS_REFINEMENT_LIPS_CONFIG[i]] = [t.lips[2 * i + 0], t.lips[2 * i + 1], rawCoords[LANDMARKS_REFINEMENT_LIPS_CONFIG[i]][2]];
return rawCoords;
}
// src/face/facemesh.ts
var cache3 = {
boxes: [],
skipped: Number.MAX_SAFE_INTEGER,
timestamp: 0
};
var model11 = null;
var inputSize6 = 0;
async function predict10(input, config3) {
var _a2, _b2, _c, _d2, _e2, _f, _g2, _h, _i2, _j2, _k2;
const skipTime = (((_a2 = config3.face.detector) == null ? void 0 : _a2.skipTime) || 0) > now() - cache3.timestamp;
const skipFrame = cache3.skipped < (((_b2 = config3.face.detector) == null ? void 0 : _b2.skipFrames) || 0);
if (!config3.skipAllowed || !skipTime || !skipFrame || cache3.boxes.length === 0) {
cache3.boxes = await getBoxes(input, config3);
cache3.timestamp = now();
cache3.skipped = 0;
} else {
cache3.skipped++;
}
const faces = [];
const newCache = [];
let id2 = 0;
for (let i = 0; i < cache3.boxes.length; i++) {
const box = cache3.boxes[i];
let angle = 0;
let rotationMatrix;
const face4 = {
id: id2++,
mesh: [],
meshRaw: [],
box: [0, 0, 0, 0],
boxRaw: [0, 0, 0, 0],
score: 0,
boxScore: 0,
faceScore: 0,
annotations: {}
};
[angle, rotationMatrix, face4.tensor] = correctFaceRotation((_c = config3.face.detector) == null ? void 0 : _c.rotation, box, input, ((_d2 = config3.face.mesh) == null ? void 0 : _d2.enabled) ? inputSize6 : size());
if ((_e2 = config3 == null ? void 0 : config3.filter) == null ? void 0 : _e2.equalization) {
const equilized = await histogramEqualization(face4.tensor);
De(face4.tensor);
face4.tensor = equilized;
}
face4.boxScore = Math.round(100 * box.confidence) / 100;
if (!((_f = config3.face.mesh) == null ? void 0 : _f.enabled)) {
face4.box = clampBox(box, input);
face4.boxRaw = getRawBox(box, input);
face4.score = face4.boxScore;
face4.mesh = box.landmarks.map((pt2) => [
(box.startPoint[0] + box.endPoint[0]) / 2 + (box.endPoint[0] + box.startPoint[0]) * pt2[0] / size(),
(box.startPoint[1] + box.endPoint[1]) / 2 + (box.endPoint[1] + box.startPoint[1]) * pt2[1] / size()
]);
face4.meshRaw = face4.mesh.map((pt2) => [pt2[0] / (input.shape[2] || 0), pt2[1] / (input.shape[1] || 0), (pt2[2] || 0) / inputSize6]);
for (const key of Object.keys(blazeFaceLandmarks)) {
face4.annotations[key] = [face4.mesh[blazeFaceLandmarks[key]]];
}
} else if (!model11) {
if (config3.debug)
log("face mesh detection requested, but model is not loaded");
} else {
const results = model11.execute(face4.tensor);
const confidenceT = results.find((t) => t.shape[t.shape.length - 1] === 1);
const meshT = results.find((t) => t.shape[t.shape.length - 1] === 1404);
const faceConfidence = await confidenceT.data();
face4.faceScore = Math.round(100 * faceConfidence[0]) / 100;
const coordsReshaped = U(meshT, [-1, 3]);
let rawCoords = await coordsReshaped.array();
if (face4.faceScore < (((_g2 = config3.face.detector) == null ? void 0 : _g2.minConfidence) || 1)) {
box.confidence = face4.faceScore;
if ((_h = config3.face.mesh) == null ? void 0 : _h.keepInvalid) {
face4.box = clampBox(box, input);
face4.boxRaw = getRawBox(box, input);
face4.score = face4.boxScore;
face4.mesh = box.landmarks.map((pt2) => [
(box.startPoint[0] + box.endPoint[0]) / 2 + (box.endPoint[0] + box.startPoint[0]) * pt2[0] / size(),
(box.startPoint[1] + box.endPoint[1]) / 2 + (box.endPoint[1] + box.startPoint[1]) * pt2[1] / size()
]);
face4.meshRaw = face4.mesh.map((pt2) => [pt2[0] / (input.shape[2] || 0), pt2[1] / (input.shape[1] || 0), (pt2[2] || 0) / inputSize6]);
for (const key of Object.keys(blazeFaceLandmarks)) {
face4.annotations[key] = [face4.mesh[blazeFaceLandmarks[key]]];
}
}
} else {
if ((_i2 = config3.face.attention) == null ? void 0 : _i2.enabled) {
rawCoords = await augment(rawCoords, results);
} else if ((_j2 = config3.face.iris) == null ? void 0 : _j2.enabled) {
rawCoords = await augmentIris(rawCoords, face4.tensor, config3, inputSize6);
}
face4.mesh = transformRawCoords(rawCoords, box, angle, rotationMatrix, inputSize6);
face4.meshRaw = face4.mesh.map((pt2) => [pt2[0] / (input.shape[2] || 0), pt2[1] / (input.shape[1] || 0), (pt2[2] || 0) / inputSize6]);
for (const key of Object.keys(meshAnnotations))
face4.annotations[key] = meshAnnotations[key].map((index2) => face4.mesh[index2]);
face4.score = face4.faceScore;
const calculatedBox = { ...calculateFaceBox(face4.mesh, box), confidence: box.confidence, landmarks: box.landmarks };
face4.box = clampBox(calculatedBox, input);
face4.boxRaw = getRawBox(calculatedBox, input);
newCache.push(calculatedBox);
}
De([...results, coordsReshaped]);
}
if (face4.score > (((_k2 = config3.face.detector) == null ? void 0 : _k2.minConfidence) || 1))
faces.push(face4);
else
De(face4.tensor);
}
cache3.boxes = newCache;
return faces;
}
async function load11(config3) {
var _a2, _b2, _c, _d2, _e2, _f;
if (env.initial)
model11 = null;
if (((_b2 = (_a2 = config3 == null ? void 0 : config3.face) == null ? void 0 : _a2.attention) == null ? void 0 : _b2.enabled) && (model11 == null ? void 0 : model11.signature)) {
if (Object.keys(((_c = model11 == null ? void 0 : model11.signature) == null ? void 0 : _c.outputs) || {}).length < 6)
model11 = null;
}
if (!model11) {
if ((_d2 = config3.face.attention) == null ? void 0 : _d2.enabled)
model11 = await loadModel((_e2 = config3.face.attention) == null ? void 0 : _e2.modelPath);
else
model11 = await loadModel((_f = config3.face.mesh) == null ? void 0 : _f.modelPath);
} else if (config3.debug) {
log("cached model:", model11["modelUrl"]);
}
inputSize6 = model11.inputs[0].shape ? model11.inputs[0].shape[2] : 0;
return model11;
}
var triangulation = TRI468;
var uvmap = UV468;
// src/face/faceres.ts
var model12;
var last8 = [];
var lastTime10 = 0;
var lastCount7 = 0;
var skipped10 = Number.MAX_SAFE_INTEGER;
async function load12(config3) {
var _a2;
if (env.initial)
model12 = null;
if (!model12)
model12 = await loadModel((_a2 = config3.face.description) == null ? void 0 : _a2.modelPath);
else if (config3.debug)
log("cached model:", model12["modelUrl"]);
return model12;
}
function enhance(input) {
const tensor = input.image || input.tensor || input;
if (!(model12 == null ? void 0 : model12.inputs[0].shape))
return tensor;
const crop = Kn.resizeBilinear(tensor, [model12.inputs[0].shape[2], model12.inputs[0].shape[1]], false);
const norm = V(crop, constants.tf255);
De(crop);
return norm;
}
async function predict11(image, config3, idx, count2) {
var _a2, _b2, _c, _d2;
if (!model12)
return { age: 0, gender: "unknown", genderScore: 0, descriptor: [] };
const skipFrame = skipped10 < (((_a2 = config3.face.description) == null ? void 0 : _a2.skipFrames) || 0);
const skipTime = (((_b2 = config3.face.description) == null ? void 0 : _b2.skipTime) || 0) > now() - lastTime10;
if (config3.skipAllowed && skipFrame && skipTime && lastCount7 === count2 && ((_c = last8[idx]) == null ? void 0 : _c.age) && ((_d2 = last8[idx]) == null ? void 0 : _d2.age) > 0) {
skipped10++;
return last8[idx];
}
skipped10 = 0;
return new Promise(async (resolve) => {
var _a3, _b3;
const obj = {
age: 0,
gender: "unknown",
genderScore: 0,
descriptor: []
};
if ((_a3 = config3.face.description) == null ? void 0 : _a3.enabled) {
const enhanced = enhance(image);
const resT = model12 == null ? void 0 : model12.execute(enhanced);
lastTime10 = now();
De(enhanced);
const genderT = await resT.find((t) => t.shape[1] === 1);
const gender = await genderT.data();
const confidence = Math.trunc(200 * Math.abs(gender[0] - 0.5)) / 100;
if (confidence > (((_b3 = config3.face.description) == null ? void 0 : _b3.minConfidence) || 0)) {
obj.gender = gender[0] <= 0.5 ? "female" : "male";
obj.genderScore = Math.min(0.99, confidence);
}
const argmax = Yu(resT.find((t) => t.shape[1] === 100), 1);
const age = (await argmax.data())[0];
De(argmax);
const ageT = resT.find((t) => t.shape[1] === 100);
const all2 = await ageT.data();
obj.age = Math.round(all2[age - 1] > all2[age + 1] ? 10 * age - 100 * all2[age - 1] : 10 * age + 100 * all2[age + 1]) / 10;
const desc = resT.find((t) => t.shape[1] === 1024);
const descriptor = desc ? await desc.data() : [];
obj.descriptor = Array.from(descriptor);
resT.forEach((t) => De(t));
}
last8[idx] = obj;
lastCount7 = count2;
resolve(obj);
});
}
// src/hand/handposeutil.ts
function getBoxSize2(box) {
return [
Math.abs(box.endPoint[0] - box.startPoint[0]),
Math.abs(box.endPoint[1] - box.startPoint[1])
];
}
function getBoxCenter2(box) {
return [
box.startPoint[0] + (box.endPoint[0] - box.startPoint[0]) / 2,
box.startPoint[1] + (box.endPoint[1] - box.startPoint[1]) / 2
];
}
function cutBoxFromImageAndResize(box, image, cropSize) {
const h = image.shape[1];
const w10 = image.shape[2];
const boxes = [[
box.startPoint[1] / h,
box.startPoint[0] / w10,
box.endPoint[1] / h,
box.endPoint[0] / w10
]];
return Kn.cropAndResize(image, boxes, [0], cropSize);
}
function scaleBoxCoordinates2(box, factor) {
const startPoint = [box.startPoint[0] * factor[0], box.startPoint[1] * factor[1]];
const endPoint = [box.endPoint[0] * factor[0], box.endPoint[1] * factor[1]];
const palmLandmarks = box.palmLandmarks.map((coord) => {
const scaledCoord = [coord[0] * factor[0], coord[1] * factor[1]];
return scaledCoord;
});
return { startPoint, endPoint, palmLandmarks, confidence: box.confidence };
}
function enlargeBox2(box, factor = 1.5) {
const center = getBoxCenter2(box);
const size2 = getBoxSize2(box);
const newHalfSize = [factor * size2[0] / 2, factor * size2[1] / 2];
const startPoint = [center[0] - newHalfSize[0], center[1] - newHalfSize[1]];
const endPoint = [center[0] + newHalfSize[0], center[1] + newHalfSize[1]];
return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };
}
function squarifyBox2(box) {
const centers = getBoxCenter2(box);
const size2 = getBoxSize2(box);
const maxEdge = Math.max(...size2);
const halfSize = maxEdge / 2;
const startPoint = [centers[0] - halfSize, centers[1] - halfSize];
const endPoint = [centers[0] + halfSize, centers[1] + halfSize];
return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };
}
function normalizeRadians2(angle) {
return angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));
}
function computeRotation2(point1, point2) {
const radians = Math.PI / 2 - Math.atan2(-(point2[1] - point1[1]), point2[0] - point1[0]);
return normalizeRadians2(radians);
}
var buildTranslationMatrix2 = (x, y) => [[1, 0, x], [0, 1, y], [0, 0, 1]];
function dot2(v12, v22) {
let product = 0;
for (let i = 0; i < v12.length; i++) {
product += v12[i] * v22[i];
}
return product;
}
function getColumnFrom2DArr2(arr, columnIndex) {
const column = [];
for (let i = 0; i < arr.length; i++) {
column.push(arr[i][columnIndex]);
}
return column;
}
function multiplyTransformMatrices2(mat1, mat2) {
const product = [];
const size2 = mat1.length;
for (let row = 0; row < size2; row++) {
product.push([]);
for (let col = 0; col < size2; col++) {
product[row].push(dot2(mat1[row], getColumnFrom2DArr2(mat2, col)));
}
}
return product;
}
function buildRotationMatrix2(rotation, center) {
const cosA = Math.cos(rotation);
const sinA = Math.sin(rotation);
const rotationMatrix = [[cosA, -sinA, 0], [sinA, cosA, 0], [0, 0, 1]];
const translationMatrix = buildTranslationMatrix2(center[0], center[1]);
const translationTimesRotation = multiplyTransformMatrices2(translationMatrix, rotationMatrix);
const negativeTranslationMatrix = buildTranslationMatrix2(-center[0], -center[1]);
return multiplyTransformMatrices2(translationTimesRotation, negativeTranslationMatrix);
}
function invertTransformMatrix2(matrix) {
const rotationComponent = [[matrix[0][0], matrix[1][0]], [matrix[0][1], matrix[1][1]]];
const translationComponent = [matrix[0][2], matrix[1][2]];
const invertedTranslation = [
-dot2(rotationComponent[0], translationComponent),
-dot2(rotationComponent[1], translationComponent)
];
return [
rotationComponent[0].concat(invertedTranslation[0]),
rotationComponent[1].concat(invertedTranslation[1]),
[0, 0, 1]
];
}
function rotatePoint2(homogeneousCoordinate, rotationMatrix) {
return [
dot2(homogeneousCoordinate, rotationMatrix[0]),
dot2(homogeneousCoordinate, rotationMatrix[1])
];
}
// src/hand/handposeanchors.ts
var anchors2 = [
{ x: 0.015625, y: 0.015625 },
{ x: 0.015625, y: 0.015625 },
{ x: 0.046875, y: 0.015625 },
{ x: 0.046875, y: 0.015625 },
{ x: 0.078125, y: 0.015625 },
{ x: 0.078125, y: 0.015625 },
{ x: 0.109375, y: 0.015625 },
{ x: 0.109375, y: 0.015625 },
{ x: 0.140625, y: 0.015625 },
{ x: 0.140625, y: 0.015625 },
{ x: 0.171875, y: 0.015625 },
{ x: 0.171875, y: 0.015625 },
{ x: 0.203125, y: 0.015625 },
{ x: 0.203125, y: 0.015625 },
{ x: 0.234375, y: 0.015625 },
{ x: 0.234375, y: 0.015625 },
{ x: 0.265625, y: 0.015625 },
{ x: 0.265625, y: 0.015625 },
{ x: 0.296875, y: 0.015625 },
{ x: 0.296875, y: 0.015625 },
{ x: 0.328125, y: 0.015625 },
{ x: 0.328125, y: 0.015625 },
{ x: 0.359375, y: 0.015625 },
{ x: 0.359375, y: 0.015625 },
{ x: 0.390625, y: 0.015625 },
{ x: 0.390625, y: 0.015625 },
{ x: 0.421875, y: 0.015625 },
{ x: 0.421875, y: 0.015625 },
{ x: 0.453125, y: 0.015625 },
{ x: 0.453125, y: 0.015625 },
{ x: 0.484375, y: 0.015625 },
{ x: 0.484375, y: 0.015625 },
{ x: 0.515625, y: 0.015625 },
{ x: 0.515625, y: 0.015625 },
{ x: 0.546875, y: 0.015625 },
{ x: 0.546875, y: 0.015625 },
{ x: 0.578125, y: 0.015625 },
{ x: 0.578125, y: 0.015625 },
{ x: 0.609375, y: 0.015625 },
{ x: 0.609375, y: 0.015625 },
{ x: 0.640625, y: 0.015625 },
{ x: 0.640625, y: 0.015625 },
{ x: 0.671875, y: 0.015625 },
{ x: 0.671875, y: 0.015625 },
{ x: 0.703125, y: 0.015625 },
{ x: 0.703125, y: 0.015625 },
{ x: 0.734375, y: 0.015625 },
{ x: 0.734375, y: 0.015625 },
{ x: 0.765625, y: 0.015625 },
{ x: 0.765625, y: 0.015625 },
{ x: 0.796875, y: 0.015625 },
{ x: 0.796875, y: 0.015625 },
{ x: 0.828125, y: 0.015625 },
{ x: 0.828125, y: 0.015625 },
{ x: 0.859375, y: 0.015625 },
{ x: 0.859375, y: 0.015625 },
{ x: 0.890625, y: 0.015625 },
{ x: 0.890625, y: 0.015625 },
{ x: 0.921875, y: 0.015625 },
{ x: 0.921875, y: 0.015625 },
{ x: 0.953125, y: 0.015625 },
{ x: 0.953125, y: 0.015625 },
{ x: 0.984375, y: 0.015625 },
{ x: 0.984375, y: 0.015625 },
{ x: 0.015625, y: 0.046875 },
{ x: 0.015625, y: 0.046875 },
{ x: 0.046875, y: 0.046875 },
{ x: 0.046875, y: 0.046875 },
{ x: 0.078125, y: 0.046875 },
{ x: 0.078125, y: 0.046875 },
{ x: 0.109375, y: 0.046875 },
{ x: 0.109375, y: 0.046875 },
{ x: 0.140625, y: 0.046875 },
{ x: 0.140625, y: 0.046875 },
{ x: 0.171875, y: 0.046875 },
{ x: 0.171875, y: 0.046875 },
{ x: 0.203125, y: 0.046875 },
{ x: 0.203125, y: 0.046875 },
{ x: 0.234375, y: 0.046875 },
{ x: 0.234375, y: 0.046875 },
{ x: 0.265625, y: 0.046875 },
{ x: 0.265625, y: 0.046875 },
{ x: 0.296875, y: 0.046875 },
{ x: 0.296875, y: 0.046875 },
{ x: 0.328125, y: 0.046875 },
{ x: 0.328125, y: 0.046875 },
{ x: 0.359375, y: 0.046875 },
{ x: 0.359375, y: 0.046875 },
{ x: 0.390625, y: 0.046875 },
{ x: 0.390625, y: 0.046875 },
{ x: 0.421875, y: 0.046875 },
{ x: 0.421875, y: 0.046875 },
{ x: 0.453125, y: 0.046875 },
{ x: 0.453125, y: 0.046875 },
{ x: 0.484375, y: 0.046875 },
{ x: 0.484375, y: 0.046875 },
{ x: 0.515625, y: 0.046875 },
{ x: 0.515625, y: 0.046875 },
{ x: 0.546875, y: 0.046875 },
{ x: 0.546875, y: 0.046875 },
{ x: 0.578125, y: 0.046875 },
{ x: 0.578125, y: 0.046875 },
{ x: 0.609375, y: 0.046875 },
{ x: 0.609375, y: 0.046875 },
{ x: 0.640625, y: 0.046875 },
{ x: 0.640625, y: 0.046875 },
{ x: 0.671875, y: 0.046875 },
{ x: 0.671875, y: 0.046875 },
{ x: 0.703125, y: 0.046875 },
{ x: 0.703125, y: 0.046875 },
{ x: 0.734375, y: 0.046875 },
{ x: 0.734375, y: 0.046875 },
{ x: 0.765625, y: 0.046875 },
{ x: 0.765625, y: 0.046875 },
{ x: 0.796875, y: 0.046875 },
{ x: 0.796875, y: 0.046875 },
{ x: 0.828125, y: 0.046875 },
{ x: 0.828125, y: 0.046875 },
{ x: 0.859375, y: 0.046875 },
{ x: 0.859375, y: 0.046875 },
{ x: 0.890625, y: 0.046875 },
{ x: 0.890625, y: 0.046875 },
{ x: 0.921875, y: 0.046875 },
{ x: 0.921875, y: 0.046875 },
{ x: 0.953125, y: 0.046875 },
{ x: 0.953125, y: 0.046875 },
{ x: 0.984375, y: 0.046875 },
{ x: 0.984375, y: 0.046875 },
{ x: 0.015625, y: 0.078125 },
{ x: 0.015625, y: 0.078125 },
{ x: 0.046875, y: 0.078125 },
{ x: 0.046875, y: 0.078125 },
{ x: 0.078125, y: 0.078125 },
{ x: 0.078125, y: 0.078125 },
{ x: 0.109375, y: 0.078125 },
{ x: 0.109375, y: 0.078125 },
{ x: 0.140625, y: 0.078125 },
{ x: 0.140625, y: 0.078125 },
{ x: 0.171875, y: 0.078125 },
{ x: 0.171875, y: 0.078125 },
{ x: 0.203125, y: 0.078125 },
{ x: 0.203125, y: 0.078125 },
{ x: 0.234375, y: 0.078125 },
{ x: 0.234375, y: 0.078125 },
{ x: 0.265625, y: 0.078125 },
{ x: 0.265625, y: 0.078125 },
{ x: 0.296875, y: 0.078125 },
{ x: 0.296875, y: 0.078125 },
{ x: 0.328125, y: 0.078125 },
{ x: 0.328125, y: 0.078125 },
{ x: 0.359375, y: 0.078125 },
{ x: 0.359375, y: 0.078125 },
{ x: 0.390625, y: 0.078125 },
{ x: 0.390625, y: 0.078125 },
{ x: 0.421875, y: 0.078125 },
{ x: 0.421875, y: 0.078125 },
{ x: 0.453125, y: 0.078125 },
{ x: 0.453125, y: 0.078125 },
{ x: 0.484375, y: 0.078125 },
{ x: 0.484375, y: 0.078125 },
{ x: 0.515625, y: 0.078125 },
{ x: 0.515625, y: 0.078125 },
{ x: 0.546875, y: 0.078125 },
{ x: 0.546875, y: 0.078125 },
{ x: 0.578125, y: 0.078125 },
{ x: 0.578125, y: 0.078125 },
{ x: 0.609375, y: 0.078125 },
{ x: 0.609375, y: 0.078125 },
{ x: 0.640625, y: 0.078125 },
{ x: 0.640625, y: 0.078125 },
{ x: 0.671875, y: 0.078125 },
{ x: 0.671875, y: 0.078125 },
{ x: 0.703125, y: 0.078125 },
{ x: 0.703125, y: 0.078125 },
{ x: 0.734375, y: 0.078125 },
{ x: 0.734375, y: 0.078125 },
{ x: 0.765625, y: 0.078125 },
{ x: 0.765625, y: 0.078125 },
{ x: 0.796875, y: 0.078125 },
{ x: 0.796875, y: 0.078125 },
{ x: 0.828125, y: 0.078125 },
{ x: 0.828125, y: 0.078125 },
{ x: 0.859375, y: 0.078125 },
{ x: 0.859375, y: 0.078125 },
{ x: 0.890625, y: 0.078125 },
{ x: 0.890625, y: 0.078125 },
{ x: 0.921875, y: 0.078125 },
{ x: 0.921875, y: 0.078125 },
{ x: 0.953125, y: 0.078125 },
{ x: 0.953125, y: 0.078125 },
{ x: 0.984375, y: 0.078125 },
{ x: 0.984375, y: 0.078125 },
{ x: 0.015625, y: 0.109375 },
{ x: 0.015625, y: 0.109375 },
{ x: 0.046875, y: 0.109375 },
{ x: 0.046875, y: 0.109375 },
{ x: 0.078125, y: 0.109375 },
{ x: 0.078125, y: 0.109375 },
{ x: 0.109375, y: 0.109375 },
{ x: 0.109375, y: 0.109375 },
{ x: 0.140625, y: 0.109375 },
{ x: 0.140625, y: 0.109375 },
{ x: 0.171875, y: 0.109375 },
{ x: 0.171875, y: 0.109375 },
{ x: 0.203125, y: 0.109375 },
{ x: 0.203125, y: 0.109375 },
{ x: 0.234375, y: 0.109375 },
{ x: 0.234375, y: 0.109375 },
{ x: 0.265625, y: 0.109375 },
{ x: 0.265625, y: 0.109375 },
{ x: 0.296875, y: 0.109375 },
{ x: 0.296875, y: 0.109375 },
{ x: 0.328125, y: 0.109375 },
{ x: 0.328125, y: 0.109375 },
{ x: 0.359375, y: 0.109375 },
{ x: 0.359375, y: 0.109375 },
{ x: 0.390625, y: 0.109375 },
{ x: 0.390625, y: 0.109375 },
{ x: 0.421875, y: 0.109375 },
{ x: 0.421875, y: 0.109375 },
{ x: 0.453125, y: 0.109375 },
{ x: 0.453125, y: 0.109375 },
{ x: 0.484375, y: 0.109375 },
{ x: 0.484375, y: 0.109375 },
{ x: 0.515625, y: 0.109375 },
{ x: 0.515625, y: 0.109375 },
{ x: 0.546875, y: 0.109375 },
{ x: 0.546875, y: 0.109375 },
{ x: 0.578125, y: 0.109375 },
{ x: 0.578125, y: 0.109375 },
{ x: 0.609375, y: 0.109375 },
{ x: 0.609375, y: 0.109375 },
{ x: 0.640625, y: 0.109375 },
{ x: 0.640625, y: 0.109375 },
{ x: 0.671875, y: 0.109375 },
{ x: 0.671875, y: 0.109375 },
{ x: 0.703125, y: 0.109375 },
{ x: 0.703125, y: 0.109375 },
{ x: 0.734375, y: 0.109375 },
{ x: 0.734375, y: 0.109375 },
{ x: 0.765625, y: 0.109375 },
{ x: 0.765625, y: 0.109375 },
{ x: 0.796875, y: 0.109375 },
{ x: 0.796875, y: 0.109375 },
{ x: 0.828125, y: 0.109375 },
{ x: 0.828125, y: 0.109375 },
{ x: 0.859375, y: 0.109375 },
{ x: 0.859375, y: 0.109375 },
{ x: 0.890625, y: 0.109375 },
{ x: 0.890625, y: 0.109375 },
{ x: 0.921875, y: 0.109375 },
{ x: 0.921875, y: 0.109375 },
{ x: 0.953125, y: 0.109375 },
{ x: 0.953125, y: 0.109375 },
{ x: 0.984375, y: 0.109375 },
{ x: 0.984375, y: 0.109375 },
{ x: 0.015625, y: 0.140625 },
{ x: 0.015625, y: 0.140625 },
{ x: 0.046875, y: 0.140625 },
{ x: 0.046875, y: 0.140625 },
{ x: 0.078125, y: 0.140625 },
{ x: 0.078125, y: 0.140625 },
{ x: 0.109375, y: 0.140625 },
{ x: 0.109375, y: 0.140625 },
{ x: 0.140625, y: 0.140625 },
{ x: 0.140625, y: 0.140625 },
{ x: 0.171875, y: 0.140625 },
{ x: 0.171875, y: 0.140625 },
{ x: 0.203125, y: 0.140625 },
{ x: 0.203125, y: 0.140625 },
{ x: 0.234375, y: 0.140625 },
{ x: 0.234375, y: 0.140625 },
{ x: 0.265625, y: 0.140625 },
{ x: 0.265625, y: 0.140625 },
{ x: 0.296875, y: 0.140625 },
{ x: 0.296875, y: 0.140625 },
{ x: 0.328125, y: 0.140625 },
{ x: 0.328125, y: 0.140625 },
{ x: 0.359375, y: 0.140625 },
{ x: 0.359375, y: 0.140625 },
{ x: 0.390625, y: 0.140625 },
{ x: 0.390625, y: 0.140625 },
{ x: 0.421875, y: 0.140625 },
{ x: 0.421875, y: 0.140625 },
{ x: 0.453125, y: 0.140625 },
{ x: 0.453125, y: 0.140625 },
{ x: 0.484375, y: 0.140625 },
{ x: 0.484375, y: 0.140625 },
{ x: 0.515625, y: 0.140625 },
{ x: 0.515625, y: 0.140625 },
{ x: 0.546875, y: 0.140625 },
{ x: 0.546875, y: 0.140625 },
{ x: 0.578125, y: 0.140625 },
{ x: 0.578125, y: 0.140625 },
{ x: 0.609375, y: 0.140625 },
{ x: 0.609375, y: 0.140625 },
{ x: 0.640625, y: 0.140625 },
{ x: 0.640625, y: 0.140625 },
{ x: 0.671875, y: 0.140625 },
{ x: 0.671875, y: 0.140625 },
{ x: 0.703125, y: 0.140625 },
{ x: 0.703125, y: 0.140625 },
{ x: 0.734375, y: 0.140625 },
{ x: 0.734375, y: 0.140625 },
{ x: 0.765625, y: 0.140625 },
{ x: 0.765625, y: 0.140625 },
{ x: 0.796875, y: 0.140625 },
{ x: 0.796875, y: 0.140625 },
{ x: 0.828125, y: 0.140625 },
{ x: 0.828125, y: 0.140625 },
{ x: 0.859375, y: 0.140625 },
{ x: 0.859375, y: 0.140625 },
{ x: 0.890625, y: 0.140625 },
{ x: 0.890625, y: 0.140625 },
{ x: 0.921875, y: 0.140625 },
{ x: 0.921875, y: 0.140625 },
{ x: 0.953125, y: 0.140625 },
{ x: 0.953125, y: 0.140625 },
{ x: 0.984375, y: 0.140625 },
{ x: 0.984375, y: 0.140625 },
{ x: 0.015625, y: 0.171875 },
{ x: 0.015625, y: 0.171875 },
{ x: 0.046875, y: 0.171875 },
{ x: 0.046875, y: 0.171875 },
{ x: 0.078125, y: 0.171875 },
{ x: 0.078125, y: 0.171875 },
{ x: 0.109375, y: 0.171875 },
{ x: 0.109375, y: 0.171875 },
{ x: 0.140625, y: 0.171875 },
{ x: 0.140625, y: 0.171875 },
{ x: 0.171875, y: 0.171875 },
{ x: 0.171875, y: 0.171875 },
{ x: 0.203125, y: 0.171875 },
{ x: 0.203125, y: 0.171875 },
{ x: 0.234375, y: 0.171875 },
{ x: 0.234375, y: 0.171875 },
{ x: 0.265625, y: 0.171875 },
{ x: 0.265625, y: 0.171875 },
{ x: 0.296875, y: 0.171875 },
{ x: 0.296875, y: 0.171875 },
{ x: 0.328125, y: 0.171875 },
{ x: 0.328125, y: 0.171875 },
{ x: 0.359375, y: 0.171875 },
{ x: 0.359375, y: 0.171875 },
{ x: 0.390625, y: 0.171875 },
{ x: 0.390625, y: 0.171875 },
{ x: 0.421875, y: 0.171875 },
{ x: 0.421875, y: 0.171875 },
{ x: 0.453125, y: 0.171875 },
{ x: 0.453125, y: 0.171875 },
{ x: 0.484375, y: 0.171875 },
{ x: 0.484375, y: 0.171875 },
{ x: 0.515625, y: 0.171875 },
{ x: 0.515625, y: 0.171875 },
{ x: 0.546875, y: 0.171875 },
{ x: 0.546875, y: 0.171875 },
{ x: 0.578125, y: 0.171875 },
{ x: 0.578125, y: 0.171875 },
{ x: 0.609375, y: 0.171875 },
{ x: 0.609375, y: 0.171875 },
{ x: 0.640625, y: 0.171875 },
{ x: 0.640625, y: 0.171875 },
{ x: 0.671875, y: 0.171875 },
{ x: 0.671875, y: 0.171875 },
{ x: 0.703125, y: 0.171875 },
{ x: 0.703125, y: 0.171875 },
{ x: 0.734375, y: 0.171875 },
{ x: 0.734375, y: 0.171875 },
{ x: 0.765625, y: 0.171875 },
{ x: 0.765625, y: 0.171875 },
{ x: 0.796875, y: 0.171875 },
{ x: 0.796875, y: 0.171875 },
{ x: 0.828125, y: 0.171875 },
{ x: 0.828125, y: 0.171875 },
{ x: 0.859375, y: 0.171875 },
{ x: 0.859375, y: 0.171875 },
{ x: 0.890625, y: 0.171875 },
{ x: 0.890625, y: 0.171875 },
{ x: 0.921875, y: 0.171875 },
{ x: 0.921875, y: 0.171875 },
{ x: 0.953125, y: 0.171875 },
{ x: 0.953125, y: 0.171875 },
{ x: 0.984375, y: 0.171875 },
{ x: 0.984375, y: 0.171875 },
{ x: 0.015625, y: 0.203125 },
{ x: 0.015625, y: 0.203125 },
{ x: 0.046875, y: 0.203125 },
{ x: 0.046875, y: 0.203125 },
{ x: 0.078125, y: 0.203125 },
{ x: 0.078125, y: 0.203125 },
{ x: 0.109375, y: 0.203125 },
{ x: 0.109375, y: 0.203125 },
{ x: 0.140625, y: 0.203125 },
{ x: 0.140625, y: 0.203125 },
{ x: 0.171875, y: 0.203125 },
{ x: 0.171875, y: 0.203125 },
{ x: 0.203125, y: 0.203125 },
{ x: 0.203125, y: 0.203125 },
{ x: 0.234375, y: 0.203125 },
{ x: 0.234375, y: 0.203125 },
{ x: 0.265625, y: 0.203125 },
{ x: 0.265625, y: 0.203125 },
{ x: 0.296875, y: 0.203125 },
{ x: 0.296875, y: 0.203125 },
{ x: 0.328125, y: 0.203125 },
{ x: 0.328125, y: 0.203125 },
{ x: 0.359375, y: 0.203125 },
{ x: 0.359375, y: 0.203125 },
{ x: 0.390625, y: 0.203125 },
{ x: 0.390625, y: 0.203125 },
{ x: 0.421875, y: 0.203125 },
{ x: 0.421875, y: 0.203125 },
{ x: 0.453125, y: 0.203125 },
{ x: 0.453125, y: 0.203125 },
{ x: 0.484375, y: 0.203125 },
{ x: 0.484375, y: 0.203125 },
{ x: 0.515625, y: 0.203125 },
{ x: 0.515625, y: 0.203125 },
{ x: 0.546875, y: 0.203125 },
{ x: 0.546875, y: 0.203125 },
{ x: 0.578125, y: 0.203125 },
{ x: 0.578125, y: 0.203125 },
{ x: 0.609375, y: 0.203125 },
{ x: 0.609375, y: 0.203125 },
{ x: 0.640625, y: 0.203125 },
{ x: 0.640625, y: 0.203125 },
{ x: 0.671875, y: 0.203125 },
{ x: 0.671875, y: 0.203125 },
{ x: 0.703125, y: 0.203125 },
{ x: 0.703125, y: 0.203125 },
{ x: 0.734375, y: 0.203125 },
{ x: 0.734375, y: 0.203125 },
{ x: 0.765625, y: 0.203125 },
{ x: 0.765625, y: 0.203125 },
{ x: 0.796875, y: 0.203125 },
{ x: 0.796875, y: 0.203125 },
{ x: 0.828125, y: 0.203125 },
{ x: 0.828125, y: 0.203125 },
{ x: 0.859375, y: 0.203125 },
{ x: 0.859375, y: 0.203125 },
{ x: 0.890625, y: 0.203125 },
{ x: 0.890625, y: 0.203125 },
{ x: 0.921875, y: 0.203125 },
{ x: 0.921875, y: 0.203125 },
{ x: 0.953125, y: 0.203125 },
{ x: 0.953125, y: 0.203125 },
{ x: 0.984375, y: 0.203125 },
{ x: 0.984375, y: 0.203125 },
{ x: 0.015625, y: 0.234375 },
{ x: 0.015625, y: 0.234375 },
{ x: 0.046875, y: 0.234375 },
{ x: 0.046875, y: 0.234375 },
{ x: 0.078125, y: 0.234375 },
{ x: 0.078125, y: 0.234375 },
{ x: 0.109375, y: 0.234375 },
{ x: 0.109375, y: 0.234375 },
{ x: 0.140625, y: 0.234375 },
{ x: 0.140625, y: 0.234375 },
{ x: 0.171875, y: 0.234375 },
{ x: 0.171875, y: 0.234375 },
{ x: 0.203125, y: 0.234375 },
{ x: 0.203125, y: 0.234375 },
{ x: 0.234375, y: 0.234375 },
{ x: 0.234375, y: 0.234375 },
{ x: 0.265625, y: 0.234375 },
{ x: 0.265625, y: 0.234375 },
{ x: 0.296875, y: 0.234375 },
{ x: 0.296875, y: 0.234375 },
{ x: 0.328125, y: 0.234375 },
{ x: 0.328125, y: 0.234375 },
{ x: 0.359375, y: 0.234375 },
{ x: 0.359375, y: 0.234375 },
{ x: 0.390625, y: 0.234375 },
{ x: 0.390625, y: 0.234375 },
{ x: 0.421875, y: 0.234375 },
{ x: 0.421875, y: 0.234375 },
{ x: 0.453125, y: 0.234375 },
{ x: 0.453125, y: 0.234375 },
{ x: 0.484375, y: 0.234375 },
{ x: 0.484375, y: 0.234375 },
{ x: 0.515625, y: 0.234375 },
{ x: 0.515625, y: 0.234375 },
{ x: 0.546875, y: 0.234375 },
{ x: 0.546875, y: 0.234375 },
{ x: 0.578125, y: 0.234375 },
{ x: 0.578125, y: 0.234375 },
{ x: 0.609375, y: 0.234375 },
{ x: 0.609375, y: 0.234375 },
{ x: 0.640625, y: 0.234375 },
{ x: 0.640625, y: 0.234375 },
{ x: 0.671875, y: 0.234375 },
{ x: 0.671875, y: 0.234375 },
{ x: 0.703125, y: 0.234375 },
{ x: 0.703125, y: 0.234375 },
{ x: 0.734375, y: 0.234375 },
{ x: 0.734375, y: 0.234375 },
{ x: 0.765625, y: 0.234375 },
{ x: 0.765625, y: 0.234375 },
{ x: 0.796875, y: 0.234375 },
{ x: 0.796875, y: 0.234375 },
{ x: 0.828125, y: 0.234375 },
{ x: 0.828125, y: 0.234375 },
{ x: 0.859375, y: 0.234375 },
{ x: 0.859375, y: 0.234375 },
{ x: 0.890625, y: 0.234375 },
{ x: 0.890625, y: 0.234375 },
{ x: 0.921875, y: 0.234375 },
{ x: 0.921875, y: 0.234375 },
{ x: 0.953125, y: 0.234375 },
{ x: 0.953125, y: 0.234375 },
{ x: 0.984375, y: 0.234375 },
{ x: 0.984375, y: 0.234375 },
{ x: 0.015625, y: 0.265625 },
{ x: 0.015625, y: 0.265625 },
{ x: 0.046875, y: 0.265625 },
{ x: 0.046875, y: 0.265625 },
{ x: 0.078125, y: 0.265625 },
{ x: 0.078125, y: 0.265625 },
{ x: 0.109375, y: 0.265625 },
{ x: 0.109375, y: 0.265625 },
{ x: 0.140625, y: 0.265625 },
{ x: 0.140625, y: 0.265625 },
{ x: 0.171875, y: 0.265625 },
{ x: 0.171875, y: 0.265625 },
{ x: 0.203125, y: 0.265625 },
{ x: 0.203125, y: 0.265625 },
{ x: 0.234375, y: 0.265625 },
{ x: 0.234375, y: 0.265625 },
{ x: 0.265625, y: 0.265625 },
{ x: 0.265625, y: 0.265625 },
{ x: 0.296875, y: 0.265625 },
{ x: 0.296875, y: 0.265625 },
{ x: 0.328125, y: 0.265625 },
{ x: 0.328125, y: 0.265625 },
{ x: 0.359375, y: 0.265625 },
{ x: 0.359375, y: 0.265625 },
{ x: 0.390625, y: 0.265625 },
{ x: 0.390625, y: 0.265625 },
{ x: 0.421875, y: 0.265625 },
{ x: 0.421875, y: 0.265625 },
{ x: 0.453125, y: 0.265625 },
{ x: 0.453125, y: 0.265625 },
{ x: 0.484375, y: 0.265625 },
{ x: 0.484375, y: 0.265625 },
{ x: 0.515625, y: 0.265625 },
{ x: 0.515625, y: 0.265625 },
{ x: 0.546875, y: 0.265625 },
{ x: 0.546875, y: 0.265625 },
{ x: 0.578125, y: 0.265625 },
{ x: 0.578125, y: 0.265625 },
{ x: 0.609375, y: 0.265625 },
{ x: 0.609375, y: 0.265625 },
{ x: 0.640625, y: 0.265625 },
{ x: 0.640625, y: 0.265625 },
{ x: 0.671875, y: 0.265625 },
{ x: 0.671875, y: 0.265625 },
{ x: 0.703125, y: 0.265625 },
{ x: 0.703125, y: 0.265625 },
{ x: 0.734375, y: 0.265625 },
{ x: 0.734375, y: 0.265625 },
{ x: 0.765625, y: 0.265625 },
{ x: 0.765625, y: 0.265625 },
{ x: 0.796875, y: 0.265625 },
{ x: 0.796875, y: 0.265625 },
{ x: 0.828125, y: 0.265625 },
{ x: 0.828125, y: 0.265625 },
{ x: 0.859375, y: 0.265625 },
{ x: 0.859375, y: 0.265625 },
{ x: 0.890625, y: 0.265625 },
{ x: 0.890625, y: 0.265625 },
{ x: 0.921875, y: 0.265625 },
{ x: 0.921875, y: 0.265625 },
{ x: 0.953125, y: 0.265625 },
{ x: 0.953125, y: 0.265625 },
{ x: 0.984375, y: 0.265625 },
{ x: 0.984375, y: 0.265625 },
{ x: 0.015625, y: 0.296875 },
{ x: 0.015625, y: 0.296875 },
{ x: 0.046875, y: 0.296875 },
{ x: 0.046875, y: 0.296875 },
{ x: 0.078125, y: 0.296875 },
{ x: 0.078125, y: 0.296875 },
{ x: 0.109375, y: 0.296875 },
{ x: 0.109375, y: 0.296875 },
{ x: 0.140625, y: 0.296875 },
{ x: 0.140625, y: 0.296875 },
{ x: 0.171875, y: 0.296875 },
{ x: 0.171875, y: 0.296875 },
{ x: 0.203125, y: 0.296875 },
{ x: 0.203125, y: 0.296875 },
{ x: 0.234375, y: 0.296875 },
{ x: 0.234375, y: 0.296875 },
{ x: 0.265625, y: 0.296875 },
{ x: 0.265625, y: 0.296875 },
{ x: 0.296875, y: 0.296875 },
{ x: 0.296875, y: 0.296875 },
{ x: 0.328125, y: 0.296875 },
{ x: 0.328125, y: 0.296875 },
{ x: 0.359375, y: 0.296875 },
{ x: 0.359375, y: 0.296875 },
{ x: 0.390625, y: 0.296875 },
{ x: 0.390625, y: 0.296875 },
{ x: 0.421875, y: 0.296875 },
{ x: 0.421875, y: 0.296875 },
{ x: 0.453125, y: 0.296875 },
{ x: 0.453125, y: 0.296875 },
{ x: 0.484375, y: 0.296875 },
{ x: 0.484375, y: 0.296875 },
{ x: 0.515625, y: 0.296875 },
{ x: 0.515625, y: 0.296875 },
{ x: 0.546875, y: 0.296875 },
{ x: 0.546875, y: 0.296875 },
{ x: 0.578125, y: 0.296875 },
{ x: 0.578125, y: 0.296875 },
{ x: 0.609375, y: 0.296875 },
{ x: 0.609375, y: 0.296875 },
{ x: 0.640625, y: 0.296875 },
{ x: 0.640625, y: 0.296875 },
{ x: 0.671875, y: 0.296875 },
{ x: 0.671875, y: 0.296875 },
{ x: 0.703125, y: 0.296875 },
{ x: 0.703125, y: 0.296875 },
{ x: 0.734375, y: 0.296875 },
{ x: 0.734375, y: 0.296875 },
{ x: 0.765625, y: 0.296875 },
{ x: 0.765625, y: 0.296875 },
{ x: 0.796875, y: 0.296875 },
{ x: 0.796875, y: 0.296875 },
{ x: 0.828125, y: 0.296875 },
{ x: 0.828125, y: 0.296875 },
{ x: 0.859375, y: 0.296875 },
{ x: 0.859375, y: 0.296875 },
{ x: 0.890625, y: 0.296875 },
{ x: 0.890625, y: 0.296875 },
{ x: 0.921875, y: 0.296875 },
{ x: 0.921875, y: 0.296875 },
{ x: 0.953125, y: 0.296875 },
{ x: 0.953125, y: 0.296875 },
{ x: 0.984375, y: 0.296875 },
{ x: 0.984375, y: 0.296875 },
{ x: 0.015625, y: 0.328125 },
{ x: 0.015625, y: 0.328125 },
{ x: 0.046875, y: 0.328125 },
{ x: 0.046875, y: 0.328125 },
{ x: 0.078125, y: 0.328125 },
{ x: 0.078125, y: 0.328125 },
{ x: 0.109375, y: 0.328125 },
{ x: 0.109375, y: 0.328125 },
{ x: 0.140625, y: 0.328125 },
{ x: 0.140625, y: 0.328125 },
{ x: 0.171875, y: 0.328125 },
{ x: 0.171875, y: 0.328125 },
{ x: 0.203125, y: 0.328125 },
{ x: 0.203125, y: 0.328125 },
{ x: 0.234375, y: 0.328125 },
{ x: 0.234375, y: 0.328125 },
{ x: 0.265625, y: 0.328125 },
{ x: 0.265625, y: 0.328125 },
{ x: 0.296875, y: 0.328125 },
{ x: 0.296875, y: 0.328125 },
{ x: 0.328125, y: 0.328125 },
{ x: 0.328125, y: 0.328125 },
{ x: 0.359375, y: 0.328125 },
{ x: 0.359375, y: 0.328125 },
{ x: 0.390625, y: 0.328125 },
{ x: 0.390625, y: 0.328125 },
{ x: 0.421875, y: 0.328125 },
{ x: 0.421875, y: 0.328125 },
{ x: 0.453125, y: 0.328125 },
{ x: 0.453125, y: 0.328125 },
{ x: 0.484375, y: 0.328125 },
{ x: 0.484375, y: 0.328125 },
{ x: 0.515625, y: 0.328125 },
{ x: 0.515625, y: 0.328125 },
{ x: 0.546875, y: 0.328125 },
{ x: 0.546875, y: 0.328125 },
{ x: 0.578125, y: 0.328125 },
{ x: 0.578125, y: 0.328125 },
{ x: 0.609375, y: 0.328125 },
{ x: 0.609375, y: 0.328125 },
{ x: 0.640625, y: 0.328125 },
{ x: 0.640625, y: 0.328125 },
{ x: 0.671875, y: 0.328125 },
{ x: 0.671875, y: 0.328125 },
{ x: 0.703125, y: 0.328125 },
{ x: 0.703125, y: 0.328125 },
{ x: 0.734375, y: 0.328125 },
{ x: 0.734375, y: 0.328125 },
{ x: 0.765625, y: 0.328125 },
{ x: 0.765625, y: 0.328125 },
{ x: 0.796875, y: 0.328125 },
{ x: 0.796875, y: 0.328125 },
{ x: 0.828125, y: 0.328125 },
{ x: 0.828125, y: 0.328125 },
{ x: 0.859375, y: 0.328125 },
{ x: 0.859375, y: 0.328125 },
{ x: 0.890625, y: 0.328125 },
{ x: 0.890625, y: 0.328125 },
{ x: 0.921875, y: 0.328125 },
{ x: 0.921875, y: 0.328125 },
{ x: 0.953125, y: 0.328125 },
{ x: 0.953125, y: 0.328125 },
{ x: 0.984375, y: 0.328125 },
{ x: 0.984375, y: 0.328125 },
{ x: 0.015625, y: 0.359375 },
{ x: 0.015625, y: 0.359375 },
{ x: 0.046875, y: 0.359375 },
{ x: 0.046875, y: 0.359375 },
{ x: 0.078125, y: 0.359375 },
{ x: 0.078125, y: 0.359375 },
{ x: 0.109375, y: 0.359375 },
{ x: 0.109375, y: 0.359375 },
{ x: 0.140625, y: 0.359375 },
{ x: 0.140625, y: 0.359375 },
{ x: 0.171875, y: 0.359375 },
{ x: 0.171875, y: 0.359375 },
{ x: 0.203125, y: 0.359375 },
{ x: 0.203125, y: 0.359375 },
{ x: 0.234375, y: 0.359375 },
{ x: 0.234375, y: 0.359375 },
{ x: 0.265625, y: 0.359375 },
{ x: 0.265625, y: 0.359375 },
{ x: 0.296875, y: 0.359375 },
{ x: 0.296875, y: 0.359375 },
{ x: 0.328125, y: 0.359375 },
{ x: 0.328125, y: 0.359375 },
{ x: 0.359375, y: 0.359375 },
{ x: 0.359375, y: 0.359375 },
{ x: 0.390625, y: 0.359375 },
{ x: 0.390625, y: 0.359375 },
{ x: 0.421875, y: 0.359375 },
{ x: 0.421875, y: 0.359375 },
{ x: 0.453125, y: 0.359375 },
{ x: 0.453125, y: 0.359375 },
{ x: 0.484375, y: 0.359375 },
{ x: 0.484375, y: 0.359375 },
{ x: 0.515625, y: 0.359375 },
{ x: 0.515625, y: 0.359375 },
{ x: 0.546875, y: 0.359375 },
{ x: 0.546875, y: 0.359375 },
{ x: 0.578125, y: 0.359375 },
{ x: 0.578125, y: 0.359375 },
{ x: 0.609375, y: 0.359375 },
{ x: 0.609375, y: 0.359375 },
{ x: 0.640625, y: 0.359375 },
{ x: 0.640625, y: 0.359375 },
{ x: 0.671875, y: 0.359375 },
{ x: 0.671875, y: 0.359375 },
{ x: 0.703125, y: 0.359375 },
{ x: 0.703125, y: 0.359375 },
{ x: 0.734375, y: 0.359375 },
{ x: 0.734375, y: 0.359375 },
{ x: 0.765625, y: 0.359375 },
{ x: 0.765625, y: 0.359375 },
{ x: 0.796875, y: 0.359375 },
{ x: 0.796875, y: 0.359375 },
{ x: 0.828125, y: 0.359375 },
{ x: 0.828125, y: 0.359375 },
{ x: 0.859375, y: 0.359375 },
{ x: 0.859375, y: 0.359375 },
{ x: 0.890625, y: 0.359375 },
{ x: 0.890625, y: 0.359375 },
{ x: 0.921875, y: 0.359375 },
{ x: 0.921875, y: 0.359375 },
{ x: 0.953125, y: 0.359375 },
{ x: 0.953125, y: 0.359375 },
{ x: 0.984375, y: 0.359375 },
{ x: 0.984375, y: 0.359375 },
{ x: 0.015625, y: 0.390625 },
{ x: 0.015625, y: 0.390625 },
{ x: 0.046875, y: 0.390625 },
{ x: 0.046875, y: 0.390625 },
{ x: 0.078125, y: 0.390625 },
{ x: 0.078125, y: 0.390625 },
{ x: 0.109375, y: 0.390625 },
{ x: 0.109375, y: 0.390625 },
{ x: 0.140625, y: 0.390625 },
{ x: 0.140625, y: 0.390625 },
{ x: 0.171875, y: 0.390625 },
{ x: 0.171875, y: 0.390625 },
{ x: 0.203125, y: 0.390625 },
{ x: 0.203125, y: 0.390625 },
{ x: 0.234375, y: 0.390625 },
{ x: 0.234375, y: 0.390625 },
{ x: 0.265625, y: 0.390625 },
{ x: 0.265625, y: 0.390625 },
{ x: 0.296875, y: 0.390625 },
{ x: 0.296875, y: 0.390625 },
{ x: 0.328125, y: 0.390625 },
{ x: 0.328125, y: 0.390625 },
{ x: 0.359375, y: 0.390625 },
{ x: 0.359375, y: 0.390625 },
{ x: 0.390625, y: 0.390625 },
{ x: 0.390625, y: 0.390625 },
{ x: 0.421875, y: 0.390625 },
{ x: 0.421875, y: 0.390625 },
{ x: 0.453125, y: 0.390625 },
{ x: 0.453125, y: 0.390625 },
{ x: 0.484375, y: 0.390625 },
{ x: 0.484375, y: 0.390625 },
{ x: 0.515625, y: 0.390625 },
{ x: 0.515625, y: 0.390625 },
{ x: 0.546875, y: 0.390625 },
{ x: 0.546875, y: 0.390625 },
{ x: 0.578125, y: 0.390625 },
{ x: 0.578125, y: 0.390625 },
{ x: 0.609375, y: 0.390625 },
{ x: 0.609375, y: 0.390625 },
{ x: 0.640625, y: 0.390625 },
{ x: 0.640625, y: 0.390625 },
{ x: 0.671875, y: 0.390625 },
{ x: 0.671875, y: 0.390625 },
{ x: 0.703125, y: 0.390625 },
{ x: 0.703125, y: 0.390625 },
{ x: 0.734375, y: 0.390625 },
{ x: 0.734375, y: 0.390625 },
{ x: 0.765625, y: 0.390625 },
{ x: 0.765625, y: 0.390625 },
{ x: 0.796875, y: 0.390625 },
{ x: 0.796875, y: 0.390625 },
{ x: 0.828125, y: 0.390625 },
{ x: 0.828125, y: 0.390625 },
{ x: 0.859375, y: 0.390625 },
{ x: 0.859375, y: 0.390625 },
{ x: 0.890625, y: 0.390625 },
{ x: 0.890625, y: 0.390625 },
{ x: 0.921875, y: 0.390625 },
{ x: 0.921875, y: 0.390625 },
{ x: 0.953125, y: 0.390625 },
{ x: 0.953125, y: 0.390625 },
{ x: 0.984375, y: 0.390625 },
{ x: 0.984375, y: 0.390625 },
{ x: 0.015625, y: 0.421875 },
{ x: 0.015625, y: 0.421875 },
{ x: 0.046875, y: 0.421875 },
{ x: 0.046875, y: 0.421875 },
{ x: 0.078125, y: 0.421875 },
{ x: 0.078125, y: 0.421875 },
{ x: 0.109375, y: 0.421875 },
{ x: 0.109375, y: 0.421875 },
{ x: 0.140625, y: 0.421875 },
{ x: 0.140625, y: 0.421875 },
{ x: 0.171875, y: 0.421875 },
{ x: 0.171875, y: 0.421875 },
{ x: 0.203125, y: 0.421875 },
{ x: 0.203125, y: 0.421875 },
{ x: 0.234375, y: 0.421875 },
{ x: 0.234375, y: 0.421875 },
{ x: 0.265625, y: 0.421875 },
{ x: 0.265625, y: 0.421875 },
{ x: 0.296875, y: 0.421875 },
{ x: 0.296875, y: 0.421875 },
{ x: 0.328125, y: 0.421875 },
{ x: 0.328125, y: 0.421875 },
{ x: 0.359375, y: 0.421875 },
{ x: 0.359375, y: 0.421875 },
{ x: 0.390625, y: 0.421875 },
{ x: 0.390625, y: 0.421875 },
{ x: 0.421875, y: 0.421875 },
{ x: 0.421875, y: 0.421875 },
{ x: 0.453125, y: 0.421875 },
{ x: 0.453125, y: 0.421875 },
{ x: 0.484375, y: 0.421875 },
{ x: 0.484375, y: 0.421875 },
{ x: 0.515625, y: 0.421875 },
{ x: 0.515625, y: 0.421875 },
{ x: 0.546875, y: 0.421875 },
{ x: 0.546875, y: 0.421875 },
{ x: 0.578125, y: 0.421875 },
{ x: 0.578125, y: 0.421875 },
{ x: 0.609375, y: 0.421875 },
{ x: 0.609375, y: 0.421875 },
{ x: 0.640625, y: 0.421875 },
{ x: 0.640625, y: 0.421875 },
{ x: 0.671875, y: 0.421875 },
{ x: 0.671875, y: 0.421875 },
{ x: 0.703125, y: 0.421875 },
{ x: 0.703125, y: 0.421875 },
{ x: 0.734375, y: 0.421875 },
{ x: 0.734375, y: 0.421875 },
{ x: 0.765625, y: 0.421875 },
{ x: 0.765625, y: 0.421875 },
{ x: 0.796875, y: 0.421875 },
{ x: 0.796875, y: 0.421875 },
{ x: 0.828125, y: 0.421875 },
{ x: 0.828125, y: 0.421875 },
{ x: 0.859375, y: 0.421875 },
{ x: 0.859375, y: 0.421875 },
{ x: 0.890625, y: 0.421875 },
{ x: 0.890625, y: 0.421875 },
{ x: 0.921875, y: 0.421875 },
{ x: 0.921875, y: 0.421875 },
{ x: 0.953125, y: 0.421875 },
{ x: 0.953125, y: 0.421875 },
{ x: 0.984375, y: 0.421875 },
{ x: 0.984375, y: 0.421875 },
{ x: 0.015625, y: 0.453125 },
{ x: 0.015625, y: 0.453125 },
{ x: 0.046875, y: 0.453125 },
{ x: 0.046875, y: 0.453125 },
{ x: 0.078125, y: 0.453125 },
{ x: 0.078125, y: 0.453125 },
{ x: 0.109375, y: 0.453125 },
{ x: 0.109375, y: 0.453125 },
{ x: 0.140625, y: 0.453125 },
{ x: 0.140625, y: 0.453125 },
{ x: 0.171875, y: 0.453125 },
{ x: 0.171875, y: 0.453125 },
{ x: 0.203125, y: 0.453125 },
{ x: 0.203125, y: 0.453125 },
{ x: 0.234375, y: 0.453125 },
{ x: 0.234375, y: 0.453125 },
{ x: 0.265625, y: 0.453125 },
{ x: 0.265625, y: 0.453125 },
{ x: 0.296875, y: 0.453125 },
{ x: 0.296875, y: 0.453125 },
{ x: 0.328125, y: 0.453125 },
{ x: 0.328125, y: 0.453125 },
{ x: 0.359375, y: 0.453125 },
{ x: 0.359375, y: 0.453125 },
{ x: 0.390625, y: 0.453125 },
{ x: 0.390625, y: 0.453125 },
{ x: 0.421875, y: 0.453125 },
{ x: 0.421875, y: 0.453125 },
{ x: 0.453125, y: 0.453125 },
{ x: 0.453125, y: 0.453125 },
{ x: 0.484375, y: 0.453125 },
{ x: 0.484375, y: 0.453125 },
{ x: 0.515625, y: 0.453125 },
{ x: 0.515625, y: 0.453125 },
{ x: 0.546875, y: 0.453125 },
{ x: 0.546875, y: 0.453125 },
{ x: 0.578125, y: 0.453125 },
{ x: 0.578125, y: 0.453125 },
{ x: 0.609375, y: 0.453125 },
{ x: 0.609375, y: 0.453125 },
{ x: 0.640625, y: 0.453125 },
{ x: 0.640625, y: 0.453125 },
{ x: 0.671875, y: 0.453125 },
{ x: 0.671875, y: 0.453125 },
{ x: 0.703125, y: 0.453125 },
{ x: 0.703125, y: 0.453125 },
{ x: 0.734375, y: 0.453125 },
{ x: 0.734375, y: 0.453125 },
{ x: 0.765625, y: 0.453125 },
{ x: 0.765625, y: 0.453125 },
{ x: 0.796875, y: 0.453125 },
{ x: 0.796875, y: 0.453125 },
{ x: 0.828125, y: 0.453125 },
{ x: 0.828125, y: 0.453125 },
{ x: 0.859375, y: 0.453125 },
{ x: 0.859375, y: 0.453125 },
{ x: 0.890625, y: 0.453125 },
{ x: 0.890625, y: 0.453125 },
{ x: 0.921875, y: 0.453125 },
{ x: 0.921875, y: 0.453125 },
{ x: 0.953125, y: 0.453125 },
{ x: 0.953125, y: 0.453125 },
{ x: 0.984375, y: 0.453125 },
{ x: 0.984375, y: 0.453125 },
{ x: 0.015625, y: 0.484375 },
{ x: 0.015625, y: 0.484375 },
{ x: 0.046875, y: 0.484375 },
{ x: 0.046875, y: 0.484375 },
{ x: 0.078125, y: 0.484375 },
{ x: 0.078125, y: 0.484375 },
{ x: 0.109375, y: 0.484375 },
{ x: 0.109375, y: 0.484375 },
{ x: 0.140625, y: 0.484375 },
{ x: 0.140625, y: 0.484375 },
{ x: 0.171875, y: 0.484375 },
{ x: 0.171875, y: 0.484375 },
{ x: 0.203125, y: 0.484375 },
{ x: 0.203125, y: 0.484375 },
{ x: 0.234375, y: 0.484375 },
{ x: 0.234375, y: 0.484375 },
{ x: 0.265625, y: 0.484375 },
{ x: 0.265625, y: 0.484375 },
{ x: 0.296875, y: 0.484375 },
{ x: 0.296875, y: 0.484375 },
{ x: 0.328125, y: 0.484375 },
{ x: 0.328125, y: 0.484375 },
{ x: 0.359375, y: 0.484375 },
{ x: 0.359375, y: 0.484375 },
{ x: 0.390625, y: 0.484375 },
{ x: 0.390625, y: 0.484375 },
{ x: 0.421875, y: 0.484375 },
{ x: 0.421875, y: 0.484375 },
{ x: 0.453125, y: 0.484375 },
{ x: 0.453125, y: 0.484375 },
{ x: 0.484375, y: 0.484375 },
{ x: 0.484375, y: 0.484375 },
{ x: 0.515625, y: 0.484375 },
{ x: 0.515625, y: 0.484375 },
{ x: 0.546875, y: 0.484375 },
{ x: 0.546875, y: 0.484375 },
{ x: 0.578125, y: 0.484375 },
{ x: 0.578125, y: 0.484375 },
{ x: 0.609375, y: 0.484375 },
{ x: 0.609375, y: 0.484375 },
{ x: 0.640625, y: 0.484375 },
{ x: 0.640625, y: 0.484375 },
{ x: 0.671875, y: 0.484375 },
{ x: 0.671875, y: 0.484375 },
{ x: 0.703125, y: 0.484375 },
{ x: 0.703125, y: 0.484375 },
{ x: 0.734375, y: 0.484375 },
{ x: 0.734375, y: 0.484375 },
{ x: 0.765625, y: 0.484375 },
{ x: 0.765625, y: 0.484375 },
{ x: 0.796875, y: 0.484375 },
{ x: 0.796875, y: 0.484375 },
{ x: 0.828125, y: 0.484375 },
{ x: 0.828125, y: 0.484375 },
{ x: 0.859375, y: 0.484375 },
{ x: 0.859375, y: 0.484375 },
{ x: 0.890625, y: 0.484375 },
{ x: 0.890625, y: 0.484375 },
{ x: 0.921875, y: 0.484375 },
{ x: 0.921875, y: 0.484375 },
{ x: 0.953125, y: 0.484375 },
{ x: 0.953125, y: 0.484375 },
{ x: 0.984375, y: 0.484375 },
{ x: 0.984375, y: 0.484375 },
{ x: 0.015625, y: 0.515625 },
{ x: 0.015625, y: 0.515625 },
{ x: 0.046875, y: 0.515625 },
{ x: 0.046875, y: 0.515625 },
{ x: 0.078125, y: 0.515625 },
{ x: 0.078125, y: 0.515625 },
{ x: 0.109375, y: 0.515625 },
{ x: 0.109375, y: 0.515625 },
{ x: 0.140625, y: 0.515625 },
{ x: 0.140625, y: 0.515625 },
{ x: 0.171875, y: 0.515625 },
{ x: 0.171875, y: 0.515625 },
{ x: 0.203125, y: 0.515625 },
{ x: 0.203125, y: 0.515625 },
{ x: 0.234375, y: 0.515625 },
{ x: 0.234375, y: 0.515625 },
{ x: 0.265625, y: 0.515625 },
{ x: 0.265625, y: 0.515625 },
{ x: 0.296875, y: 0.515625 },
{ x: 0.296875, y: 0.515625 },
{ x: 0.328125, y: 0.515625 },
{ x: 0.328125, y: 0.515625 },
{ x: 0.359375, y: 0.515625 },
{ x: 0.359375, y: 0.515625 },
{ x: 0.390625, y: 0.515625 },
{ x: 0.390625, y: 0.515625 },
{ x: 0.421875, y: 0.515625 },
{ x: 0.421875, y: 0.515625 },
{ x: 0.453125, y: 0.515625 },
{ x: 0.453125, y: 0.515625 },
{ x: 0.484375, y: 0.515625 },
{ x: 0.484375, y: 0.515625 },
{ x: 0.515625, y: 0.515625 },
{ x: 0.515625, y: 0.515625 },
{ x: 0.546875, y: 0.515625 },
{ x: 0.546875, y: 0.515625 },
{ x: 0.578125, y: 0.515625 },
{ x: 0.578125, y: 0.515625 },
{ x: 0.609375, y: 0.515625 },
{ x: 0.609375, y: 0.515625 },
{ x: 0.640625, y: 0.515625 },
{ x: 0.640625, y: 0.515625 },
{ x: 0.671875, y: 0.515625 },
{ x: 0.671875, y: 0.515625 },
{ x: 0.703125, y: 0.515625 },
{ x: 0.703125, y: 0.515625 },
{ x: 0.734375, y: 0.515625 },
{ x: 0.734375, y: 0.515625 },
{ x: 0.765625, y: 0.515625 },
{ x: 0.765625, y: 0.515625 },
{ x: 0.796875, y: 0.515625 },
{ x: 0.796875, y: 0.515625 },
{ x: 0.828125, y: 0.515625 },
{ x: 0.828125, y: 0.515625 },
{ x: 0.859375, y: 0.515625 },
{ x: 0.859375, y: 0.515625 },
{ x: 0.890625, y: 0.515625 },
{ x: 0.890625, y: 0.515625 },
{ x: 0.921875, y: 0.515625 },
{ x: 0.921875, y: 0.515625 },
{ x: 0.953125, y: 0.515625 },
{ x: 0.953125, y: 0.515625 },
{ x: 0.984375, y: 0.515625 },
{ x: 0.984375, y: 0.515625 },
{ x: 0.015625, y: 0.546875 },
{ x: 0.015625, y: 0.546875 },
{ x: 0.046875, y: 0.546875 },
{ x: 0.046875, y: 0.546875 },
{ x: 0.078125, y: 0.546875 },
{ x: 0.078125, y: 0.546875 },
{ x: 0.109375, y: 0.546875 },
{ x: 0.109375, y: 0.546875 },
{ x: 0.140625, y: 0.546875 },
{ x: 0.140625, y: 0.546875 },
{ x: 0.171875, y: 0.546875 },
{ x: 0.171875, y: 0.546875 },
{ x: 0.203125, y: 0.546875 },
{ x: 0.203125, y: 0.546875 },
{ x: 0.234375, y: 0.546875 },
{ x: 0.234375, y: 0.546875 },
{ x: 0.265625, y: 0.546875 },
{ x: 0.265625, y: 0.546875 },
{ x: 0.296875, y: 0.546875 },
{ x: 0.296875, y: 0.546875 },
{ x: 0.328125, y: 0.546875 },
{ x: 0.328125, y: 0.546875 },
{ x: 0.359375, y: 0.546875 },
{ x: 0.359375, y: 0.546875 },
{ x: 0.390625, y: 0.546875 },
{ x: 0.390625, y: 0.546875 },
{ x: 0.421875, y: 0.546875 },
{ x: 0.421875, y: 0.546875 },
{ x: 0.453125, y: 0.546875 },
{ x: 0.453125, y: 0.546875 },
{ x: 0.484375, y: 0.546875 },
{ x: 0.484375, y: 0.546875 },
{ x: 0.515625, y: 0.546875 },
{ x: 0.515625, y: 0.546875 },
{ x: 0.546875, y: 0.546875 },
{ x: 0.546875, y: 0.546875 },
{ x: 0.578125, y: 0.546875 },
{ x: 0.578125, y: 0.546875 },
{ x: 0.609375, y: 0.546875 },
{ x: 0.609375, y: 0.546875 },
{ x: 0.640625, y: 0.546875 },
{ x: 0.640625, y: 0.546875 },
{ x: 0.671875, y: 0.546875 },
{ x: 0.671875, y: 0.546875 },
{ x: 0.703125, y: 0.546875 },
{ x: 0.703125, y: 0.546875 },
{ x: 0.734375, y: 0.546875 },
{ x: 0.734375, y: 0.546875 },
{ x: 0.765625, y: 0.546875 },
{ x: 0.765625, y: 0.546875 },
{ x: 0.796875, y: 0.546875 },
{ x: 0.796875, y: 0.546875 },
{ x: 0.828125, y: 0.546875 },
{ x: 0.828125, y: 0.546875 },
{ x: 0.859375, y: 0.546875 },
{ x: 0.859375, y: 0.546875 },
{ x: 0.890625, y: 0.546875 },
{ x: 0.890625, y: 0.546875 },
{ x: 0.921875, y: 0.546875 },
{ x: 0.921875, y: 0.546875 },
{ x: 0.953125, y: 0.546875 },
{ x: 0.953125, y: 0.546875 },
{ x: 0.984375, y: 0.546875 },
{ x: 0.984375, y: 0.546875 },
{ x: 0.015625, y: 0.578125 },
{ x: 0.015625, y: 0.578125 },
{ x: 0.046875, y: 0.578125 },
{ x: 0.046875, y: 0.578125 },
{ x: 0.078125, y: 0.578125 },
{ x: 0.078125, y: 0.578125 },
{ x: 0.109375, y: 0.578125 },
{ x: 0.109375, y: 0.578125 },
{ x: 0.140625, y: 0.578125 },
{ x: 0.140625, y: 0.578125 },
{ x: 0.171875, y: 0.578125 },
{ x: 0.171875, y: 0.578125 },
{ x: 0.203125, y: 0.578125 },
{ x: 0.203125, y: 0.578125 },
{ x: 0.234375, y: 0.578125 },
{ x: 0.234375, y: 0.578125 },
{ x: 0.265625, y: 0.578125 },
{ x: 0.265625, y: 0.578125 },
{ x: 0.296875, y: 0.578125 },
{ x: 0.296875, y: 0.578125 },
{ x: 0.328125, y: 0.578125 },
{ x: 0.328125, y: 0.578125 },
{ x: 0.359375, y: 0.578125 },
{ x: 0.359375, y: 0.578125 },
{ x: 0.390625, y: 0.578125 },
{ x: 0.390625, y: 0.578125 },
{ x: 0.421875, y: 0.578125 },
{ x: 0.421875, y: 0.578125 },
{ x: 0.453125, y: 0.578125 },
{ x: 0.453125, y: 0.578125 },
{ x: 0.484375, y: 0.578125 },
{ x: 0.484375, y: 0.578125 },
{ x: 0.515625, y: 0.578125 },
{ x: 0.515625, y: 0.578125 },
{ x: 0.546875, y: 0.578125 },
{ x: 0.546875, y: 0.578125 },
{ x: 0.578125, y: 0.578125 },
{ x: 0.578125, y: 0.578125 },
{ x: 0.609375, y: 0.578125 },
{ x: 0.609375, y: 0.578125 },
{ x: 0.640625, y: 0.578125 },
{ x: 0.640625, y: 0.578125 },
{ x: 0.671875, y: 0.578125 },
{ x: 0.671875, y: 0.578125 },
{ x: 0.703125, y: 0.578125 },
{ x: 0.703125, y: 0.578125 },
{ x: 0.734375, y: 0.578125 },
{ x: 0.734375, y: 0.578125 },
{ x: 0.765625, y: 0.578125 },
{ x: 0.765625, y: 0.578125 },
{ x: 0.796875, y: 0.578125 },
{ x: 0.796875, y: 0.578125 },
{ x: 0.828125, y: 0.578125 },
{ x: 0.828125, y: 0.578125 },
{ x: 0.859375, y: 0.578125 },
{ x: 0.859375, y: 0.578125 },
{ x: 0.890625, y: 0.578125 },
{ x: 0.890625, y: 0.578125 },
{ x: 0.921875, y: 0.578125 },
{ x: 0.921875, y: 0.578125 },
{ x: 0.953125, y: 0.578125 },
{ x: 0.953125, y: 0.578125 },
{ x: 0.984375, y: 0.578125 },
{ x: 0.984375, y: 0.578125 },
{ x: 0.015625, y: 0.609375 },
{ x: 0.015625, y: 0.609375 },
{ x: 0.046875, y: 0.609375 },
{ x: 0.046875, y: 0.609375 },
{ x: 0.078125, y: 0.609375 },
{ x: 0.078125, y: 0.609375 },
{ x: 0.109375, y: 0.609375 },
{ x: 0.109375, y: 0.609375 },
{ x: 0.140625, y: 0.609375 },
{ x: 0.140625, y: 0.609375 },
{ x: 0.171875, y: 0.609375 },
{ x: 0.171875, y: 0.609375 },
{ x: 0.203125, y: 0.609375 },
{ x: 0.203125, y: 0.609375 },
{ x: 0.234375, y: 0.609375 },
{ x: 0.234375, y: 0.609375 },
{ x: 0.265625, y: 0.609375 },
{ x: 0.265625, y: 0.609375 },
{ x: 0.296875, y: 0.609375 },
{ x: 0.296875, y: 0.609375 },
{ x: 0.328125, y: 0.609375 },
{ x: 0.328125, y: 0.609375 },
{ x: 0.359375, y: 0.609375 },
{ x: 0.359375, y: 0.609375 },
{ x: 0.390625, y: 0.609375 },
{ x: 0.390625, y: 0.609375 },
{ x: 0.421875, y: 0.609375 },
{ x: 0.421875, y: 0.609375 },
{ x: 0.453125, y: 0.609375 },
{ x: 0.453125, y: 0.609375 },
{ x: 0.484375, y: 0.609375 },
{ x: 0.484375, y: 0.609375 },
{ x: 0.515625, y: 0.609375 },
{ x: 0.515625, y: 0.609375 },
{ x: 0.546875, y: 0.609375 },
{ x: 0.546875, y: 0.609375 },
{ x: 0.578125, y: 0.609375 },
{ x: 0.578125, y: 0.609375 },
{ x: 0.609375, y: 0.609375 },
{ x: 0.609375, y: 0.609375 },
{ x: 0.640625, y: 0.609375 },
{ x: 0.640625, y: 0.609375 },
{ x: 0.671875, y: 0.609375 },
{ x: 0.671875, y: 0.609375 },
{ x: 0.703125, y: 0.609375 },
{ x: 0.703125, y: 0.609375 },
{ x: 0.734375, y: 0.609375 },
{ x: 0.734375, y: 0.609375 },
{ x: 0.765625, y: 0.609375 },
{ x: 0.765625, y: 0.609375 },
{ x: 0.796875, y: 0.609375 },
{ x: 0.796875, y: 0.609375 },
{ x: 0.828125, y: 0.609375 },
{ x: 0.828125, y: 0.609375 },
{ x: 0.859375, y: 0.609375 },
{ x: 0.859375, y: 0.609375 },
{ x: 0.890625, y: 0.609375 },
{ x: 0.890625, y: 0.609375 },
{ x: 0.921875, y: 0.609375 },
{ x: 0.921875, y: 0.609375 },
{ x: 0.953125, y: 0.609375 },
{ x: 0.953125, y: 0.609375 },
{ x: 0.984375, y: 0.609375 },
{ x: 0.984375, y: 0.609375 },
{ x: 0.015625, y: 0.640625 },
{ x: 0.015625, y: 0.640625 },
{ x: 0.046875, y: 0.640625 },
{ x: 0.046875, y: 0.640625 },
{ x: 0.078125, y: 0.640625 },
{ x: 0.078125, y: 0.640625 },
{ x: 0.109375, y: 0.640625 },
{ x: 0.109375, y: 0.640625 },
{ x: 0.140625, y: 0.640625 },
{ x: 0.140625, y: 0.640625 },
{ x: 0.171875, y: 0.640625 },
{ x: 0.171875, y: 0.640625 },
{ x: 0.203125, y: 0.640625 },
{ x: 0.203125, y: 0.640625 },
{ x: 0.234375, y: 0.640625 },
{ x: 0.234375, y: 0.640625 },
{ x: 0.265625, y: 0.640625 },
{ x: 0.265625, y: 0.640625 },
{ x: 0.296875, y: 0.640625 },
{ x: 0.296875, y: 0.640625 },
{ x: 0.328125, y: 0.640625 },
{ x: 0.328125, y: 0.640625 },
{ x: 0.359375, y: 0.640625 },
{ x: 0.359375, y: 0.640625 },
{ x: 0.390625, y: 0.640625 },
{ x: 0.390625, y: 0.640625 },
{ x: 0.421875, y: 0.640625 },
{ x: 0.421875, y: 0.640625 },
{ x: 0.453125, y: 0.640625 },
{ x: 0.453125, y: 0.640625 },
{ x: 0.484375, y: 0.640625 },
{ x: 0.484375, y: 0.640625 },
{ x: 0.515625, y: 0.640625 },
{ x: 0.515625, y: 0.640625 },
{ x: 0.546875, y: 0.640625 },
{ x: 0.546875, y: 0.640625 },
{ x: 0.578125, y: 0.640625 },
{ x: 0.578125, y: 0.640625 },
{ x: 0.609375, y: 0.640625 },
{ x: 0.609375, y: 0.640625 },
{ x: 0.640625, y: 0.640625 },
{ x: 0.640625, y: 0.640625 },
{ x: 0.671875, y: 0.640625 },
{ x: 0.671875, y: 0.640625 },
{ x: 0.703125, y: 0.640625 },
{ x: 0.703125, y: 0.640625 },
{ x: 0.734375, y: 0.640625 },
{ x: 0.734375, y: 0.640625 },
{ x: 0.765625, y: 0.640625 },
{ x: 0.765625, y: 0.640625 },
{ x: 0.796875, y: 0.640625 },
{ x: 0.796875, y: 0.640625 },
{ x: 0.828125, y: 0.640625 },
{ x: 0.828125, y: 0.640625 },
{ x: 0.859375, y: 0.640625 },
{ x: 0.859375, y: 0.640625 },
{ x: 0.890625, y: 0.640625 },
{ x: 0.890625, y: 0.640625 },
{ x: 0.921875, y: 0.640625 },
{ x: 0.921875, y: 0.640625 },
{ x: 0.953125, y: 0.640625 },
{ x: 0.953125, y: 0.640625 },
{ x: 0.984375, y: 0.640625 },
{ x: 0.984375, y: 0.640625 },
{ x: 0.015625, y: 0.671875 },
{ x: 0.015625, y: 0.671875 },
{ x: 0.046875, y: 0.671875 },
{ x: 0.046875, y: 0.671875 },
{ x: 0.078125, y: 0.671875 },
{ x: 0.078125, y: 0.671875 },
{ x: 0.109375, y: 0.671875 },
{ x: 0.109375, y: 0.671875 },
{ x: 0.140625, y: 0.671875 },
{ x: 0.140625, y: 0.671875 },
{ x: 0.171875, y: 0.671875 },
{ x: 0.171875, y: 0.671875 },
{ x: 0.203125, y: 0.671875 },
{ x: 0.203125, y: 0.671875 },
{ x: 0.234375, y: 0.671875 },
{ x: 0.234375, y: 0.671875 },
{ x: 0.265625, y: 0.671875 },
{ x: 0.265625, y: 0.671875 },
{ x: 0.296875, y: 0.671875 },
{ x: 0.296875, y: 0.671875 },
{ x: 0.328125, y: 0.671875 },
{ x: 0.328125, y: 0.671875 },
{ x: 0.359375, y: 0.671875 },
{ x: 0.359375, y: 0.671875 },
{ x: 0.390625, y: 0.671875 },
{ x: 0.390625, y: 0.671875 },
{ x: 0.421875, y: 0.671875 },
{ x: 0.421875, y: 0.671875 },
{ x: 0.453125, y: 0.671875 },
{ x: 0.453125, y: 0.671875 },
{ x: 0.484375, y: 0.671875 },
{ x: 0.484375, y: 0.671875 },
{ x: 0.515625, y: 0.671875 },
{ x: 0.515625, y: 0.671875 },
{ x: 0.546875, y: 0.671875 },
{ x: 0.546875, y: 0.671875 },
{ x: 0.578125, y: 0.671875 },
{ x: 0.578125, y: 0.671875 },
{ x: 0.609375, y: 0.671875 },
{ x: 0.609375, y: 0.671875 },
{ x: 0.640625, y: 0.671875 },
{ x: 0.640625, y: 0.671875 },
{ x: 0.671875, y: 0.671875 },
{ x: 0.671875, y: 0.671875 },
{ x: 0.703125, y: 0.671875 },
{ x: 0.703125, y: 0.671875 },
{ x: 0.734375, y: 0.671875 },
{ x: 0.734375, y: 0.671875 },
{ x: 0.765625, y: 0.671875 },
{ x: 0.765625, y: 0.671875 },
{ x: 0.796875, y: 0.671875 },
{ x: 0.796875, y: 0.671875 },
{ x: 0.828125, y: 0.671875 },
{ x: 0.828125, y: 0.671875 },
{ x: 0.859375, y: 0.671875 },
{ x: 0.859375, y: 0.671875 },
{ x: 0.890625, y: 0.671875 },
{ x: 0.890625, y: 0.671875 },
{ x: 0.921875, y: 0.671875 },
{ x: 0.921875, y: 0.671875 },
{ x: 0.953125, y: 0.671875 },
{ x: 0.953125, y: 0.671875 },
{ x: 0.984375, y: 0.671875 },
{ x: 0.984375, y: 0.671875 },
{ x: 0.015625, y: 0.703125 },
{ x: 0.015625, y: 0.703125 },
{ x: 0.046875, y: 0.703125 },
{ x: 0.046875, y: 0.703125 },
{ x: 0.078125, y: 0.703125 },
{ x: 0.078125, y: 0.703125 },
{ x: 0.109375, y: 0.703125 },
{ x: 0.109375, y: 0.703125 },
{ x: 0.140625, y: 0.703125 },
{ x: 0.140625, y: 0.703125 },
{ x: 0.171875, y: 0.703125 },
{ x: 0.171875, y: 0.703125 },
{ x: 0.203125, y: 0.703125 },
{ x: 0.203125, y: 0.703125 },
{ x: 0.234375, y: 0.703125 },
{ x: 0.234375, y: 0.703125 },
{ x: 0.265625, y: 0.703125 },
{ x: 0.265625, y: 0.703125 },
{ x: 0.296875, y: 0.703125 },
{ x: 0.296875, y: 0.703125 },
{ x: 0.328125, y: 0.703125 },
{ x: 0.328125, y: 0.703125 },
{ x: 0.359375, y: 0.703125 },
{ x: 0.359375, y: 0.703125 },
{ x: 0.390625, y: 0.703125 },
{ x: 0.390625, y: 0.703125 },
{ x: 0.421875, y: 0.703125 },
{ x: 0.421875, y: 0.703125 },
{ x: 0.453125, y: 0.703125 },
{ x: 0.453125, y: 0.703125 },
{ x: 0.484375, y: 0.703125 },
{ x: 0.484375, y: 0.703125 },
{ x: 0.515625, y: 0.703125 },
{ x: 0.515625, y: 0.703125 },
{ x: 0.546875, y: 0.703125 },
{ x: 0.546875, y: 0.703125 },
{ x: 0.578125, y: 0.703125 },
{ x: 0.578125, y: 0.703125 },
{ x: 0.609375, y: 0.703125 },
{ x: 0.609375, y: 0.703125 },
{ x: 0.640625, y: 0.703125 },
{ x: 0.640625, y: 0.703125 },
{ x: 0.671875, y: 0.703125 },
{ x: 0.671875, y: 0.703125 },
{ x: 0.703125, y: 0.703125 },
{ x: 0.703125, y: 0.703125 },
{ x: 0.734375, y: 0.703125 },
{ x: 0.734375, y: 0.703125 },
{ x: 0.765625, y: 0.703125 },
{ x: 0.765625, y: 0.703125 },
{ x: 0.796875, y: 0.703125 },
{ x: 0.796875, y: 0.703125 },
{ x: 0.828125, y: 0.703125 },
{ x: 0.828125, y: 0.703125 },
{ x: 0.859375, y: 0.703125 },
{ x: 0.859375, y: 0.703125 },
{ x: 0.890625, y: 0.703125 },
{ x: 0.890625, y: 0.703125 },
{ x: 0.921875, y: 0.703125 },
{ x: 0.921875, y: 0.703125 },
{ x: 0.953125, y: 0.703125 },
{ x: 0.953125, y: 0.703125 },
{ x: 0.984375, y: 0.703125 },
{ x: 0.984375, y: 0.703125 },
{ x: 0.015625, y: 0.734375 },
{ x: 0.015625, y: 0.734375 },
{ x: 0.046875, y: 0.734375 },
{ x: 0.046875, y: 0.734375 },
{ x: 0.078125, y: 0.734375 },
{ x: 0.078125, y: 0.734375 },
{ x: 0.109375, y: 0.734375 },
{ x: 0.109375, y: 0.734375 },
{ x: 0.140625, y: 0.734375 },
{ x: 0.140625, y: 0.734375 },
{ x: 0.171875, y: 0.734375 },
{ x: 0.171875, y: 0.734375 },
{ x: 0.203125, y: 0.734375 },
{ x: 0.203125, y: 0.734375 },
{ x: 0.234375, y: 0.734375 },
{ x: 0.234375, y: 0.734375 },
{ x: 0.265625, y: 0.734375 },
{ x: 0.265625, y: 0.734375 },
{ x: 0.296875, y: 0.734375 },
{ x: 0.296875, y: 0.734375 },
{ x: 0.328125, y: 0.734375 },
{ x: 0.328125, y: 0.734375 },
{ x: 0.359375, y: 0.734375 },
{ x: 0.359375, y: 0.734375 },
{ x: 0.390625, y: 0.734375 },
{ x: 0.390625, y: 0.734375 },
{ x: 0.421875, y: 0.734375 },
{ x: 0.421875, y: 0.734375 },
{ x: 0.453125, y: 0.734375 },
{ x: 0.453125, y: 0.734375 },
{ x: 0.484375, y: 0.734375 },
{ x: 0.484375, y: 0.734375 },
{ x: 0.515625, y: 0.734375 },
{ x: 0.515625, y: 0.734375 },
{ x: 0.546875, y: 0.734375 },
{ x: 0.546875, y: 0.734375 },
{ x: 0.578125, y: 0.734375 },
{ x: 0.578125, y: 0.734375 },
{ x: 0.609375, y: 0.734375 },
{ x: 0.609375, y: 0.734375 },
{ x: 0.640625, y: 0.734375 },
{ x: 0.640625, y: 0.734375 },
{ x: 0.671875, y: 0.734375 },
{ x: 0.671875, y: 0.734375 },
{ x: 0.703125, y: 0.734375 },
{ x: 0.703125, y: 0.734375 },
{ x: 0.734375, y: 0.734375 },
{ x: 0.734375, y: 0.734375 },
{ x: 0.765625, y: 0.734375 },
{ x: 0.765625, y: 0.734375 },
{ x: 0.796875, y: 0.734375 },
{ x: 0.796875, y: 0.734375 },
{ x: 0.828125, y: 0.734375 },
{ x: 0.828125, y: 0.734375 },
{ x: 0.859375, y: 0.734375 },
{ x: 0.859375, y: 0.734375 },
{ x: 0.890625, y: 0.734375 },
{ x: 0.890625, y: 0.734375 },
{ x: 0.921875, y: 0.734375 },
{ x: 0.921875, y: 0.734375 },
{ x: 0.953125, y: 0.734375 },
{ x: 0.953125, y: 0.734375 },
{ x: 0.984375, y: 0.734375 },
{ x: 0.984375, y: 0.734375 },
{ x: 0.015625, y: 0.765625 },
{ x: 0.015625, y: 0.765625 },
{ x: 0.046875, y: 0.765625 },
{ x: 0.046875, y: 0.765625 },
{ x: 0.078125, y: 0.765625 },
{ x: 0.078125, y: 0.765625 },
{ x: 0.109375, y: 0.765625 },
{ x: 0.109375, y: 0.765625 },
{ x: 0.140625, y: 0.765625 },
{ x: 0.140625, y: 0.765625 },
{ x: 0.171875, y: 0.765625 },
{ x: 0.171875, y: 0.765625 },
{ x: 0.203125, y: 0.765625 },
{ x: 0.203125, y: 0.765625 },
{ x: 0.234375, y: 0.765625 },
{ x: 0.234375, y: 0.765625 },
{ x: 0.265625, y: 0.765625 },
{ x: 0.265625, y: 0.765625 },
{ x: 0.296875, y: 0.765625 },
{ x: 0.296875, y: 0.765625 },
{ x: 0.328125, y: 0.765625 },
{ x: 0.328125, y: 0.765625 },
{ x: 0.359375, y: 0.765625 },
{ x: 0.359375, y: 0.765625 },
{ x: 0.390625, y: 0.765625 },
{ x: 0.390625, y: 0.765625 },
{ x: 0.421875, y: 0.765625 },
{ x: 0.421875, y: 0.765625 },
{ x: 0.453125, y: 0.765625 },
{ x: 0.453125, y: 0.765625 },
{ x: 0.484375, y: 0.765625 },
{ x: 0.484375, y: 0.765625 },
{ x: 0.515625, y: 0.765625 },
{ x: 0.515625, y: 0.765625 },
{ x: 0.546875, y: 0.765625 },
{ x: 0.546875, y: 0.765625 },
{ x: 0.578125, y: 0.765625 },
{ x: 0.578125, y: 0.765625 },
{ x: 0.609375, y: 0.765625 },
{ x: 0.609375, y: 0.765625 },
{ x: 0.640625, y: 0.765625 },
{ x: 0.640625, y: 0.765625 },
{ x: 0.671875, y: 0.765625 },
{ x: 0.671875, y: 0.765625 },
{ x: 0.703125, y: 0.765625 },
{ x: 0.703125, y: 0.765625 },
{ x: 0.734375, y: 0.765625 },
{ x: 0.734375, y: 0.765625 },
{ x: 0.765625, y: 0.765625 },
{ x: 0.765625, y: 0.765625 },
{ x: 0.796875, y: 0.765625 },
{ x: 0.796875, y: 0.765625 },
{ x: 0.828125, y: 0.765625 },
{ x: 0.828125, y: 0.765625 },
{ x: 0.859375, y: 0.765625 },
{ x: 0.859375, y: 0.765625 },
{ x: 0.890625, y: 0.765625 },
{ x: 0.890625, y: 0.765625 },
{ x: 0.921875, y: 0.765625 },
{ x: 0.921875, y: 0.765625 },
{ x: 0.953125, y: 0.765625 },
{ x: 0.953125, y: 0.765625 },
{ x: 0.984375, y: 0.765625 },
{ x: 0.984375, y: 0.765625 },
{ x: 0.015625, y: 0.796875 },
{ x: 0.015625, y: 0.796875 },
{ x: 0.046875, y: 0.796875 },
{ x: 0.046875, y: 0.796875 },
{ x: 0.078125, y: 0.796875 },
{ x: 0.078125, y: 0.796875 },
{ x: 0.109375, y: 0.796875 },
{ x: 0.109375, y: 0.796875 },
{ x: 0.140625, y: 0.796875 },
{ x: 0.140625, y: 0.796875 },
{ x: 0.171875, y: 0.796875 },
{ x: 0.171875, y: 0.796875 },
{ x: 0.203125, y: 0.796875 },
{ x: 0.203125, y: 0.796875 },
{ x: 0.234375, y: 0.796875 },
{ x: 0.234375, y: 0.796875 },
{ x: 0.265625, y: 0.796875 },
{ x: 0.265625, y: 0.796875 },
{ x: 0.296875, y: 0.796875 },
{ x: 0.296875, y: 0.796875 },
{ x: 0.328125, y: 0.796875 },
{ x: 0.328125, y: 0.796875 },
{ x: 0.359375, y: 0.796875 },
{ x: 0.359375, y: 0.796875 },
{ x: 0.390625, y: 0.796875 },
{ x: 0.390625, y: 0.796875 },
{ x: 0.421875, y: 0.796875 },
{ x: 0.421875, y: 0.796875 },
{ x: 0.453125, y: 0.796875 },
{ x: 0.453125, y: 0.796875 },
{ x: 0.484375, y: 0.796875 },
{ x: 0.484375, y: 0.796875 },
{ x: 0.515625, y: 0.796875 },
{ x: 0.515625, y: 0.796875 },
{ x: 0.546875, y: 0.796875 },
{ x: 0.546875, y: 0.796875 },
{ x: 0.578125, y: 0.796875 },
{ x: 0.578125, y: 0.796875 },
{ x: 0.609375, y: 0.796875 },
{ x: 0.609375, y: 0.796875 },
{ x: 0.640625, y: 0.796875 },
{ x: 0.640625, y: 0.796875 },
{ x: 0.671875, y: 0.796875 },
{ x: 0.671875, y: 0.796875 },
{ x: 0.703125, y: 0.796875 },
{ x: 0.703125, y: 0.796875 },
{ x: 0.734375, y: 0.796875 },
{ x: 0.734375, y: 0.796875 },
{ x: 0.765625, y: 0.796875 },
{ x: 0.765625, y: 0.796875 },
{ x: 0.796875, y: 0.796875 },
{ x: 0.796875, y: 0.796875 },
{ x: 0.828125, y: 0.796875 },
{ x: 0.828125, y: 0.796875 },
{ x: 0.859375, y: 0.796875 },
{ x: 0.859375, y: 0.796875 },
{ x: 0.890625, y: 0.796875 },
{ x: 0.890625, y: 0.796875 },
{ x: 0.921875, y: 0.796875 },
{ x: 0.921875, y: 0.796875 },
{ x: 0.953125, y: 0.796875 },
{ x: 0.953125, y: 0.796875 },
{ x: 0.984375, y: 0.796875 },
{ x: 0.984375, y: 0.796875 },
{ x: 0.015625, y: 0.828125 },
{ x: 0.015625, y: 0.828125 },
{ x: 0.046875, y: 0.828125 },
{ x: 0.046875, y: 0.828125 },
{ x: 0.078125, y: 0.828125 },
{ x: 0.078125, y: 0.828125 },
{ x: 0.109375, y: 0.828125 },
{ x: 0.109375, y: 0.828125 },
{ x: 0.140625, y: 0.828125 },
{ x: 0.140625, y: 0.828125 },
{ x: 0.171875, y: 0.828125 },
{ x: 0.171875, y: 0.828125 },
{ x: 0.203125, y: 0.828125 },
{ x: 0.203125, y: 0.828125 },
{ x: 0.234375, y: 0.828125 },
{ x: 0.234375, y: 0.828125 },
{ x: 0.265625, y: 0.828125 },
{ x: 0.265625, y: 0.828125 },
{ x: 0.296875, y: 0.828125 },
{ x: 0.296875, y: 0.828125 },
{ x: 0.328125, y: 0.828125 },
{ x: 0.328125, y: 0.828125 },
{ x: 0.359375, y: 0.828125 },
{ x: 0.359375, y: 0.828125 },
{ x: 0.390625, y: 0.828125 },
{ x: 0.390625, y: 0.828125 },
{ x: 0.421875, y: 0.828125 },
{ x: 0.421875, y: 0.828125 },
{ x: 0.453125, y: 0.828125 },
{ x: 0.453125, y: 0.828125 },
{ x: 0.484375, y: 0.828125 },
{ x: 0.484375, y: 0.828125 },
{ x: 0.515625, y: 0.828125 },
{ x: 0.515625, y: 0.828125 },
{ x: 0.546875, y: 0.828125 },
{ x: 0.546875, y: 0.828125 },
{ x: 0.578125, y: 0.828125 },
{ x: 0.578125, y: 0.828125 },
{ x: 0.609375, y: 0.828125 },
{ x: 0.609375, y: 0.828125 },
{ x: 0.640625, y: 0.828125 },
{ x: 0.640625, y: 0.828125 },
{ x: 0.671875, y: 0.828125 },
{ x: 0.671875, y: 0.828125 },
{ x: 0.703125, y: 0.828125 },
{ x: 0.703125, y: 0.828125 },
{ x: 0.734375, y: 0.828125 },
{ x: 0.734375, y: 0.828125 },
{ x: 0.765625, y: 0.828125 },
{ x: 0.765625, y: 0.828125 },
{ x: 0.796875, y: 0.828125 },
{ x: 0.796875, y: 0.828125 },
{ x: 0.828125, y: 0.828125 },
{ x: 0.828125, y: 0.828125 },
{ x: 0.859375, y: 0.828125 },
{ x: 0.859375, y: 0.828125 },
{ x: 0.890625, y: 0.828125 },
{ x: 0.890625, y: 0.828125 },
{ x: 0.921875, y: 0.828125 },
{ x: 0.921875, y: 0.828125 },
{ x: 0.953125, y: 0.828125 },
{ x: 0.953125, y: 0.828125 },
{ x: 0.984375, y: 0.828125 },
{ x: 0.984375, y: 0.828125 },
{ x: 0.015625, y: 0.859375 },
{ x: 0.015625, y: 0.859375 },
{ x: 0.046875, y: 0.859375 },
{ x: 0.046875, y: 0.859375 },
{ x: 0.078125, y: 0.859375 },
{ x: 0.078125, y: 0.859375 },
{ x: 0.109375, y: 0.859375 },
{ x: 0.109375, y: 0.859375 },
{ x: 0.140625, y: 0.859375 },
{ x: 0.140625, y: 0.859375 },
{ x: 0.171875, y: 0.859375 },
{ x: 0.171875, y: 0.859375 },
{ x: 0.203125, y: 0.859375 },
{ x: 0.203125, y: 0.859375 },
{ x: 0.234375, y: 0.859375 },
{ x: 0.234375, y: 0.859375 },
{ x: 0.265625, y: 0.859375 },
{ x: 0.265625, y: 0.859375 },
{ x: 0.296875, y: 0.859375 },
{ x: 0.296875, y: 0.859375 },
{ x: 0.328125, y: 0.859375 },
{ x: 0.328125, y: 0.859375 },
{ x: 0.359375, y: 0.859375 },
{ x: 0.359375, y: 0.859375 },
{ x: 0.390625, y: 0.859375 },
{ x: 0.390625, y: 0.859375 },
{ x: 0.421875, y: 0.859375 },
{ x: 0.421875, y: 0.859375 },
{ x: 0.453125, y: 0.859375 },
{ x: 0.453125, y: 0.859375 },
{ x: 0.484375, y: 0.859375 },
{ x: 0.484375, y: 0.859375 },
{ x: 0.515625, y: 0.859375 },
{ x: 0.515625, y: 0.859375 },
{ x: 0.546875, y: 0.859375 },
{ x: 0.546875, y: 0.859375 },
{ x: 0.578125, y: 0.859375 },
{ x: 0.578125, y: 0.859375 },
{ x: 0.609375, y: 0.859375 },
{ x: 0.609375, y: 0.859375 },
{ x: 0.640625, y: 0.859375 },
{ x: 0.640625, y: 0.859375 },
{ x: 0.671875, y: 0.859375 },
{ x: 0.671875, y: 0.859375 },
{ x: 0.703125, y: 0.859375 },
{ x: 0.703125, y: 0.859375 },
{ x: 0.734375, y: 0.859375 },
{ x: 0.734375, y: 0.859375 },
{ x: 0.765625, y: 0.859375 },
{ x: 0.765625, y: 0.859375 },
{ x: 0.796875, y: 0.859375 },
{ x: 0.796875, y: 0.859375 },
{ x: 0.828125, y: 0.859375 },
{ x: 0.828125, y: 0.859375 },
{ x: 0.859375, y: 0.859375 },
{ x: 0.859375, y: 0.859375 },
{ x: 0.890625, y: 0.859375 },
{ x: 0.890625, y: 0.859375 },
{ x: 0.921875, y: 0.859375 },
{ x: 0.921875, y: 0.859375 },
{ x: 0.953125, y: 0.859375 },
{ x: 0.953125, y: 0.859375 },
{ x: 0.984375, y: 0.859375 },
{ x: 0.984375, y: 0.859375 },
{ x: 0.015625, y: 0.890625 },
{ x: 0.015625, y: 0.890625 },
{ x: 0.046875, y: 0.890625 },
{ x: 0.046875, y: 0.890625 },
{ x: 0.078125, y: 0.890625 },
{ x: 0.078125, y: 0.890625 },
{ x: 0.109375, y: 0.890625 },
{ x: 0.109375, y: 0.890625 },
{ x: 0.140625, y: 0.890625 },
{ x: 0.140625, y: 0.890625 },
{ x: 0.171875, y: 0.890625 },
{ x: 0.171875, y: 0.890625 },
{ x: 0.203125, y: 0.890625 },
{ x: 0.203125, y: 0.890625 },
{ x: 0.234375, y: 0.890625 },
{ x: 0.234375, y: 0.890625 },
{ x: 0.265625, y: 0.890625 },
{ x: 0.265625, y: 0.890625 },
{ x: 0.296875, y: 0.890625 },
{ x: 0.296875, y: 0.890625 },
{ x: 0.328125, y: 0.890625 },
{ x: 0.328125, y: 0.890625 },
{ x: 0.359375, y: 0.890625 },
{ x: 0.359375, y: 0.890625 },
{ x: 0.390625, y: 0.890625 },
{ x: 0.390625, y: 0.890625 },
{ x: 0.421875, y: 0.890625 },
{ x: 0.421875, y: 0.890625 },
{ x: 0.453125, y: 0.890625 },
{ x: 0.453125, y: 0.890625 },
{ x: 0.484375, y: 0.890625 },
{ x: 0.484375, y: 0.890625 },
{ x: 0.515625, y: 0.890625 },
{ x: 0.515625, y: 0.890625 },
{ x: 0.546875, y: 0.890625 },
{ x: 0.546875, y: 0.890625 },
{ x: 0.578125, y: 0.890625 },
{ x: 0.578125, y: 0.890625 },
{ x: 0.609375, y: 0.890625 },
{ x: 0.609375, y: 0.890625 },
{ x: 0.640625, y: 0.890625 },
{ x: 0.640625, y: 0.890625 },
{ x: 0.671875, y: 0.890625 },
{ x: 0.671875, y: 0.890625 },
{ x: 0.703125, y: 0.890625 },
{ x: 0.703125, y: 0.890625 },
{ x: 0.734375, y: 0.890625 },
{ x: 0.734375, y: 0.890625 },
{ x: 0.765625, y: 0.890625 },
{ x: 0.765625, y: 0.890625 },
{ x: 0.796875, y: 0.890625 },
{ x: 0.796875, y: 0.890625 },
{ x: 0.828125, y: 0.890625 },
{ x: 0.828125, y: 0.890625 },
{ x: 0.859375, y: 0.890625 },
{ x: 0.859375, y: 0.890625 },
{ x: 0.890625, y: 0.890625 },
{ x: 0.890625, y: 0.890625 },
{ x: 0.921875, y: 0.890625 },
{ x: 0.921875, y: 0.890625 },
{ x: 0.953125, y: 0.890625 },
{ x: 0.953125, y: 0.890625 },
{ x: 0.984375, y: 0.890625 },
{ x: 0.984375, y: 0.890625 },
{ x: 0.015625, y: 0.921875 },
{ x: 0.015625, y: 0.921875 },
{ x: 0.046875, y: 0.921875 },
{ x: 0.046875, y: 0.921875 },
{ x: 0.078125, y: 0.921875 },
{ x: 0.078125, y: 0.921875 },
{ x: 0.109375, y: 0.921875 },
{ x: 0.109375, y: 0.921875 },
{ x: 0.140625, y: 0.921875 },
{ x: 0.140625, y: 0.921875 },
{ x: 0.171875, y: 0.921875 },
{ x: 0.171875, y: 0.921875 },
{ x: 0.203125, y: 0.921875 },
{ x: 0.203125, y: 0.921875 },
{ x: 0.234375, y: 0.921875 },
{ x: 0.234375, y: 0.921875 },
{ x: 0.265625, y: 0.921875 },
{ x: 0.265625, y: 0.921875 },
{ x: 0.296875, y: 0.921875 },
{ x: 0.296875, y: 0.921875 },
{ x: 0.328125, y: 0.921875 },
{ x: 0.328125, y: 0.921875 },
{ x: 0.359375, y: 0.921875 },
{ x: 0.359375, y: 0.921875 },
{ x: 0.390625, y: 0.921875 },
{ x: 0.390625, y: 0.921875 },
{ x: 0.421875, y: 0.921875 },
{ x: 0.421875, y: 0.921875 },
{ x: 0.453125, y: 0.921875 },
{ x: 0.453125, y: 0.921875 },
{ x: 0.484375, y: 0.921875 },
{ x: 0.484375, y: 0.921875 },
{ x: 0.515625, y: 0.921875 },
{ x: 0.515625, y: 0.921875 },
{ x: 0.546875, y: 0.921875 },
{ x: 0.546875, y: 0.921875 },
{ x: 0.578125, y: 0.921875 },
{ x: 0.578125, y: 0.921875 },
{ x: 0.609375, y: 0.921875 },
{ x: 0.609375, y: 0.921875 },
{ x: 0.640625, y: 0.921875 },
{ x: 0.640625, y: 0.921875 },
{ x: 0.671875, y: 0.921875 },
{ x: 0.671875, y: 0.921875 },
{ x: 0.703125, y: 0.921875 },
{ x: 0.703125, y: 0.921875 },
{ x: 0.734375, y: 0.921875 },
{ x: 0.734375, y: 0.921875 },
{ x: 0.765625, y: 0.921875 },
{ x: 0.765625, y: 0.921875 },
{ x: 0.796875, y: 0.921875 },
{ x: 0.796875, y: 0.921875 },
{ x: 0.828125, y: 0.921875 },
{ x: 0.828125, y: 0.921875 },
{ x: 0.859375, y: 0.921875 },
{ x: 0.859375, y: 0.921875 },
{ x: 0.890625, y: 0.921875 },
{ x: 0.890625, y: 0.921875 },
{ x: 0.921875, y: 0.921875 },
{ x: 0.921875, y: 0.921875 },
{ x: 0.953125, y: 0.921875 },
{ x: 0.953125, y: 0.921875 },
{ x: 0.984375, y: 0.921875 },
{ x: 0.984375, y: 0.921875 },
{ x: 0.015625, y: 0.953125 },
{ x: 0.015625, y: 0.953125 },
{ x: 0.046875, y: 0.953125 },
{ x: 0.046875, y: 0.953125 },
{ x: 0.078125, y: 0.953125 },
{ x: 0.078125, y: 0.953125 },
{ x: 0.109375, y: 0.953125 },
{ x: 0.109375, y: 0.953125 },
{ x: 0.140625, y: 0.953125 },
{ x: 0.140625, y: 0.953125 },
{ x: 0.171875, y: 0.953125 },
{ x: 0.171875, y: 0.953125 },
{ x: 0.203125, y: 0.953125 },
{ x: 0.203125, y: 0.953125 },
{ x: 0.234375, y: 0.953125 },
{ x: 0.234375, y: 0.953125 },
{ x: 0.265625, y: 0.953125 },
{ x: 0.265625, y: 0.953125 },
{ x: 0.296875, y: 0.953125 },
{ x: 0.296875, y: 0.953125 },
{ x: 0.328125, y: 0.953125 },
{ x: 0.328125, y: 0.953125 },
{ x: 0.359375, y: 0.953125 },
{ x: 0.359375, y: 0.953125 },
{ x: 0.390625, y: 0.953125 },
{ x: 0.390625, y: 0.953125 },
{ x: 0.421875, y: 0.953125 },
{ x: 0.421875, y: 0.953125 },
{ x: 0.453125, y: 0.953125 },
{ x: 0.453125, y: 0.953125 },
{ x: 0.484375, y: 0.953125 },
{ x: 0.484375, y: 0.953125 },
{ x: 0.515625, y: 0.953125 },
{ x: 0.515625, y: 0.953125 },
{ x: 0.546875, y: 0.953125 },
{ x: 0.546875, y: 0.953125 },
{ x: 0.578125, y: 0.953125 },
{ x: 0.578125, y: 0.953125 },
{ x: 0.609375, y: 0.953125 },
{ x: 0.609375, y: 0.953125 },
{ x: 0.640625, y: 0.953125 },
{ x: 0.640625, y: 0.953125 },
{ x: 0.671875, y: 0.953125 },
{ x: 0.671875, y: 0.953125 },
{ x: 0.703125, y: 0.953125 },
{ x: 0.703125, y: 0.953125 },
{ x: 0.734375, y: 0.953125 },
{ x: 0.734375, y: 0.953125 },
{ x: 0.765625, y: 0.953125 },
{ x: 0.765625, y: 0.953125 },
{ x: 0.796875, y: 0.953125 },
{ x: 0.796875, y: 0.953125 },
{ x: 0.828125, y: 0.953125 },
{ x: 0.828125, y: 0.953125 },
{ x: 0.859375, y: 0.953125 },
{ x: 0.859375, y: 0.953125 },
{ x: 0.890625, y: 0.953125 },
{ x: 0.890625, y: 0.953125 },
{ x: 0.921875, y: 0.953125 },
{ x: 0.921875, y: 0.953125 },
{ x: 0.953125, y: 0.953125 },
{ x: 0.953125, y: 0.953125 },
{ x: 0.984375, y: 0.953125 },
{ x: 0.984375, y: 0.953125 },
{ x: 0.015625, y: 0.984375 },
{ x: 0.015625, y: 0.984375 },
{ x: 0.046875, y: 0.984375 },
{ x: 0.046875, y: 0.984375 },
{ x: 0.078125, y: 0.984375 },
{ x: 0.078125, y: 0.984375 },
{ x: 0.109375, y: 0.984375 },
{ x: 0.109375, y: 0.984375 },
{ x: 0.140625, y: 0.984375 },
{ x: 0.140625, y: 0.984375 },
{ x: 0.171875, y: 0.984375 },
{ x: 0.171875, y: 0.984375 },
{ x: 0.203125, y: 0.984375 },
{ x: 0.203125, y: 0.984375 },
{ x: 0.234375, y: 0.984375 },
{ x: 0.234375, y: 0.984375 },
{ x: 0.265625, y: 0.984375 },
{ x: 0.265625, y: 0.984375 },
{ x: 0.296875, y: 0.984375 },
{ x: 0.296875, y: 0.984375 },
{ x: 0.328125, y: 0.984375 },
{ x: 0.328125, y: 0.984375 },
{ x: 0.359375, y: 0.984375 },
{ x: 0.359375, y: 0.984375 },
{ x: 0.390625, y: 0.984375 },
{ x: 0.390625, y: 0.984375 },
{ x: 0.421875, y: 0.984375 },
{ x: 0.421875, y: 0.984375 },
{ x: 0.453125, y: 0.984375 },
{ x: 0.453125, y: 0.984375 },
{ x: 0.484375, y: 0.984375 },
{ x: 0.484375, y: 0.984375 },
{ x: 0.515625, y: 0.984375 },
{ x: 0.515625, y: 0.984375 },
{ x: 0.546875, y: 0.984375 },
{ x: 0.546875, y: 0.984375 },
{ x: 0.578125, y: 0.984375 },
{ x: 0.578125, y: 0.984375 },
{ x: 0.609375, y: 0.984375 },
{ x: 0.609375, y: 0.984375 },
{ x: 0.640625, y: 0.984375 },
{ x: 0.640625, y: 0.984375 },
{ x: 0.671875, y: 0.984375 },
{ x: 0.671875, y: 0.984375 },
{ x: 0.703125, y: 0.984375 },
{ x: 0.703125, y: 0.984375 },
{ x: 0.734375, y: 0.984375 },
{ x: 0.734375, y: 0.984375 },
{ x: 0.765625, y: 0.984375 },
{ x: 0.765625, y: 0.984375 },
{ x: 0.796875, y: 0.984375 },
{ x: 0.796875, y: 0.984375 },
{ x: 0.828125, y: 0.984375 },
{ x: 0.828125, y: 0.984375 },
{ x: 0.859375, y: 0.984375 },
{ x: 0.859375, y: 0.984375 },
{ x: 0.890625, y: 0.984375 },
{ x: 0.890625, y: 0.984375 },
{ x: 0.921875, y: 0.984375 },
{ x: 0.921875, y: 0.984375 },
{ x: 0.953125, y: 0.984375 },
{ x: 0.953125, y: 0.984375 },
{ x: 0.984375, y: 0.984375 },
{ x: 0.984375, y: 0.984375 },
{ x: 0.03125, y: 0.03125 },
{ x: 0.03125, y: 0.03125 },
{ x: 0.09375, y: 0.03125 },
{ x: 0.09375, y: 0.03125 },
{ x: 0.15625, y: 0.03125 },
{ x: 0.15625, y: 0.03125 },
{ x: 0.21875, y: 0.03125 },
{ x: 0.21875, y: 0.03125 },
{ x: 0.28125, y: 0.03125 },
{ x: 0.28125, y: 0.03125 },
{ x: 0.34375, y: 0.03125 },
{ x: 0.34375, y: 0.03125 },
{ x: 0.40625, y: 0.03125 },
{ x: 0.40625, y: 0.03125 },
{ x: 0.46875, y: 0.03125 },
{ x: 0.46875, y: 0.03125 },
{ x: 0.53125, y: 0.03125 },
{ x: 0.53125, y: 0.03125 },
{ x: 0.59375, y: 0.03125 },
{ x: 0.59375, y: 0.03125 },
{ x: 0.65625, y: 0.03125 },
{ x: 0.65625, y: 0.03125 },
{ x: 0.71875, y: 0.03125 },
{ x: 0.71875, y: 0.03125 },
{ x: 0.78125, y: 0.03125 },
{ x: 0.78125, y: 0.03125 },
{ x: 0.84375, y: 0.03125 },
{ x: 0.84375, y: 0.03125 },
{ x: 0.90625, y: 0.03125 },
{ x: 0.90625, y: 0.03125 },
{ x: 0.96875, y: 0.03125 },
{ x: 0.96875, y: 0.03125 },
{ x: 0.03125, y: 0.09375 },
{ x: 0.03125, y: 0.09375 },
{ x: 0.09375, y: 0.09375 },
{ x: 0.09375, y: 0.09375 },
{ x: 0.15625, y: 0.09375 },
{ x: 0.15625, y: 0.09375 },
{ x: 0.21875, y: 0.09375 },
{ x: 0.21875, y: 0.09375 },
{ x: 0.28125, y: 0.09375 },
{ x: 0.28125, y: 0.09375 },
{ x: 0.34375, y: 0.09375 },
{ x: 0.34375, y: 0.09375 },
{ x: 0.40625, y: 0.09375 },
{ x: 0.40625, y: 0.09375 },
{ x: 0.46875, y: 0.09375 },
{ x: 0.46875, y: 0.09375 },
{ x: 0.53125, y: 0.09375 },
{ x: 0.53125, y: 0.09375 },
{ x: 0.59375, y: 0.09375 },
{ x: 0.59375, y: 0.09375 },
{ x: 0.65625, y: 0.09375 },
{ x: 0.65625, y: 0.09375 },
{ x: 0.71875, y: 0.09375 },
{ x: 0.71875, y: 0.09375 },
{ x: 0.78125, y: 0.09375 },
{ x: 0.78125, y: 0.09375 },
{ x: 0.84375, y: 0.09375 },
{ x: 0.84375, y: 0.09375 },
{ x: 0.90625, y: 0.09375 },
{ x: 0.90625, y: 0.09375 },
{ x: 0.96875, y: 0.09375 },
{ x: 0.96875, y: 0.09375 },
{ x: 0.03125, y: 0.15625 },
{ x: 0.03125, y: 0.15625 },
{ x: 0.09375, y: 0.15625 },
{ x: 0.09375, y: 0.15625 },
{ x: 0.15625, y: 0.15625 },
{ x: 0.15625, y: 0.15625 },
{ x: 0.21875, y: 0.15625 },
{ x: 0.21875, y: 0.15625 },
{ x: 0.28125, y: 0.15625 },
{ x: 0.28125, y: 0.15625 },
{ x: 0.34375, y: 0.15625 },
{ x: 0.34375, y: 0.15625 },
{ x: 0.40625, y: 0.15625 },
{ x: 0.40625, y: 0.15625 },
{ x: 0.46875, y: 0.15625 },
{ x: 0.46875, y: 0.15625 },
{ x: 0.53125, y: 0.15625 },
{ x: 0.53125, y: 0.15625 },
{ x: 0.59375, y: 0.15625 },
{ x: 0.59375, y: 0.15625 },
{ x: 0.65625, y: 0.15625 },
{ x: 0.65625, y: 0.15625 },
{ x: 0.71875, y: 0.15625 },
{ x: 0.71875, y: 0.15625 },
{ x: 0.78125, y: 0.15625 },
{ x: 0.78125, y: 0.15625 },
{ x: 0.84375, y: 0.15625 },
{ x: 0.84375, y: 0.15625 },
{ x: 0.90625, y: 0.15625 },
{ x: 0.90625, y: 0.15625 },
{ x: 0.96875, y: 0.15625 },
{ x: 0.96875, y: 0.15625 },
{ x: 0.03125, y: 0.21875 },
{ x: 0.03125, y: 0.21875 },
{ x: 0.09375, y: 0.21875 },
{ x: 0.09375, y: 0.21875 },
{ x: 0.15625, y: 0.21875 },
{ x: 0.15625, y: 0.21875 },
{ x: 0.21875, y: 0.21875 },
{ x: 0.21875, y: 0.21875 },
{ x: 0.28125, y: 0.21875 },
{ x: 0.28125, y: 0.21875 },
{ x: 0.34375, y: 0.21875 },
{ x: 0.34375, y: 0.21875 },
{ x: 0.40625, y: 0.21875 },
{ x: 0.40625, y: 0.21875 },
{ x: 0.46875, y: 0.21875 },
{ x: 0.46875, y: 0.21875 },
{ x: 0.53125, y: 0.21875 },
{ x: 0.53125, y: 0.21875 },
{ x: 0.59375, y: 0.21875 },
{ x: 0.59375, y: 0.21875 },
{ x: 0.65625, y: 0.21875 },
{ x: 0.65625, y: 0.21875 },
{ x: 0.71875, y: 0.21875 },
{ x: 0.71875, y: 0.21875 },
{ x: 0.78125, y: 0.21875 },
{ x: 0.78125, y: 0.21875 },
{ x: 0.84375, y: 0.21875 },
{ x: 0.84375, y: 0.21875 },
{ x: 0.90625, y: 0.21875 },
{ x: 0.90625, y: 0.21875 },
{ x: 0.96875, y: 0.21875 },
{ x: 0.96875, y: 0.21875 },
{ x: 0.03125, y: 0.28125 },
{ x: 0.03125, y: 0.28125 },
{ x: 0.09375, y: 0.28125 },
{ x: 0.09375, y: 0.28125 },
{ x: 0.15625, y: 0.28125 },
{ x: 0.15625, y: 0.28125 },
{ x: 0.21875, y: 0.28125 },
{ x: 0.21875, y: 0.28125 },
{ x: 0.28125, y: 0.28125 },
{ x: 0.28125, y: 0.28125 },
{ x: 0.34375, y: 0.28125 },
{ x: 0.34375, y: 0.28125 },
{ x: 0.40625, y: 0.28125 },
{ x: 0.40625, y: 0.28125 },
{ x: 0.46875, y: 0.28125 },
{ x: 0.46875, y: 0.28125 },
{ x: 0.53125, y: 0.28125 },
{ x: 0.53125, y: 0.28125 },
{ x: 0.59375, y: 0.28125 },
{ x: 0.59375, y: 0.28125 },
{ x: 0.65625, y: 0.28125 },
{ x: 0.65625, y: 0.28125 },
{ x: 0.71875, y: 0.28125 },
{ x: 0.71875, y: 0.28125 },
{ x: 0.78125, y: 0.28125 },
{ x: 0.78125, y: 0.28125 },
{ x: 0.84375, y: 0.28125 },
{ x: 0.84375, y: 0.28125 },
{ x: 0.90625, y: 0.28125 },
{ x: 0.90625, y: 0.28125 },
{ x: 0.96875, y: 0.28125 },
{ x: 0.96875, y: 0.28125 },
{ x: 0.03125, y: 0.34375 },
{ x: 0.03125, y: 0.34375 },
{ x: 0.09375, y: 0.34375 },
{ x: 0.09375, y: 0.34375 },
{ x: 0.15625, y: 0.34375 },
{ x: 0.15625, y: 0.34375 },
{ x: 0.21875, y: 0.34375 },
{ x: 0.21875, y: 0.34375 },
{ x: 0.28125, y: 0.34375 },
{ x: 0.28125, y: 0.34375 },
{ x: 0.34375, y: 0.34375 },
{ x: 0.34375, y: 0.34375 },
{ x: 0.40625, y: 0.34375 },
{ x: 0.40625, y: 0.34375 },
{ x: 0.46875, y: 0.34375 },
{ x: 0.46875, y: 0.34375 },
{ x: 0.53125, y: 0.34375 },
{ x: 0.53125, y: 0.34375 },
{ x: 0.59375, y: 0.34375 },
{ x: 0.59375, y: 0.34375 },
{ x: 0.65625, y: 0.34375 },
{ x: 0.65625, y: 0.34375 },
{ x: 0.71875, y: 0.34375 },
{ x: 0.71875, y: 0.34375 },
{ x: 0.78125, y: 0.34375 },
{ x: 0.78125, y: 0.34375 },
{ x: 0.84375, y: 0.34375 },
{ x: 0.84375, y: 0.34375 },
{ x: 0.90625, y: 0.34375 },
{ x: 0.90625, y: 0.34375 },
{ x: 0.96875, y: 0.34375 },
{ x: 0.96875, y: 0.34375 },
{ x: 0.03125, y: 0.40625 },
{ x: 0.03125, y: 0.40625 },
{ x: 0.09375, y: 0.40625 },
{ x: 0.09375, y: 0.40625 },
{ x: 0.15625, y: 0.40625 },
{ x: 0.15625, y: 0.40625 },
{ x: 0.21875, y: 0.40625 },
{ x: 0.21875, y: 0.40625 },
{ x: 0.28125, y: 0.40625 },
{ x: 0.28125, y: 0.40625 },
{ x: 0.34375, y: 0.40625 },
{ x: 0.34375, y: 0.40625 },
{ x: 0.40625, y: 0.40625 },
{ x: 0.40625, y: 0.40625 },
{ x: 0.46875, y: 0.40625 },
{ x: 0.46875, y: 0.40625 },
{ x: 0.53125, y: 0.40625 },
{ x: 0.53125, y: 0.40625 },
{ x: 0.59375, y: 0.40625 },
{ x: 0.59375, y: 0.40625 },
{ x: 0.65625, y: 0.40625 },
{ x: 0.65625, y: 0.40625 },
{ x: 0.71875, y: 0.40625 },
{ x: 0.71875, y: 0.40625 },
{ x: 0.78125, y: 0.40625 },
{ x: 0.78125, y: 0.40625 },
{ x: 0.84375, y: 0.40625 },
{ x: 0.84375, y: 0.40625 },
{ x: 0.90625, y: 0.40625 },
{ x: 0.90625, y: 0.40625 },
{ x: 0.96875, y: 0.40625 },
{ x: 0.96875, y: 0.40625 },
{ x: 0.03125, y: 0.46875 },
{ x: 0.03125, y: 0.46875 },
{ x: 0.09375, y: 0.46875 },
{ x: 0.09375, y: 0.46875 },
{ x: 0.15625, y: 0.46875 },
{ x: 0.15625, y: 0.46875 },
{ x: 0.21875, y: 0.46875 },
{ x: 0.21875, y: 0.46875 },
{ x: 0.28125, y: 0.46875 },
{ x: 0.28125, y: 0.46875 },
{ x: 0.34375, y: 0.46875 },
{ x: 0.34375, y: 0.46875 },
{ x: 0.40625, y: 0.46875 },
{ x: 0.40625, y: 0.46875 },
{ x: 0.46875, y: 0.46875 },
{ x: 0.46875, y: 0.46875 },
{ x: 0.53125, y: 0.46875 },
{ x: 0.53125, y: 0.46875 },
{ x: 0.59375, y: 0.46875 },
{ x: 0.59375, y: 0.46875 },
{ x: 0.65625, y: 0.46875 },
{ x: 0.65625, y: 0.46875 },
{ x: 0.71875, y: 0.46875 },
{ x: 0.71875, y: 0.46875 },
{ x: 0.78125, y: 0.46875 },
{ x: 0.78125, y: 0.46875 },
{ x: 0.84375, y: 0.46875 },
{ x: 0.84375, y: 0.46875 },
{ x: 0.90625, y: 0.46875 },
{ x: 0.90625, y: 0.46875 },
{ x: 0.96875, y: 0.46875 },
{ x: 0.96875, y: 0.46875 },
{ x: 0.03125, y: 0.53125 },
{ x: 0.03125, y: 0.53125 },
{ x: 0.09375, y: 0.53125 },
{ x: 0.09375, y: 0.53125 },
{ x: 0.15625, y: 0.53125 },
{ x: 0.15625, y: 0.53125 },
{ x: 0.21875, y: 0.53125 },
{ x: 0.21875, y: 0.53125 },
{ x: 0.28125, y: 0.53125 },
{ x: 0.28125, y: 0.53125 },
{ x: 0.34375, y: 0.53125 },
{ x: 0.34375, y: 0.53125 },
{ x: 0.40625, y: 0.53125 },
{ x: 0.40625, y: 0.53125 },
{ x: 0.46875, y: 0.53125 },
{ x: 0.46875, y: 0.53125 },
{ x: 0.53125, y: 0.53125 },
{ x: 0.53125, y: 0.53125 },
{ x: 0.59375, y: 0.53125 },
{ x: 0.59375, y: 0.53125 },
{ x: 0.65625, y: 0.53125 },
{ x: 0.65625, y: 0.53125 },
{ x: 0.71875, y: 0.53125 },
{ x: 0.71875, y: 0.53125 },
{ x: 0.78125, y: 0.53125 },
{ x: 0.78125, y: 0.53125 },
{ x: 0.84375, y: 0.53125 },
{ x: 0.84375, y: 0.53125 },
{ x: 0.90625, y: 0.53125 },
{ x: 0.90625, y: 0.53125 },
{ x: 0.96875, y: 0.53125 },
{ x: 0.96875, y: 0.53125 },
{ x: 0.03125, y: 0.59375 },
{ x: 0.03125, y: 0.59375 },
{ x: 0.09375, y: 0.59375 },
{ x: 0.09375, y: 0.59375 },
{ x: 0.15625, y: 0.59375 },
{ x: 0.15625, y: 0.59375 },
{ x: 0.21875, y: 0.59375 },
{ x: 0.21875, y: 0.59375 },
{ x: 0.28125, y: 0.59375 },
{ x: 0.28125, y: 0.59375 },
{ x: 0.34375, y: 0.59375 },
{ x: 0.34375, y: 0.59375 },
{ x: 0.40625, y: 0.59375 },
{ x: 0.40625, y: 0.59375 },
{ x: 0.46875, y: 0.59375 },
{ x: 0.46875, y: 0.59375 },
{ x: 0.53125, y: 0.59375 },
{ x: 0.53125, y: 0.59375 },
{ x: 0.59375, y: 0.59375 },
{ x: 0.59375, y: 0.59375 },
{ x: 0.65625, y: 0.59375 },
{ x: 0.65625, y: 0.59375 },
{ x: 0.71875, y: 0.59375 },
{ x: 0.71875, y: 0.59375 },
{ x: 0.78125, y: 0.59375 },
{ x: 0.78125, y: 0.59375 },
{ x: 0.84375, y: 0.59375 },
{ x: 0.84375, y: 0.59375 },
{ x: 0.90625, y: 0.59375 },
{ x: 0.90625, y: 0.59375 },
{ x: 0.96875, y: 0.59375 },
{ x: 0.96875, y: 0.59375 },
{ x: 0.03125, y: 0.65625 },
{ x: 0.03125, y: 0.65625 },
{ x: 0.09375, y: 0.65625 },
{ x: 0.09375, y: 0.65625 },
{ x: 0.15625, y: 0.65625 },
{ x: 0.15625, y: 0.65625 },
{ x: 0.21875, y: 0.65625 },
{ x: 0.21875, y: 0.65625 },
{ x: 0.28125, y: 0.65625 },
{ x: 0.28125, y: 0.65625 },
{ x: 0.34375, y: 0.65625 },
{ x: 0.34375, y: 0.65625 },
{ x: 0.40625, y: 0.65625 },
{ x: 0.40625, y: 0.65625 },
{ x: 0.46875, y: 0.65625 },
{ x: 0.46875, y: 0.65625 },
{ x: 0.53125, y: 0.65625 },
{ x: 0.53125, y: 0.65625 },
{ x: 0.59375, y: 0.65625 },
{ x: 0.59375, y: 0.65625 },
{ x: 0.65625, y: 0.65625 },
{ x: 0.65625, y: 0.65625 },
{ x: 0.71875, y: 0.65625 },
{ x: 0.71875, y: 0.65625 },
{ x: 0.78125, y: 0.65625 },
{ x: 0.78125, y: 0.65625 },
{ x: 0.84375, y: 0.65625 },
{ x: 0.84375, y: 0.65625 },
{ x: 0.90625, y: 0.65625 },
{ x: 0.90625, y: 0.65625 },
{ x: 0.96875, y: 0.65625 },
{ x: 0.96875, y: 0.65625 },
{ x: 0.03125, y: 0.71875 },
{ x: 0.03125, y: 0.71875 },
{ x: 0.09375, y: 0.71875 },
{ x: 0.09375, y: 0.71875 },
{ x: 0.15625, y: 0.71875 },
{ x: 0.15625, y: 0.71875 },
{ x: 0.21875, y: 0.71875 },
{ x: 0.21875, y: 0.71875 },
{ x: 0.28125, y: 0.71875 },
{ x: 0.28125, y: 0.71875 },
{ x: 0.34375, y: 0.71875 },
{ x: 0.34375, y: 0.71875 },
{ x: 0.40625, y: 0.71875 },
{ x: 0.40625, y: 0.71875 },
{ x: 0.46875, y: 0.71875 },
{ x: 0.46875, y: 0.71875 },
{ x: 0.53125, y: 0.71875 },
{ x: 0.53125, y: 0.71875 },
{ x: 0.59375, y: 0.71875 },
{ x: 0.59375, y: 0.71875 },
{ x: 0.65625, y: 0.71875 },
{ x: 0.65625, y: 0.71875 },
{ x: 0.71875, y: 0.71875 },
{ x: 0.71875, y: 0.71875 },
{ x: 0.78125, y: 0.71875 },
{ x: 0.78125, y: 0.71875 },
{ x: 0.84375, y: 0.71875 },
{ x: 0.84375, y: 0.71875 },
{ x: 0.90625, y: 0.71875 },
{ x: 0.90625, y: 0.71875 },
{ x: 0.96875, y: 0.71875 },
{ x: 0.96875, y: 0.71875 },
{ x: 0.03125, y: 0.78125 },
{ x: 0.03125, y: 0.78125 },
{ x: 0.09375, y: 0.78125 },
{ x: 0.09375, y: 0.78125 },
{ x: 0.15625, y: 0.78125 },
{ x: 0.15625, y: 0.78125 },
{ x: 0.21875, y: 0.78125 },
{ x: 0.21875, y: 0.78125 },
{ x: 0.28125, y: 0.78125 },
{ x: 0.28125, y: 0.78125 },
{ x: 0.34375, y: 0.78125 },
{ x: 0.34375, y: 0.78125 },
{ x: 0.40625, y: 0.78125 },
{ x: 0.40625, y: 0.78125 },
{ x: 0.46875, y: 0.78125 },
{ x: 0.46875, y: 0.78125 },
{ x: 0.53125, y: 0.78125 },
{ x: 0.53125, y: 0.78125 },
{ x: 0.59375, y: 0.78125 },
{ x: 0.59375, y: 0.78125 },
{ x: 0.65625, y: 0.78125 },
{ x: 0.65625, y: 0.78125 },
{ x: 0.71875, y: 0.78125 },
{ x: 0.71875, y: 0.78125 },
{ x: 0.78125, y: 0.78125 },
{ x: 0.78125, y: 0.78125 },
{ x: 0.84375, y: 0.78125 },
{ x: 0.84375, y: 0.78125 },
{ x: 0.90625, y: 0.78125 },
{ x: 0.90625, y: 0.78125 },
{ x: 0.96875, y: 0.78125 },
{ x: 0.96875, y: 0.78125 },
{ x: 0.03125, y: 0.84375 },
{ x: 0.03125, y: 0.84375 },
{ x: 0.09375, y: 0.84375 },
{ x: 0.09375, y: 0.84375 },
{ x: 0.15625, y: 0.84375 },
{ x: 0.15625, y: 0.84375 },
{ x: 0.21875, y: 0.84375 },
{ x: 0.21875, y: 0.84375 },
{ x: 0.28125, y: 0.84375 },
{ x: 0.28125, y: 0.84375 },
{ x: 0.34375, y: 0.84375 },
{ x: 0.34375, y: 0.84375 },
{ x: 0.40625, y: 0.84375 },
{ x: 0.40625, y: 0.84375 },
{ x: 0.46875, y: 0.84375 },
{ x: 0.46875, y: 0.84375 },
{ x: 0.53125, y: 0.84375 },
{ x: 0.53125, y: 0.84375 },
{ x: 0.59375, y: 0.84375 },
{ x: 0.59375, y: 0.84375 },
{ x: 0.65625, y: 0.84375 },
{ x: 0.65625, y: 0.84375 },
{ x: 0.71875, y: 0.84375 },
{ x: 0.71875, y: 0.84375 },
{ x: 0.78125, y: 0.84375 },
{ x: 0.78125, y: 0.84375 },
{ x: 0.84375, y: 0.84375 },
{ x: 0.84375, y: 0.84375 },
{ x: 0.90625, y: 0.84375 },
{ x: 0.90625, y: 0.84375 },
{ x: 0.96875, y: 0.84375 },
{ x: 0.96875, y: 0.84375 },
{ x: 0.03125, y: 0.90625 },
{ x: 0.03125, y: 0.90625 },
{ x: 0.09375, y: 0.90625 },
{ x: 0.09375, y: 0.90625 },
{ x: 0.15625, y: 0.90625 },
{ x: 0.15625, y: 0.90625 },
{ x: 0.21875, y: 0.90625 },
{ x: 0.21875, y: 0.90625 },
{ x: 0.28125, y: 0.90625 },
{ x: 0.28125, y: 0.90625 },
{ x: 0.34375, y: 0.90625 },
{ x: 0.34375, y: 0.90625 },
{ x: 0.40625, y: 0.90625 },
{ x: 0.40625, y: 0.90625 },
{ x: 0.46875, y: 0.90625 },
{ x: 0.46875, y: 0.90625 },
{ x: 0.53125, y: 0.90625 },
{ x: 0.53125, y: 0.90625 },
{ x: 0.59375, y: 0.90625 },
{ x: 0.59375, y: 0.90625 },
{ x: 0.65625, y: 0.90625 },
{ x: 0.65625, y: 0.90625 },
{ x: 0.71875, y: 0.90625 },
{ x: 0.71875, y: 0.90625 },
{ x: 0.78125, y: 0.90625 },
{ x: 0.78125, y: 0.90625 },
{ x: 0.84375, y: 0.90625 },
{ x: 0.84375, y: 0.90625 },
{ x: 0.90625, y: 0.90625 },
{ x: 0.90625, y: 0.90625 },
{ x: 0.96875, y: 0.90625 },
{ x: 0.96875, y: 0.90625 },
{ x: 0.03125, y: 0.96875 },
{ x: 0.03125, y: 0.96875 },
{ x: 0.09375, y: 0.96875 },
{ x: 0.09375, y: 0.96875 },
{ x: 0.15625, y: 0.96875 },
{ x: 0.15625, y: 0.96875 },
{ x: 0.21875, y: 0.96875 },
{ x: 0.21875, y: 0.96875 },
{ x: 0.28125, y: 0.96875 },
{ x: 0.28125, y: 0.96875 },
{ x: 0.34375, y: 0.96875 },
{ x: 0.34375, y: 0.96875 },
{ x: 0.40625, y: 0.96875 },
{ x: 0.40625, y: 0.96875 },
{ x: 0.46875, y: 0.96875 },
{ x: 0.46875, y: 0.96875 },
{ x: 0.53125, y: 0.96875 },
{ x: 0.53125, y: 0.96875 },
{ x: 0.59375, y: 0.96875 },
{ x: 0.59375, y: 0.96875 },
{ x: 0.65625, y: 0.96875 },
{ x: 0.65625, y: 0.96875 },
{ x: 0.71875, y: 0.96875 },
{ x: 0.71875, y: 0.96875 },
{ x: 0.78125, y: 0.96875 },
{ x: 0.78125, y: 0.96875 },
{ x: 0.84375, y: 0.96875 },
{ x: 0.84375, y: 0.96875 },
{ x: 0.90625, y: 0.96875 },
{ x: 0.90625, y: 0.96875 },
{ x: 0.96875, y: 0.96875 },
{ x: 0.96875, y: 0.96875 },
{ x: 0.0625, y: 0.0625 },
{ x: 0.0625, y: 0.0625 },
{ x: 0.0625, y: 0.0625 },
{ x: 0.0625, y: 0.0625 },
{ x: 0.0625, y: 0.0625 },
{ x: 0.0625, y: 0.0625 },
{ x: 0.1875, y: 0.0625 },
{ x: 0.1875, y: 0.0625 },
{ x: 0.1875, y: 0.0625 },
{ x: 0.1875, y: 0.0625 },
{ x: 0.1875, y: 0.0625 },
{ x: 0.1875, y: 0.0625 },
{ x: 0.3125, y: 0.0625 },
{ x: 0.3125, y: 0.0625 },
{ x: 0.3125, y: 0.0625 },
{ x: 0.3125, y: 0.0625 },
{ x: 0.3125, y: 0.0625 },
{ x: 0.3125, y: 0.0625 },
{ x: 0.4375, y: 0.0625 },
{ x: 0.4375, y: 0.0625 },
{ x: 0.4375, y: 0.0625 },
{ x: 0.4375, y: 0.0625 },
{ x: 0.4375, y: 0.0625 },
{ x: 0.4375, y: 0.0625 },
{ x: 0.5625, y: 0.0625 },
{ x: 0.5625, y: 0.0625 },
{ x: 0.5625, y: 0.0625 },
{ x: 0.5625, y: 0.0625 },
{ x: 0.5625, y: 0.0625 },
{ x: 0.5625, y: 0.0625 },
{ x: 0.6875, y: 0.0625 },
{ x: 0.6875, y: 0.0625 },
{ x: 0.6875, y: 0.0625 },
{ x: 0.6875, y: 0.0625 },
{ x: 0.6875, y: 0.0625 },
{ x: 0.6875, y: 0.0625 },
{ x: 0.8125, y: 0.0625 },
{ x: 0.8125, y: 0.0625 },
{ x: 0.8125, y: 0.0625 },
{ x: 0.8125, y: 0.0625 },
{ x: 0.8125, y: 0.0625 },
{ x: 0.8125, y: 0.0625 },
{ x: 0.9375, y: 0.0625 },
{ x: 0.9375, y: 0.0625 },
{ x: 0.9375, y: 0.0625 },
{ x: 0.9375, y: 0.0625 },
{ x: 0.9375, y: 0.0625 },
{ x: 0.9375, y: 0.0625 },
{ x: 0.0625, y: 0.1875 },
{ x: 0.0625, y: 0.1875 },
{ x: 0.0625, y: 0.1875 },
{ x: 0.0625, y: 0.1875 },
{ x: 0.0625, y: 0.1875 },
{ x: 0.0625, y: 0.1875 },
{ x: 0.1875, y: 0.1875 },
{ x: 0.1875, y: 0.1875 },
{ x: 0.1875, y: 0.1875 },
{ x: 0.1875, y: 0.1875 },
{ x: 0.1875, y: 0.1875 },
{ x: 0.1875, y: 0.1875 },
{ x: 0.3125, y: 0.1875 },
{ x: 0.3125, y: 0.1875 },
{ x: 0.3125, y: 0.1875 },
{ x: 0.3125, y: 0.1875 },
{ x: 0.3125, y: 0.1875 },
{ x: 0.3125, y: 0.1875 },
{ x: 0.4375, y: 0.1875 },
{ x: 0.4375, y: 0.1875 },
{ x: 0.4375, y: 0.1875 },
{ x: 0.4375, y: 0.1875 },
{ x: 0.4375, y: 0.1875 },
{ x: 0.4375, y: 0.1875 },
{ x: 0.5625, y: 0.1875 },
{ x: 0.5625, y: 0.1875 },
{ x: 0.5625, y: 0.1875 },
{ x: 0.5625, y: 0.1875 },
{ x: 0.5625, y: 0.1875 },
{ x: 0.5625, y: 0.1875 },
{ x: 0.6875, y: 0.1875 },
{ x: 0.6875, y: 0.1875 },
{ x: 0.6875, y: 0.1875 },
{ x: 0.6875, y: 0.1875 },
{ x: 0.6875, y: 0.1875 },
{ x: 0.6875, y: 0.1875 },
{ x: 0.8125, y: 0.1875 },
{ x: 0.8125, y: 0.1875 },
{ x: 0.8125, y: 0.1875 },
{ x: 0.8125, y: 0.1875 },
{ x: 0.8125, y: 0.1875 },
{ x: 0.8125, y: 0.1875 },
{ x: 0.9375, y: 0.1875 },
{ x: 0.9375, y: 0.1875 },
{ x: 0.9375, y: 0.1875 },
{ x: 0.9375, y: 0.1875 },
{ x: 0.9375, y: 0.1875 },
{ x: 0.9375, y: 0.1875 },
{ x: 0.0625, y: 0.3125 },
{ x: 0.0625, y: 0.3125 },
{ x: 0.0625, y: 0.3125 },
{ x: 0.0625, y: 0.3125 },
{ x: 0.0625, y: 0.3125 },
{ x: 0.0625, y: 0.3125 },
{ x: 0.1875, y: 0.3125 },
{ x: 0.1875, y: 0.3125 },
{ x: 0.1875, y: 0.3125 },
{ x: 0.1875, y: 0.3125 },
{ x: 0.1875, y: 0.3125 },
{ x: 0.1875, y: 0.3125 },
{ x: 0.3125, y: 0.3125 },
{ x: 0.3125, y: 0.3125 },
{ x: 0.3125, y: 0.3125 },
{ x: 0.3125, y: 0.3125 },
{ x: 0.3125, y: 0.3125 },
{ x: 0.3125, y: 0.3125 },
{ x: 0.4375, y: 0.3125 },
{ x: 0.4375, y: 0.3125 },
{ x: 0.4375, y: 0.3125 },
{ x: 0.4375, y: 0.3125 },
{ x: 0.4375, y: 0.3125 },
{ x: 0.4375, y: 0.3125 },
{ x: 0.5625, y: 0.3125 },
{ x: 0.5625, y: 0.3125 },
{ x: 0.5625, y: 0.3125 },
{ x: 0.5625, y: 0.3125 },
{ x: 0.5625, y: 0.3125 },
{ x: 0.5625, y: 0.3125 },
{ x: 0.6875, y: 0.3125 },
{ x: 0.6875, y: 0.3125 },
{ x: 0.6875, y: 0.3125 },
{ x: 0.6875, y: 0.3125 },
{ x: 0.6875, y: 0.3125 },
{ x: 0.6875, y: 0.3125 },
{ x: 0.8125, y: 0.3125 },
{ x: 0.8125, y: 0.3125 },
{ x: 0.8125, y: 0.3125 },
{ x: 0.8125, y: 0.3125 },
{ x: 0.8125, y: 0.3125 },
{ x: 0.8125, y: 0.3125 },
{ x: 0.9375, y: 0.3125 },
{ x: 0.9375, y: 0.3125 },
{ x: 0.9375, y: 0.3125 },
{ x: 0.9375, y: 0.3125 },
{ x: 0.9375, y: 0.3125 },
{ x: 0.9375, y: 0.3125 },
{ x: 0.0625, y: 0.4375 },
{ x: 0.0625, y: 0.4375 },
{ x: 0.0625, y: 0.4375 },
{ x: 0.0625, y: 0.4375 },
{ x: 0.0625, y: 0.4375 },
{ x: 0.0625, y: 0.4375 },
{ x: 0.1875, y: 0.4375 },
{ x: 0.1875, y: 0.4375 },
{ x: 0.1875, y: 0.4375 },
{ x: 0.1875, y: 0.4375 },
{ x: 0.1875, y: 0.4375 },
{ x: 0.1875, y: 0.4375 },
{ x: 0.3125, y: 0.4375 },
{ x: 0.3125, y: 0.4375 },
{ x: 0.3125, y: 0.4375 },
{ x: 0.3125, y: 0.4375 },
{ x: 0.3125, y: 0.4375 },
{ x: 0.3125, y: 0.4375 },
{ x: 0.4375, y: 0.4375 },
{ x: 0.4375, y: 0.4375 },
{ x: 0.4375, y: 0.4375 },
{ x: 0.4375, y: 0.4375 },
{ x: 0.4375, y: 0.4375 },
{ x: 0.4375, y: 0.4375 },
{ x: 0.5625, y: 0.4375 },
{ x: 0.5625, y: 0.4375 },
{ x: 0.5625, y: 0.4375 },
{ x: 0.5625, y: 0.4375 },
{ x: 0.5625, y: 0.4375 },
{ x: 0.5625, y: 0.4375 },
{ x: 0.6875, y: 0.4375 },
{ x: 0.6875, y: 0.4375 },
{ x: 0.6875, y: 0.4375 },
{ x: 0.6875, y: 0.4375 },
{ x: 0.6875, y: 0.4375 },
{ x: 0.6875, y: 0.4375 },
{ x: 0.8125, y: 0.4375 },
{ x: 0.8125, y: 0.4375 },
{ x: 0.8125, y: 0.4375 },
{ x: 0.8125, y: 0.4375 },
{ x: 0.8125, y: 0.4375 },
{ x: 0.8125, y: 0.4375 },
{ x: 0.9375, y: 0.4375 },
{ x: 0.9375, y: 0.4375 },
{ x: 0.9375, y: 0.4375 },
{ x: 0.9375, y: 0.4375 },
{ x: 0.9375, y: 0.4375 },
{ x: 0.9375, y: 0.4375 },
{ x: 0.0625, y: 0.5625 },
{ x: 0.0625, y: 0.5625 },
{ x: 0.0625, y: 0.5625 },
{ x: 0.0625, y: 0.5625 },
{ x: 0.0625, y: 0.5625 },
{ x: 0.0625, y: 0.5625 },
{ x: 0.1875, y: 0.5625 },
{ x: 0.1875, y: 0.5625 },
{ x: 0.1875, y: 0.5625 },
{ x: 0.1875, y: 0.5625 },
{ x: 0.1875, y: 0.5625 },
{ x: 0.1875, y: 0.5625 },
{ x: 0.3125, y: 0.5625 },
{ x: 0.3125, y: 0.5625 },
{ x: 0.3125, y: 0.5625 },
{ x: 0.3125, y: 0.5625 },
{ x: 0.3125, y: 0.5625 },
{ x: 0.3125, y: 0.5625 },
{ x: 0.4375, y: 0.5625 },
{ x: 0.4375, y: 0.5625 },
{ x: 0.4375, y: 0.5625 },
{ x: 0.4375, y: 0.5625 },
{ x: 0.4375, y: 0.5625 },
{ x: 0.4375, y: 0.5625 },
{ x: 0.5625, y: 0.5625 },
{ x: 0.5625, y: 0.5625 },
{ x: 0.5625, y: 0.5625 },
{ x: 0.5625, y: 0.5625 },
{ x: 0.5625, y: 0.5625 },
{ x: 0.5625, y: 0.5625 },
{ x: 0.6875, y: 0.5625 },
{ x: 0.6875, y: 0.5625 },
{ x: 0.6875, y: 0.5625 },
{ x: 0.6875, y: 0.5625 },
{ x: 0.6875, y: 0.5625 },
{ x: 0.6875, y: 0.5625 },
{ x: 0.8125, y: 0.5625 },
{ x: 0.8125, y: 0.5625 },
{ x: 0.8125, y: 0.5625 },
{ x: 0.8125, y: 0.5625 },
{ x: 0.8125, y: 0.5625 },
{ x: 0.8125, y: 0.5625 },
{ x: 0.9375, y: 0.5625 },
{ x: 0.9375, y: 0.5625 },
{ x: 0.9375, y: 0.5625 },
{ x: 0.9375, y: 0.5625 },
{ x: 0.9375, y: 0.5625 },
{ x: 0.9375, y: 0.5625 },
{ x: 0.0625, y: 0.6875 },
{ x: 0.0625, y: 0.6875 },
{ x: 0.0625, y: 0.6875 },
{ x: 0.0625, y: 0.6875 },
{ x: 0.0625, y: 0.6875 },
{ x: 0.0625, y: 0.6875 },
{ x: 0.1875, y: 0.6875 },
{ x: 0.1875, y: 0.6875 },
{ x: 0.1875, y: 0.6875 },
{ x: 0.1875, y: 0.6875 },
{ x: 0.1875, y: 0.6875 },
{ x: 0.1875, y: 0.6875 },
{ x: 0.3125, y: 0.6875 },
{ x: 0.3125, y: 0.6875 },
{ x: 0.3125, y: 0.6875 },
{ x: 0.3125, y: 0.6875 },
{ x: 0.3125, y: 0.6875 },
{ x: 0.3125, y: 0.6875 },
{ x: 0.4375, y: 0.6875 },
{ x: 0.4375, y: 0.6875 },
{ x: 0.4375, y: 0.6875 },
{ x: 0.4375, y: 0.6875 },
{ x: 0.4375, y: 0.6875 },
{ x: 0.4375, y: 0.6875 },
{ x: 0.5625, y: 0.6875 },
{ x: 0.5625, y: 0.6875 },
{ x: 0.5625, y: 0.6875 },
{ x: 0.5625, y: 0.6875 },
{ x: 0.5625, y: 0.6875 },
{ x: 0.5625, y: 0.6875 },
{ x: 0.6875, y: 0.6875 },
{ x: 0.6875, y: 0.6875 },
{ x: 0.6875, y: 0.6875 },
{ x: 0.6875, y: 0.6875 },
{ x: 0.6875, y: 0.6875 },
{ x: 0.6875, y: 0.6875 },
{ x: 0.8125, y: 0.6875 },
{ x: 0.8125, y: 0.6875 },
{ x: 0.8125, y: 0.6875 },
{ x: 0.8125, y: 0.6875 },
{ x: 0.8125, y: 0.6875 },
{ x: 0.8125, y: 0.6875 },
{ x: 0.9375, y: 0.6875 },
{ x: 0.9375, y: 0.6875 },
{ x: 0.9375, y: 0.6875 },
{ x: 0.9375, y: 0.6875 },
{ x: 0.9375, y: 0.6875 },
{ x: 0.9375, y: 0.6875 },
{ x: 0.0625, y: 0.8125 },
{ x: 0.0625, y: 0.8125 },
{ x: 0.0625, y: 0.8125 },
{ x: 0.0625, y: 0.8125 },
{ x: 0.0625, y: 0.8125 },
{ x: 0.0625, y: 0.8125 },
{ x: 0.1875, y: 0.8125 },
{ x: 0.1875, y: 0.8125 },
{ x: 0.1875, y: 0.8125 },
{ x: 0.1875, y: 0.8125 },
{ x: 0.1875, y: 0.8125 },
{ x: 0.1875, y: 0.8125 },
{ x: 0.3125, y: 0.8125 },
{ x: 0.3125, y: 0.8125 },
{ x: 0.3125, y: 0.8125 },
{ x: 0.3125, y: 0.8125 },
{ x: 0.3125, y: 0.8125 },
{ x: 0.3125, y: 0.8125 },
{ x: 0.4375, y: 0.8125 },
{ x: 0.4375, y: 0.8125 },
{ x: 0.4375, y: 0.8125 },
{ x: 0.4375, y: 0.8125 },
{ x: 0.4375, y: 0.8125 },
{ x: 0.4375, y: 0.8125 },
{ x: 0.5625, y: 0.8125 },
{ x: 0.5625, y: 0.8125 },
{ x: 0.5625, y: 0.8125 },
{ x: 0.5625, y: 0.8125 },
{ x: 0.5625, y: 0.8125 },
{ x: 0.5625, y: 0.8125 },
{ x: 0.6875, y: 0.8125 },
{ x: 0.6875, y: 0.8125 },
{ x: 0.6875, y: 0.8125 },
{ x: 0.6875, y: 0.8125 },
{ x: 0.6875, y: 0.8125 },
{ x: 0.6875, y: 0.8125 },
{ x: 0.8125, y: 0.8125 },
{ x: 0.8125, y: 0.8125 },
{ x: 0.8125, y: 0.8125 },
{ x: 0.8125, y: 0.8125 },
{ x: 0.8125, y: 0.8125 },
{ x: 0.8125, y: 0.8125 },
{ x: 0.9375, y: 0.8125 },
{ x: 0.9375, y: 0.8125 },
{ x: 0.9375, y: 0.8125 },
{ x: 0.9375, y: 0.8125 },
{ x: 0.9375, y: 0.8125 },
{ x: 0.9375, y: 0.8125 },
{ x: 0.0625, y: 0.9375 },
{ x: 0.0625, y: 0.9375 },
{ x: 0.0625, y: 0.9375 },
{ x: 0.0625, y: 0.9375 },
{ x: 0.0625, y: 0.9375 },
{ x: 0.0625, y: 0.9375 },
{ x: 0.1875, y: 0.9375 },
{ x: 0.1875, y: 0.9375 },
{ x: 0.1875, y: 0.9375 },
{ x: 0.1875, y: 0.9375 },
{ x: 0.1875, y: 0.9375 },
{ x: 0.1875, y: 0.9375 },
{ x: 0.3125, y: 0.9375 },
{ x: 0.3125, y: 0.9375 },
{ x: 0.3125, y: 0.9375 },
{ x: 0.3125, y: 0.9375 },
{ x: 0.3125, y: 0.9375 },
{ x: 0.3125, y: 0.9375 },
{ x: 0.4375, y: 0.9375 },
{ x: 0.4375, y: 0.9375 },
{ x: 0.4375, y: 0.9375 },
{ x: 0.4375, y: 0.9375 },
{ x: 0.4375, y: 0.9375 },
{ x: 0.4375, y: 0.9375 },
{ x: 0.5625, y: 0.9375 },
{ x: 0.5625, y: 0.9375 },
{ x: 0.5625, y: 0.9375 },
{ x: 0.5625, y: 0.9375 },
{ x: 0.5625, y: 0.9375 },
{ x: 0.5625, y: 0.9375 },
{ x: 0.6875, y: 0.9375 },
{ x: 0.6875, y: 0.9375 },
{ x: 0.6875, y: 0.9375 },
{ x: 0.6875, y: 0.9375 },
{ x: 0.6875, y: 0.9375 },
{ x: 0.6875, y: 0.9375 },
{ x: 0.8125, y: 0.9375 },
{ x: 0.8125, y: 0.9375 },
{ x: 0.8125, y: 0.9375 },
{ x: 0.8125, y: 0.9375 },
{ x: 0.8125, y: 0.9375 },
{ x: 0.8125, y: 0.9375 },
{ x: 0.9375, y: 0.9375 },
{ x: 0.9375, y: 0.9375 },
{ x: 0.9375, y: 0.9375 },
{ x: 0.9375, y: 0.9375 },
{ x: 0.9375, y: 0.9375 },
{ x: 0.9375, y: 0.9375 }
];
// src/hand/handposedetector.ts
var HandDetector = class {
constructor(model18) {
__publicField(this, "model");
__publicField(this, "anchors");
__publicField(this, "anchorsTensor");
__publicField(this, "inputSize");
__publicField(this, "inputSizeTensor");
__publicField(this, "doubleInputSizeTensor");
this.model = model18;
this.anchors = anchors2.map((anchor) => [anchor.x, anchor.y]);
this.anchorsTensor = Zo(this.anchors);
this.inputSize = this.model && this.model.inputs && this.model.inputs[0].shape ? this.model.inputs[0].shape[2] : 0;
this.inputSizeTensor = Zt([this.inputSize, this.inputSize]);
this.doubleInputSizeTensor = Zt([this.inputSize * 2, this.inputSize * 2]);
}
normalizeBoxes(boxes) {
const t = {};
t.boxOffsets = qe(boxes, [0, 0], [-1, 2]);
t.boxSizes = qe(boxes, [0, 2], [-1, 2]);
t.div = xe(t.boxOffsets, this.inputSizeTensor);
t.boxCenterPoints = oe(t.div, this.anchorsTensor);
t.halfBoxSizes = xe(t.boxSizes, this.doubleInputSizeTensor);
t.sub = ge(t.boxCenterPoints, t.halfBoxSizes);
t.startPoints = V(t.sub, this.inputSizeTensor);
t.add = oe(t.boxCenterPoints, t.halfBoxSizes);
t.endPoints = V(t.add, this.inputSizeTensor);
const res = dR([t.startPoints, t.endPoints], 1);
Object.keys(t).forEach((tensor) => De(t[tensor]));
return res;
}
normalizeLandmarks(rawPalmLandmarks, index2) {
const t = {};
t.reshape = U(rawPalmLandmarks, [-1, 7, 2]);
t.div = xe(t.reshape, this.inputSizeTensor);
t.landmarks = oe(t.div, this.anchors[index2]);
const res = V(t.landmarks, this.inputSizeTensor);
Object.keys(t).forEach((tensor) => De(t[tensor]));
return res;
}
async predict(input, config3) {
const t = {};
t.resize = Kn.resizeBilinear(input, [this.inputSize, this.inputSize]);
t.div = xe(t.resize, constants.tf127);
t.image = ge(t.div, constants.tf1);
t.batched = this.model.execute(t.image);
t.predictions = br(t.batched);
t.slice = qe(t.predictions, [0, 0], [-1, 1]);
t.sigmoid = qs(t.slice);
t.scores = br(t.sigmoid);
const scores = await t.scores.data();
t.boxes = qe(t.predictions, [0, 1], [-1, 4]);
t.norm = this.normalizeBoxes(t.boxes);
t.nms = await Kn.nonMaxSuppressionAsync(t.norm, t.scores, 3 * config3.hand.maxDetected, config3.hand.iouThreshold, config3.hand.minConfidence);
const nms = await t.nms.array();
const hands = [];
for (const index2 of nms) {
const p = {};
p.box = qe(t.norm, [index2, 0], [1, -1]);
p.slice = qe(t.predictions, [index2, 5], [1, 14]);
p.norm = this.normalizeLandmarks(p.slice, index2);
p.palmLandmarks = U(p.norm, [-1, 2]);
const box = await p.box.data();
const startPoint = box.slice(0, 2);
const endPoint = box.slice(2, 4);
const palmLandmarks = await p.palmLandmarks.array();
const hand3 = { startPoint, endPoint, palmLandmarks, confidence: scores[index2] };
const scaled = scaleBoxCoordinates2(hand3, [input.shape[2] / this.inputSize, input.shape[1] / this.inputSize]);
hands.push(scaled);
Object.keys(p).forEach((tensor) => De(p[tensor]));
}
Object.keys(t).forEach((tensor) => De(t[tensor]));
return hands;
}
};
// src/hand/handposepipeline.ts
var palmBoxEnlargeFactor = 5;
var handBoxEnlargeFactor = 1.65;
var palmLandmarkIds = [0, 5, 9, 13, 17, 1, 2];
var palmLandmarksPalmBase = 0;
var palmLandmarksMiddleFingerBase = 2;
var lastTime11 = 0;
var HandPipeline = class {
constructor(handDetector, handPoseModel2) {
__publicField(this, "handDetector");
__publicField(this, "handPoseModel");
__publicField(this, "inputSize");
__publicField(this, "storedBoxes");
__publicField(this, "skipped");
__publicField(this, "detectedHands");
this.handDetector = handDetector;
this.handPoseModel = handPoseModel2;
this.inputSize = this.handPoseModel && this.handPoseModel.inputs[0].shape ? this.handPoseModel.inputs[0].shape[2] : 0;
this.storedBoxes = [];
this.skipped = Number.MAX_SAFE_INTEGER;
this.detectedHands = 0;
}
calculateLandmarksBoundingBox(landmarks) {
const xs2 = landmarks.map((d) => d[0]);
const ys2 = landmarks.map((d) => d[1]);
const startPoint = [Math.min(...xs2), Math.min(...ys2)];
const endPoint = [Math.max(...xs2), Math.max(...ys2)];
return { startPoint, endPoint };
}
getBoxForPalmLandmarks(palmLandmarks, rotationMatrix) {
const rotatedPalmLandmarks = palmLandmarks.map((coord) => rotatePoint2([...coord, 1], rotationMatrix));
const boxAroundPalm = this.calculateLandmarksBoundingBox(rotatedPalmLandmarks);
return enlargeBox2(squarifyBox2(boxAroundPalm), palmBoxEnlargeFactor);
}
getBoxForHandLandmarks(landmarks) {
const boundingBox = this.calculateLandmarksBoundingBox(landmarks);
const boxAroundHand = enlargeBox2(squarifyBox2(boundingBox), handBoxEnlargeFactor);
boxAroundHand.palmLandmarks = [];
for (let i = 0; i < palmLandmarkIds.length; i++) {
boxAroundHand.palmLandmarks.push(landmarks[palmLandmarkIds[i]].slice(0, 2));
}
return boxAroundHand;
}
transformRawCoords(rawCoords, box2, angle, rotationMatrix) {
const boxSize = getBoxSize2(box2);
const scaleFactor = [boxSize[0] / this.inputSize, boxSize[1] / this.inputSize, (boxSize[0] + boxSize[1]) / this.inputSize / 2];
const coordsScaled = rawCoords.map((coord) => [
scaleFactor[0] * (coord[0] - this.inputSize / 2),
scaleFactor[1] * (coord[1] - this.inputSize / 2),
scaleFactor[2] * coord[2]
]);
const coordsRotationMatrix = buildRotationMatrix2(angle, [0, 0]);
const coordsRotated = coordsScaled.map((coord) => {
const rotated = rotatePoint2(coord, coordsRotationMatrix);
return [...rotated, coord[2]];
});
const inverseRotationMatrix = invertTransformMatrix2(rotationMatrix);
const boxCenter = [...getBoxCenter2(box2), 1];
const originalBoxCenter = [
dot2(boxCenter, inverseRotationMatrix[0]),
dot2(boxCenter, inverseRotationMatrix[1])
];
return coordsRotated.map((coord) => [
Math.trunc(coord[0] + originalBoxCenter[0]),
Math.trunc(coord[1] + originalBoxCenter[1]),
Math.trunc(coord[2])
]);
}
async estimateHands(image, config3) {
let useFreshBox = false;
let boxes;
const skipTime = (config3.hand.skipTime || 0) > now() - lastTime11;
const skipFrame = this.skipped < (config3.hand.skipFrames || 0);
if (config3.skipAllowed && skipTime && skipFrame) {
boxes = await this.handDetector.predict(image, config3);
this.skipped = 0;
}
if (config3.skipAllowed)
this.skipped++;
if (boxes && boxes.length > 0 && (boxes.length !== this.detectedHands && this.detectedHands !== config3.hand.maxDetected || !config3.hand.landmarks)) {
this.detectedHands = 0;
this.storedBoxes = [...boxes];
if (this.storedBoxes.length > 0)
useFreshBox = true;
}
const hands = [];
for (let i = 0; i < this.storedBoxes.length; i++) {
const currentBox = this.storedBoxes[i];
if (!currentBox)
continue;
if (config3.hand.landmarks) {
const angle = config3.hand.rotation ? computeRotation2(currentBox.palmLandmarks[palmLandmarksPalmBase], currentBox.palmLandmarks[palmLandmarksMiddleFingerBase]) : 0;
const palmCenter = getBoxCenter2(currentBox);
const palmCenterNormalized = [palmCenter[0] / image.shape[2], palmCenter[1] / image.shape[1]];
const rotatedImage = config3.hand.rotation && env.kernels.includes("rotatewithoffset") ? Kn.rotateWithOffset(image, angle, 0, palmCenterNormalized) : image.clone();
const rotationMatrix = buildRotationMatrix2(-angle, palmCenter);
const newBox = useFreshBox ? this.getBoxForPalmLandmarks(currentBox.palmLandmarks, rotationMatrix) : currentBox;
const croppedInput = cutBoxFromImageAndResize(newBox, rotatedImage, [this.inputSize, this.inputSize]);
const handImage = xe(croppedInput, constants.tf255);
De(croppedInput);
De(rotatedImage);
const [confidenceT, keypoints] = this.handPoseModel.execute(handImage);
lastTime11 = now();
De(handImage);
const confidence = (await confidenceT.data())[0];
De(confidenceT);
if (confidence >= config3.hand.minConfidence / 4) {
const keypointsReshaped = U(keypoints, [-1, 3]);
const rawCoords = await keypointsReshaped.array();
De(keypoints);
De(keypointsReshaped);
const coords = this.transformRawCoords(rawCoords, newBox, angle, rotationMatrix);
const nextBoundingBox = this.getBoxForHandLandmarks(coords);
this.storedBoxes[i] = { ...nextBoundingBox, confidence };
const result = {
landmarks: coords,
confidence,
boxConfidence: currentBox.confidence,
fingerConfidence: confidence,
box: { topLeft: nextBoundingBox.startPoint, bottomRight: nextBoundingBox.endPoint }
};
hands.push(result);
} else {
this.storedBoxes[i] = null;
}
De(keypoints);
} else {
const enlarged = enlargeBox2(squarifyBox2(currentBox), handBoxEnlargeFactor);
const result = {
confidence: currentBox.confidence,
boxConfidence: currentBox.confidence,
fingerConfidence: 0,
box: { topLeft: enlarged.startPoint, bottomRight: enlarged.endPoint },
landmarks: []
};
hands.push(result);
}
}
this.storedBoxes = this.storedBoxes.filter((a) => a !== null);
this.detectedHands = hands.length;
if (hands.length > config3.hand.maxDetected)
hands.length = config3.hand.maxDetected;
return hands;
}
};
// src/hand/fingerdef.ts
var Finger = {
thumb: 0,
index: 1,
middle: 2,
ring: 3,
pinky: 4,
all: [0, 1, 2, 3, 4],
nameMapping: { 0: "thumb", 1: "index", 2: "middle", 3: "ring", 4: "pinky" },
pointsMapping: {
0: [[0, 1], [1, 2], [2, 3], [3, 4]],
1: [[0, 5], [5, 6], [6, 7], [7, 8]],
2: [[0, 9], [9, 10], [10, 11], [11, 12]],
3: [[0, 13], [13, 14], [14, 15], [15, 16]],
4: [[0, 17], [17, 18], [18, 19], [19, 20]]
},
getName: (value) => Finger.nameMapping[value],
getPoints: (value) => Finger.pointsMapping[value]
};
var FingerCurl = {
none: 0,
half: 1,
full: 2,
nameMapping: { 0: "none", 1: "half", 2: "full" },
getName: (value) => FingerCurl.nameMapping[value]
};
var FingerDirection = {
verticalUp: 0,
verticalDown: 1,
horizontalLeft: 2,
horizontalRight: 3,
diagonalUpRight: 4,
diagonalUpLeft: 5,
diagonalDownRight: 6,
diagonalDownLeft: 7,
nameMapping: { 0: "verticalUp", 1: "verticalDown", 2: "horizontalLeft", 3: "horizontalRight", 4: "diagonalUpRight", 5: "diagonalUpLeft", 6: "diagonalDownRight", 7: "diagonalDownLeft" },
getName: (value) => FingerDirection.nameMapping[value]
};
var FingerGesture = class {
constructor(name) {
__publicField(this, "name");
__publicField(this, "curls");
__publicField(this, "directions");
__publicField(this, "weights");
__publicField(this, "weightsRelative");
this.name = name;
this.curls = {};
this.directions = {};
this.weights = [1, 1, 1, 1, 1];
this.weightsRelative = [1, 1, 1, 1, 1];
}
curl(finger, curl, confidence) {
if (typeof this.curls[finger] === "undefined")
this.curls[finger] = [];
this.curls[finger].push([curl, confidence]);
}
direction(finger, position, confidence) {
if (!this.directions[finger])
this.directions[finger] = [];
this.directions[finger].push([position, confidence]);
}
weight(finger, weight) {
this.weights[finger] = weight;
const total = this.weights.reduce((a, b) => a + b, 0);
this.weightsRelative = this.weights.map((el2) => el2 * 5 / total);
}
matchAgainst(detectedCurls, detectedDirections) {
let confidence = 0;
for (const fingerIdx in detectedCurls) {
const detectedCurl = detectedCurls[fingerIdx];
const expectedCurls = this.curls[fingerIdx];
if (typeof expectedCurls === "undefined") {
confidence += this.weightsRelative[fingerIdx];
continue;
}
for (const [expectedCurl, score] of expectedCurls) {
if (detectedCurl === expectedCurl) {
confidence += score * this.weightsRelative[fingerIdx];
break;
}
}
}
for (const fingerIdx in detectedDirections) {
const detectedDirection = detectedDirections[fingerIdx];
const expectedDirections = this.directions[fingerIdx];
if (typeof expectedDirections === "undefined") {
confidence += this.weightsRelative[fingerIdx];
continue;
}
for (const [expectedDirection, score] of expectedDirections) {
if (detectedDirection === expectedDirection) {
confidence += score * this.weightsRelative[fingerIdx];
break;
}
}
}
return confidence / 10;
}
};
// src/hand/fingergesture.ts
var { thumb, index, middle, ring, pinky } = Finger;
var { none, half, full } = FingerCurl;
var { verticalUp, verticalDown, horizontalLeft, horizontalRight, diagonalUpRight, diagonalUpLeft, diagonalDownRight, diagonalDownLeft } = FingerDirection;
var ThumbsUp = new FingerGesture("thumbs up");
ThumbsUp.curl(thumb, none, 1);
ThumbsUp.direction(thumb, verticalUp, 1);
ThumbsUp.direction(thumb, diagonalUpLeft, 0.25);
ThumbsUp.direction(thumb, diagonalUpRight, 0.25);
for (const finger of [Finger.index, Finger.middle, Finger.ring, Finger.pinky]) {
ThumbsUp.curl(finger, full, 1);
ThumbsUp.direction(finger, horizontalLeft, 1);
ThumbsUp.direction(finger, horizontalRight, 1);
}
var Victory = new FingerGesture("victory");
Victory.curl(thumb, half, 0.5);
Victory.curl(thumb, none, 0.5);
Victory.direction(thumb, verticalUp, 1);
Victory.direction(thumb, diagonalUpLeft, 1);
Victory.curl(index, none, 1);
Victory.direction(index, verticalUp, 0.75);
Victory.direction(index, diagonalUpLeft, 1);
Victory.curl(middle, none, 1);
Victory.direction(middle, verticalUp, 1);
Victory.direction(middle, diagonalUpLeft, 0.75);
Victory.curl(ring, full, 1);
Victory.direction(ring, verticalUp, 0.2);
Victory.direction(ring, diagonalUpLeft, 1);
Victory.direction(ring, horizontalLeft, 0.2);
Victory.curl(pinky, full, 1);
Victory.direction(pinky, verticalUp, 0.2);
Victory.direction(pinky, diagonalUpLeft, 1);
Victory.direction(pinky, horizontalLeft, 0.2);
Victory.weight(index, 2);
Victory.weight(middle, 2);
var Point = new FingerGesture("point");
Point.curl(thumb, full, 1);
Point.curl(index, none, 0.5);
Point.curl(middle, full, 0.5);
Point.curl(ring, full, 0.5);
Point.curl(pinky, full, 0.5);
Point.weight(index, 2);
Point.weight(middle, 2);
var MiddleFinger = new FingerGesture("middle finger");
MiddleFinger.curl(thumb, none, 1);
MiddleFinger.curl(index, full, 0.5);
MiddleFinger.curl(middle, full, 0.5);
MiddleFinger.curl(ring, full, 0.5);
MiddleFinger.curl(pinky, full, 0.5);
MiddleFinger.weight(index, 2);
MiddleFinger.weight(middle, 2);
var OpenPalm = new FingerGesture("open palm");
OpenPalm.curl(thumb, none, 0.75);
OpenPalm.curl(index, none, 0.75);
OpenPalm.curl(middle, none, 0.75);
OpenPalm.curl(ring, none, 0.75);
OpenPalm.curl(pinky, none, 0.75);
var fingergesture_default = [ThumbsUp, Victory, Point, MiddleFinger, OpenPalm];
// src/hand/fingerpose.ts
var minConfidence = 0.7;
var options2 = {
HALF_CURL_START_LIMIT: 60,
NO_CURL_START_LIMIT: 130,
DISTANCE_VOTE_POWER: 1.1,
SINGLE_ANGLE_VOTE_POWER: 0.9,
TOTAL_ANGLE_VOTE_POWER: 1.6
};
function calculateSlope(point1x, point1y, point2x, point2y) {
const value = (point1y - point2y) / (point1x - point2x);
let slope = Math.atan(value) * 180 / Math.PI;
if (slope <= 0)
slope = -slope;
else if (slope > 0)
slope = 180 - slope;
return slope;
}
function getSlopes(point1, point2) {
if (!point1 || !point2)
return [0, 0];
const slopeXY = calculateSlope(point1[0], point1[1], point2[0], point2[1]);
if (point1.length === 2)
return slopeXY;
const slopeYZ = calculateSlope(point1[1], point1[2], point2[1], point2[2]);
return [slopeXY, slopeYZ];
}
function angleOrientationAt(angle, weightageAt = 1) {
let isVertical = 0;
let isDiagonal = 0;
let isHorizontal = 0;
if (angle >= 75 && angle <= 105)
isVertical = 1 * weightageAt;
else if (angle >= 25 && angle <= 155)
isDiagonal = 1 * weightageAt;
else
isHorizontal = 1 * weightageAt;
return [isVertical, isDiagonal, isHorizontal];
}
function estimateFingerCurl(startPoint, midPoint, endPoint) {
const start_mid_x_dist = startPoint[0] - midPoint[0];
const start_end_x_dist = startPoint[0] - endPoint[0];
const mid_end_x_dist = midPoint[0] - endPoint[0];
const start_mid_y_dist = startPoint[1] - midPoint[1];
const start_end_y_dist = startPoint[1] - endPoint[1];
const mid_end_y_dist = midPoint[1] - endPoint[1];
const start_mid_z_dist = startPoint[2] - midPoint[2];
const start_end_z_dist = startPoint[2] - endPoint[2];
const mid_end_z_dist = midPoint[2] - endPoint[2];
const start_mid_dist = Math.sqrt(start_mid_x_dist * start_mid_x_dist + start_mid_y_dist * start_mid_y_dist + start_mid_z_dist * start_mid_z_dist);
const start_end_dist = Math.sqrt(start_end_x_dist * start_end_x_dist + start_end_y_dist * start_end_y_dist + start_end_z_dist * start_end_z_dist);
const mid_end_dist = Math.sqrt(mid_end_x_dist * mid_end_x_dist + mid_end_y_dist * mid_end_y_dist + mid_end_z_dist * mid_end_z_dist);
let cos_in = (mid_end_dist * mid_end_dist + start_mid_dist * start_mid_dist - start_end_dist * start_end_dist) / (2 * mid_end_dist * start_mid_dist);
if (cos_in > 1)
cos_in = 1;
else if (cos_in < -1)
cos_in = -1;
let angleOfCurve = Math.acos(cos_in);
angleOfCurve = 57.2958 * angleOfCurve % 180;
let fingerCurl;
if (angleOfCurve > options2.NO_CURL_START_LIMIT)
fingerCurl = FingerCurl.none;
else if (angleOfCurve > options2.HALF_CURL_START_LIMIT)
fingerCurl = FingerCurl.half;
else
fingerCurl = FingerCurl.full;
return fingerCurl;
}
function estimateHorizontalDirection(start_end_x_dist, start_mid_x_dist, mid_end_x_dist, max_dist_x) {
let estimatedDirection;
if (max_dist_x === Math.abs(start_end_x_dist)) {
if (start_end_x_dist > 0)
estimatedDirection = FingerDirection.horizontalLeft;
else
estimatedDirection = FingerDirection.horizontalRight;
} else if (max_dist_x === Math.abs(start_mid_x_dist)) {
if (start_mid_x_dist > 0)
estimatedDirection = FingerDirection.horizontalLeft;
else
estimatedDirection = FingerDirection.horizontalRight;
} else {
if (mid_end_x_dist > 0)
estimatedDirection = FingerDirection.horizontalLeft;
else
estimatedDirection = FingerDirection.horizontalRight;
}
return estimatedDirection;
}
function estimateVerticalDirection(start_end_y_dist, start_mid_y_dist, mid_end_y_dist, max_dist_y) {
let estimatedDirection;
if (max_dist_y === Math.abs(start_end_y_dist)) {
if (start_end_y_dist < 0)
estimatedDirection = FingerDirection.verticalDown;
else
estimatedDirection = FingerDirection.verticalUp;
} else if (max_dist_y === Math.abs(start_mid_y_dist)) {
if (start_mid_y_dist < 0)
estimatedDirection = FingerDirection.verticalDown;
else
estimatedDirection = FingerDirection.verticalUp;
} else {
if (mid_end_y_dist < 0)
estimatedDirection = FingerDirection.verticalDown;
else
estimatedDirection = FingerDirection.verticalUp;
}
return estimatedDirection;
}
function estimateDiagonalDirection(start_end_y_dist, start_mid_y_dist, mid_end_y_dist, max_dist_y, start_end_x_dist, start_mid_x_dist, mid_end_x_dist, max_dist_x) {
let estimatedDirection;
const reqd_vertical_direction = estimateVerticalDirection(start_end_y_dist, start_mid_y_dist, mid_end_y_dist, max_dist_y);
const reqd_horizontal_direction = estimateHorizontalDirection(start_end_x_dist, start_mid_x_dist, mid_end_x_dist, max_dist_x);
if (reqd_vertical_direction === FingerDirection.verticalUp) {
if (reqd_horizontal_direction === FingerDirection.horizontalLeft)
estimatedDirection = FingerDirection.diagonalUpLeft;
else
estimatedDirection = FingerDirection.diagonalUpRight;
} else {
if (reqd_horizontal_direction === FingerDirection.horizontalLeft)
estimatedDirection = FingerDirection.diagonalDownLeft;
else
estimatedDirection = FingerDirection.diagonalDownRight;
}
return estimatedDirection;
}
function calculateFingerDirection(startPoint, midPoint, endPoint, fingerSlopes) {
const start_mid_x_dist = startPoint[0] - midPoint[0];
const start_end_x_dist = startPoint[0] - endPoint[0];
const mid_end_x_dist = midPoint[0] - endPoint[0];
const start_mid_y_dist = startPoint[1] - midPoint[1];
const start_end_y_dist = startPoint[1] - endPoint[1];
const mid_end_y_dist = midPoint[1] - endPoint[1];
const max_dist_x = Math.max(Math.abs(start_mid_x_dist), Math.abs(start_end_x_dist), Math.abs(mid_end_x_dist));
const max_dist_y = Math.max(Math.abs(start_mid_y_dist), Math.abs(start_end_y_dist), Math.abs(mid_end_y_dist));
let voteVertical = 0;
let voteDiagonal = 0;
let voteHorizontal = 0;
const start_end_x_y_dist_ratio = max_dist_y / (max_dist_x + 1e-5);
if (start_end_x_y_dist_ratio > 1.5)
voteVertical += options2.DISTANCE_VOTE_POWER;
else if (start_end_x_y_dist_ratio > 0.66)
voteDiagonal += options2.DISTANCE_VOTE_POWER;
else
voteHorizontal += options2.DISTANCE_VOTE_POWER;
const start_mid_dist = Math.sqrt(start_mid_x_dist * start_mid_x_dist + start_mid_y_dist * start_mid_y_dist);
const start_end_dist = Math.sqrt(start_end_x_dist * start_end_x_dist + start_end_y_dist * start_end_y_dist);
const mid_end_dist = Math.sqrt(mid_end_x_dist * mid_end_x_dist + mid_end_y_dist * mid_end_y_dist);
const max_dist = Math.max(start_mid_dist, start_end_dist, mid_end_dist);
let calc_start_point_x = startPoint[0];
let calc_start_point_y = startPoint[1];
let calc_end_point_x = endPoint[0];
let calc_end_point_y = endPoint[1];
if (max_dist === start_mid_dist) {
calc_end_point_x = endPoint[0];
calc_end_point_y = endPoint[1];
} else if (max_dist === mid_end_dist) {
calc_start_point_x = midPoint[0];
calc_start_point_y = midPoint[1];
}
const calcStartPoint = [calc_start_point_x, calc_start_point_y];
const calcEndPoint = [calc_end_point_x, calc_end_point_y];
const totalAngle = getSlopes(calcStartPoint, calcEndPoint);
const votes = angleOrientationAt(totalAngle, options2.TOTAL_ANGLE_VOTE_POWER);
voteVertical += votes[0];
voteDiagonal += votes[1];
voteHorizontal += votes[2];
for (const fingerSlope of fingerSlopes) {
const fingerVotes = angleOrientationAt(fingerSlope, options2.SINGLE_ANGLE_VOTE_POWER);
voteVertical += fingerVotes[0];
voteDiagonal += fingerVotes[1];
voteHorizontal += fingerVotes[2];
}
let estimatedDirection;
if (voteVertical === Math.max(voteVertical, voteDiagonal, voteHorizontal)) {
estimatedDirection = estimateVerticalDirection(start_end_y_dist, start_mid_y_dist, mid_end_y_dist, max_dist_y);
} else if (voteHorizontal === Math.max(voteDiagonal, voteHorizontal)) {
estimatedDirection = estimateHorizontalDirection(start_end_x_dist, start_mid_x_dist, mid_end_x_dist, max_dist_x);
} else {
estimatedDirection = estimateDiagonalDirection(start_end_y_dist, start_mid_y_dist, mid_end_y_dist, max_dist_y, start_end_x_dist, start_mid_x_dist, mid_end_x_dist, max_dist_x);
}
return estimatedDirection;
}
function estimate(landmarks) {
const slopesXY = [];
const slopesYZ = [];
const fingerCurls = [];
const fingerDirections = [];
if (!landmarks)
return { curls: fingerCurls, directions: fingerDirections };
for (const finger of Finger.all) {
const points = Finger.getPoints(finger);
const slopeAtXY = [];
const slopeAtYZ = [];
for (const point2 of points) {
const point1 = landmarks[point2[0]];
const point22 = landmarks[point2[1]];
const slopes = getSlopes(point1, point22);
const slopeXY = slopes[0];
const slopeYZ = slopes[1];
slopeAtXY.push(slopeXY);
slopeAtYZ.push(slopeYZ);
}
slopesXY.push(slopeAtXY);
slopesYZ.push(slopeAtYZ);
}
for (const finger of Finger.all) {
const pointIndexAt = finger === Finger.thumb ? 1 : 0;
const fingerPointsAt = Finger.getPoints(finger);
const startPoint = landmarks[fingerPointsAt[pointIndexAt][0]];
const midPoint = landmarks[fingerPointsAt[pointIndexAt + 1][1]];
const endPoint = landmarks[fingerPointsAt[3][1]];
const fingerCurled = estimateFingerCurl(startPoint, midPoint, endPoint);
const fingerPosition = calculateFingerDirection(startPoint, midPoint, endPoint, slopesXY[finger].slice(pointIndexAt));
fingerCurls[finger] = fingerCurled;
fingerDirections[finger] = fingerPosition;
}
return { curls: fingerCurls, directions: fingerDirections };
}
function analyze(keypoints) {
if (!keypoints || keypoints.length === 0)
return null;
const estimatorRes = estimate(keypoints);
const landmarks = {};
for (const fingerIdx of Finger.all) {
landmarks[Finger.getName(fingerIdx)] = {
curl: FingerCurl.getName(estimatorRes.curls[fingerIdx]),
direction: FingerDirection.getName(estimatorRes.directions[fingerIdx])
};
}
return landmarks;
}
function match(keypoints) {
const poses = [];
if (!keypoints || keypoints.length === 0)
return poses;
const estimatorRes = estimate(keypoints);
for (const gesture2 of fingergesture_default) {
const confidence = gesture2.matchAgainst(estimatorRes.curls, estimatorRes.directions);
if (confidence >= minConfidence)
poses.push({ name: gesture2.name, confidence });
}
return poses;
}
// src/hand/handpose.ts
var meshAnnotations2 = {
thumb: [1, 2, 3, 4],
index: [5, 6, 7, 8],
middle: [9, 10, 11, 12],
ring: [13, 14, 15, 16],
pinky: [17, 18, 19, 20],
palm: [0]
};
var handDetectorModel;
var handPoseModel;
var handPipeline;
async function predict12(input, config3) {
const predictions = await handPipeline.estimateHands(input, config3);
if (!predictions)
return [];
const hands = [];
for (let i = 0; i < predictions.length; i++) {
const annotations2 = {};
if (predictions[i].landmarks) {
for (const key of Object.keys(meshAnnotations2)) {
annotations2[key] = meshAnnotations2[key].map((index2) => predictions[i].landmarks[index2]);
}
}
const keypoints = predictions[i].landmarks;
let box = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, 0, 0];
let boxRaw = [0, 0, 0, 0];
if (keypoints && keypoints.length > 0) {
for (const pt2 of keypoints) {
if (pt2[0] < box[0])
box[0] = pt2[0];
if (pt2[1] < box[1])
box[1] = pt2[1];
if (pt2[0] > box[2])
box[2] = pt2[0];
if (pt2[1] > box[3])
box[3] = pt2[1];
}
box[2] -= box[0];
box[3] -= box[1];
boxRaw = [box[0] / (input.shape[2] || 0), box[1] / (input.shape[1] || 0), box[2] / (input.shape[2] || 0), box[3] / (input.shape[1] || 0)];
} else {
box = predictions[i].box ? [
Math.trunc(Math.max(0, predictions[i].box.topLeft[0])),
Math.trunc(Math.max(0, predictions[i].box.topLeft[1])),
Math.trunc(Math.min(input.shape[2] || 0, predictions[i].box.bottomRight[0]) - Math.max(0, predictions[i].box.topLeft[0])),
Math.trunc(Math.min(input.shape[1] || 0, predictions[i].box.bottomRight[1]) - Math.max(0, predictions[i].box.topLeft[1]))
] : [0, 0, 0, 0];
boxRaw = [
predictions[i].box.topLeft[0] / (input.shape[2] || 0),
predictions[i].box.topLeft[1] / (input.shape[1] || 0),
(predictions[i].box.bottomRight[0] - predictions[i].box.topLeft[0]) / (input.shape[2] || 0),
(predictions[i].box.bottomRight[1] - predictions[i].box.topLeft[1]) / (input.shape[1] || 0)
];
}
const landmarks = analyze(keypoints);
hands.push({
id: i,
score: Math.round(100 * predictions[i].confidence) / 100,
boxScore: Math.round(100 * predictions[i].boxConfidence) / 100,
fingerScore: Math.round(100 * predictions[i].fingerConfidence) / 100,
label: "hand",
box,
boxRaw,
keypoints,
annotations: annotations2,
landmarks
});
}
return hands;
}
async function load13(config3) {
var _a2, _b2;
if (env.initial) {
handDetectorModel = null;
handPoseModel = null;
}
if (!handDetectorModel || !handPoseModel) {
[handDetectorModel, handPoseModel] = await Promise.all([
config3.hand.enabled ? loadModel((_a2 = config3.hand.detector) == null ? void 0 : _a2.modelPath) : null,
config3.hand.landmarks ? loadModel((_b2 = config3.hand.skeleton) == null ? void 0 : _b2.modelPath) : null
]);
} else {
if (config3.debug)
log("cached model:", handDetectorModel["modelUrl"]);
if (config3.debug)
log("cached model:", handPoseModel["modelUrl"]);
}
const handDetector = new HandDetector(handDetectorModel);
handPipeline = new HandPipeline(handDetector, handPoseModel);
return [handDetectorModel, handPoseModel];
}
// src/hand/handtrack.ts
var models2 = [null, null];
var modelOutputNodes = ["StatefulPartitionedCall/Postprocessor/Slice", "StatefulPartitionedCall/Postprocessor/ExpandDims_1"];
var inputSize7 = [[0, 0], [0, 0]];
var classes = ["hand", "fist", "pinch", "point", "face", "tip", "pinchtip"];
var faceIndex = 4;
var boxExpandFact = 1.6;
var maxDetectorResolution = 512;
var detectorExpandFact = 1.4;
var skipped11 = Number.MAX_SAFE_INTEGER;
var lastTime12 = 0;
var outputSize = [0, 0];
var cache4 = {
boxes: [],
hands: []
};
var fingerMap = {
thumb: [1, 2, 3, 4],
index: [5, 6, 7, 8],
middle: [9, 10, 11, 12],
ring: [13, 14, 15, 16],
pinky: [17, 18, 19, 20],
base: [0],
palm: [0, 17, 13, 9, 5, 1, 0]
};
async function loadDetect2(config3) {
var _a2;
if (env.initial)
models2[0] = null;
if (!models2[0]) {
fakeOps(["tensorlistreserve", "enter", "tensorlistfromtensor", "merge", "loopcond", "switch", "exit", "tensorliststack", "nextiteration", "tensorlistsetitem", "tensorlistgetitem", "reciprocal", "shape", "split", "where"], config3);
models2[0] = await loadModel((_a2 = config3.hand.detector) == null ? void 0 : _a2.modelPath);
const inputs = Object.values(models2[0].modelSignature["inputs"]);
inputSize7[0][0] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[1].size) : 0;
inputSize7[0][1] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : 0;
} else if (config3.debug)
log("cached model:", models2[0]["modelUrl"]);
return models2[0];
}
async function loadSkeleton(config3) {
var _a2;
if (env.initial)
models2[1] = null;
if (!models2[1]) {
models2[1] = await loadModel((_a2 = config3.hand.skeleton) == null ? void 0 : _a2.modelPath);
const inputs = Object.values(models2[1].modelSignature["inputs"]);
inputSize7[1][0] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[1].size) : 0;
inputSize7[1][1] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : 0;
} else if (config3.debug)
log("cached model:", models2[1]["modelUrl"]);
return models2[1];
}
async function detectHands(input, config3) {
const hands = [];
if (!input || !models2[0])
return hands;
const t = {};
const ratio = (input.shape[2] || 1) / (input.shape[1] || 1);
const height = Math.min(Math.round((input.shape[1] || 0) / 8) * 8, maxDetectorResolution);
const width = Math.round(height * ratio / 8) * 8;
t.resize = Kn.resizeBilinear(input, [height, width]);
t.cast = le(t.resize, "int32");
[t.rawScores, t.rawBoxes] = await models2[0].executeAsync(t.cast, modelOutputNodes);
t.boxes = br(t.rawBoxes, [0, 2]);
t.scores = br(t.rawScores, [0]);
const classScores = Fs(t.scores, 1);
De(classScores[faceIndex]);
classScores.splice(faceIndex, 1);
t.filtered = es(classScores, 1);
De(classScores);
t.max = As(t.filtered, 1);
t.argmax = Yu(t.filtered, 1);
let id2 = 0;
t.nms = await Kn.nonMaxSuppressionAsync(t.boxes, t.max, (config3.hand.maxDetected || 0) + 1, config3.hand.iouThreshold || 0, config3.hand.minConfidence || 1);
const nms = await t.nms.data();
const scores = await t.max.data();
const classNum = await t.argmax.data();
for (const nmsIndex of Array.from(nms)) {
const boxSlice = qe(t.boxes, nmsIndex, 1);
const boxYX = await boxSlice.data();
De(boxSlice);
const boxData = [boxYX[1], boxYX[0], boxYX[3] - boxYX[1], boxYX[2] - boxYX[0]];
const boxRaw = scale(boxData, detectorExpandFact);
const boxFull = [Math.trunc(boxData[0] * outputSize[0]), Math.trunc(boxData[1] * outputSize[1]), Math.trunc(boxData[2] * outputSize[0]), Math.trunc(boxData[3] * outputSize[1])];
const score = scores[nmsIndex];
const label = classes[classNum[nmsIndex]];
const hand3 = { id: id2++, score, box: boxFull, boxRaw, label };
hands.push(hand3);
}
Object.keys(t).forEach((tensor) => De(t[tensor]));
hands.sort((a, b) => b.score - a.score);
if (hands.length > (config3.hand.maxDetected || 1))
hands.length = config3.hand.maxDetected || 1;
return hands;
}
async function detectFingers(input, h, config3) {
const hand3 = {
id: h.id,
score: Math.round(100 * h.score) / 100,
boxScore: Math.round(100 * h.score) / 100,
fingerScore: 0,
box: h.box,
boxRaw: h.boxRaw,
label: h.label,
keypoints: [],
landmarks: {},
annotations: {}
};
if (input && models2[1] && config3.hand.landmarks && h.score > (config3.hand.minConfidence || 0)) {
const t = {};
const boxCrop = [h.boxRaw[1], h.boxRaw[0], h.boxRaw[3] + h.boxRaw[1], h.boxRaw[2] + h.boxRaw[0]];
t.crop = Kn.cropAndResize(input, [boxCrop], [0], [inputSize7[1][0], inputSize7[1][1]], "bilinear");
t.div = xe(t.crop, constants.tf255);
[t.score, t.keypoints] = models2[1].execute(t.div, ["Identity_1", "Identity"]);
const rawScore = (await t.score.data())[0];
const score = (100 - Math.trunc(100 / (1 + Math.exp(rawScore)))) / 100;
if (score >= (config3.hand.minConfidence || 0)) {
hand3.fingerScore = score;
t.reshaped = U(t.keypoints, [-1, 3]);
const coordsData = await t.reshaped.array();
const coordsRaw = coordsData.map((kpt4) => [kpt4[0] / inputSize7[1][1], kpt4[1] / inputSize7[1][0], kpt4[2] || 0]);
const coordsNorm = coordsRaw.map((kpt4) => [kpt4[0] * h.boxRaw[2], kpt4[1] * h.boxRaw[3], kpt4[2] || 0]);
hand3.keypoints = coordsNorm.map((kpt4) => [outputSize[0] * (kpt4[0] + h.boxRaw[0]), outputSize[1] * (kpt4[1] + h.boxRaw[1]), kpt4[2] || 0]);
hand3.landmarks = analyze(hand3.keypoints);
for (const key of Object.keys(fingerMap)) {
hand3.annotations[key] = fingerMap[key].map((index2) => hand3.landmarks && hand3.keypoints[index2] ? hand3.keypoints[index2] : null);
}
}
Object.keys(t).forEach((tensor) => De(t[tensor]));
}
return hand3;
}
async function predict13(input, config3) {
var _a2, _b2;
if (!models2[0] || !models2[1] || !((_a2 = models2[0]) == null ? void 0 : _a2.inputs[0].shape) || !((_b2 = models2[1]) == null ? void 0 : _b2.inputs[0].shape))
return [];
outputSize = [input.shape[2] || 0, input.shape[1] || 0];
skipped11++;
const skipTime = (config3.hand.skipTime || 0) > now() - lastTime12;
const skipFrame = skipped11 < (config3.hand.skipFrames || 0);
if (config3.skipAllowed && skipTime && skipFrame) {
return cache4.hands;
}
return new Promise(async (resolve) => {
const skipTimeExtended = 3 * (config3.hand.skipTime || 0) > now() - lastTime12;
const skipFrameExtended = skipped11 < 3 * (config3.hand.skipFrames || 0);
if (config3.skipAllowed && cache4.hands.length === config3.hand.maxDetected) {
cache4.hands = await Promise.all(cache4.boxes.map((handBox) => detectFingers(input, handBox, config3)));
} else if (config3.skipAllowed && skipTimeExtended && skipFrameExtended && cache4.hands.length > 0) {
cache4.hands = await Promise.all(cache4.boxes.map((handBox) => detectFingers(input, handBox, config3)));
} else {
cache4.boxes = await detectHands(input, config3);
lastTime12 = now();
cache4.hands = await Promise.all(cache4.boxes.map((handBox) => detectFingers(input, handBox, config3)));
skipped11 = 0;
}
const oldCache = [...cache4.boxes];
cache4.boxes.length = 0;
if (config3.cacheSensitivity > 0) {
for (let i = 0; i < cache4.hands.length; i++) {
const boxKpt = square(cache4.hands[i].keypoints, outputSize);
if (boxKpt.box[2] / (input.shape[2] || 1) > 0.05 && boxKpt.box[3] / (input.shape[1] || 1) > 0.05 && cache4.hands[i].fingerScore && cache4.hands[i].fingerScore > (config3.hand.minConfidence || 0)) {
const boxScale = scale(boxKpt.box, boxExpandFact);
const boxScaleRaw = scale(boxKpt.boxRaw, boxExpandFact);
cache4.boxes.push({ ...oldCache[i], box: boxScale, boxRaw: boxScaleRaw });
}
}
}
for (let i = 0; i < cache4.hands.length; i++) {
const bbox = calc(cache4.hands[i].keypoints, outputSize);
cache4.hands[i].box = bbox.box;
cache4.hands[i].boxRaw = bbox.boxRaw;
}
resolve(cache4.hands);
});
}
// src/face/liveness.ts
var model13;
var cached2 = [];
var skipped12 = Number.MAX_SAFE_INTEGER;
var lastCount8 = 0;
var lastTime13 = 0;
async function load14(config3) {
var _a2;
if (env.initial)
model13 = null;
if (!model13)
model13 = await loadModel((_a2 = config3.face.liveness) == null ? void 0 : _a2.modelPath);
else if (config3.debug)
log("cached model:", model13["modelUrl"]);
return model13;
}
async function predict14(image, config3, idx, count2) {
var _a2, _b2;
if (!model13)
return 0;
const skipTime = (((_a2 = config3.face.liveness) == null ? void 0 : _a2.skipTime) || 0) > now() - lastTime13;
const skipFrame = skipped12 < (((_b2 = config3.face.liveness) == null ? void 0 : _b2.skipFrames) || 0);
if (config3.skipAllowed && skipTime && skipFrame && lastCount8 === count2 && cached2[idx]) {
skipped12++;
return cached2[idx];
}
skipped12 = 0;
return new Promise(async (resolve) => {
const resize = Kn.resizeBilinear(image, [(model13 == null ? void 0 : model13.inputs[0].shape) ? model13.inputs[0].shape[2] : 0, (model13 == null ? void 0 : model13.inputs[0].shape) ? model13.inputs[0].shape[1] : 0], false);
const res = model13 == null ? void 0 : model13.execute(resize);
const num = (await res.data())[0];
cached2[idx] = Math.round(100 * num) / 100;
lastCount8 = count2;
lastTime13 = now();
De([resize, res]);
resolve(cached2[idx]);
});
}
// src/body/movenetcoords.ts
var movenetcoords_exports = {};
__export(movenetcoords_exports, {
connected: () => connected3,
horizontal: () => horizontal,
kpt: () => kpt3,
relative: () => relative,
vertical: () => vertical
});
var kpt3 = [
"nose",
"leftEye",
"rightEye",
"leftEar",
"rightEar",
"leftShoulder",
"rightShoulder",
"leftElbow",
"rightElbow",
"leftWrist",
"rightWrist",
"leftHip",
"rightHip",
"leftKnee",
"rightKnee",
"leftAnkle",
"rightAnkle"
];
var horizontal = [
["leftEye", "rightEye"],
["leftEar", "rightEar"],
["leftShoulder", "rightShoulder"],
["leftElbow", "rightElbow"],
["leftWrist", "rightWrist"],
["leftHip", "rightHip"],
["leftKnee", "rightKnee"],
["leftAnkle", "rightAnkle"]
];
var vertical = [
["leftKnee", "leftShoulder"],
["rightKnee", "rightShoulder"],
["leftAnkle", "leftKnee"],
["rightAnkle", "rightKnee"]
];
var relative = [
[["leftHip", "rightHip"], ["leftShoulder", "rightShoulder"]],
[["leftElbow", "rightElbow"], ["leftShoulder", "rightShoulder"]]
];
var connected3 = {
leftLeg: ["leftHip", "leftKnee", "leftAnkle"],
rightLeg: ["rightHip", "rightKnee", "rightAnkle"],
torso: ["leftShoulder", "rightShoulder", "rightHip", "leftHip", "leftShoulder"],
leftArm: ["leftShoulder", "leftElbow", "leftWrist"],
rightArm: ["rightShoulder", "rightElbow", "rightWrist"],
head: []
};
// src/body/movenetfix.ts
var maxJitter = 5e-3;
var cache5 = {
keypoints: [],
padding: [[0, 0], [0, 0], [0, 0], [0, 0]]
};
function bodyParts(body4) {
for (const pair of horizontal) {
const left = body4.keypoints.findIndex((kp2) => kp2.part === pair[0]);
const right = body4.keypoints.findIndex((kp2) => kp2.part === pair[1]);
if (body4.keypoints[left] && body4.keypoints[right]) {
if (body4.keypoints[left].position[0] < body4.keypoints[right].position[0]) {
const tmp = body4.keypoints[left];
body4.keypoints[left] = body4.keypoints[right];
body4.keypoints[right] = tmp;
}
}
}
for (const pair of vertical) {
const lower = body4.keypoints.findIndex((kp2) => kp2 && kp2.part === pair[0]);
const higher = body4.keypoints.findIndex((kp2) => kp2 && kp2.part === pair[1]);
if (body4.keypoints[lower] && body4.keypoints[higher]) {
if (body4.keypoints[lower].position[1] < body4.keypoints[higher].position[1]) {
body4.keypoints.splice(lower, 1);
}
}
}
for (const [pair, compare2] of relative) {
const left = body4.keypoints.findIndex((kp2) => kp2 && kp2.part === pair[0]);
const right = body4.keypoints.findIndex((kp2) => kp2 && kp2.part === pair[1]);
const leftTo = body4.keypoints.findIndex((kp2) => kp2 && kp2.part === compare2[0]);
const rightTo = body4.keypoints.findIndex((kp2) => kp2 && kp2.part === compare2[1]);
if (!body4.keypoints[leftTo] || !body4.keypoints[rightTo])
continue;
const distanceLeft = body4.keypoints[left] ? [
Math.abs(body4.keypoints[leftTo].position[0] - body4.keypoints[left].position[0]),
Math.abs(body4.keypoints[rightTo].position[0] - body4.keypoints[left].position[0])
] : [0, 0];
const distanceRight = body4.keypoints[right] ? [
Math.abs(body4.keypoints[rightTo].position[0] - body4.keypoints[right].position[0]),
Math.abs(body4.keypoints[leftTo].position[0] - body4.keypoints[right].position[0])
] : [0, 0];
if (distanceLeft[0] > distanceLeft[1] || distanceRight[0] > distanceRight[1]) {
const tmp = body4.keypoints[left];
body4.keypoints[left] = body4.keypoints[right];
body4.keypoints[right] = tmp;
}
}
}
function jitter(keypoints) {
for (let i = 0; i < keypoints.length; i++) {
if (keypoints[i] && cache5.keypoints[i]) {
const diff = [Math.abs(keypoints[i].positionRaw[0] - cache5.keypoints[i].positionRaw[0]), Math.abs(keypoints[i].positionRaw[1] - cache5.keypoints[i].positionRaw[1])];
if (diff[0] < maxJitter && diff[1] < maxJitter) {
keypoints[i] = cache5.keypoints[i];
} else {
cache5.keypoints[i] = keypoints[i];
}
} else {
cache5.keypoints[i] = keypoints[i];
}
}
return keypoints;
}
function padInput(input, inputSize10) {
const t = {};
if (!input.shape || !input.shape[1] || !input.shape[2])
return input;
cache5.padding = [
[0, 0],
[input.shape[2] > input.shape[1] ? Math.trunc((input.shape[2] - input.shape[1]) / 2) : 0, input.shape[2] > input.shape[1] ? Math.trunc((input.shape[2] - input.shape[1]) / 2) : 0],
[input.shape[1] > input.shape[2] ? Math.trunc((input.shape[1] - input.shape[2]) / 2) : 0, input.shape[1] > input.shape[2] ? Math.trunc((input.shape[1] - input.shape[2]) / 2) : 0],
[0, 0]
];
t.pad = bo(input, cache5.padding);
t.resize = Kn.resizeBilinear(t.pad, [inputSize10, inputSize10]);
const final = le(t.resize, "int32");
Object.keys(t).forEach((tensor) => De(t[tensor]));
return final;
}
function rescaleBody(body4, outputSize2) {
body4.keypoints = body4.keypoints.filter((kpt4) => kpt4 && kpt4.position);
for (const kpt4 of body4.keypoints) {
kpt4.position = [
kpt4.position[0] * (outputSize2[0] + cache5.padding[2][0] + cache5.padding[2][1]) / outputSize2[0] - cache5.padding[2][0],
kpt4.position[1] * (outputSize2[1] + cache5.padding[1][0] + cache5.padding[1][1]) / outputSize2[1] - cache5.padding[1][0]
];
kpt4.positionRaw = [
kpt4.position[0] / outputSize2[0],
kpt4.position[1] / outputSize2[1]
];
}
const rescaledBoxes = calc(body4.keypoints.map((pt2) => pt2.position), outputSize2);
body4.box = rescaledBoxes.box;
body4.boxRaw = rescaledBoxes.boxRaw;
return body4;
}
// src/body/movenet.ts
var model14;
var inputSize8 = 0;
var skipped13 = Number.MAX_SAFE_INTEGER;
var cache6 = {
boxes: [],
bodies: [],
last: 0
};
async function load15(config3) {
if (env.initial)
model14 = null;
if (!model14) {
fakeOps(["size"], config3);
model14 = await loadModel(config3.body.modelPath);
} else if (config3.debug)
log("cached model:", model14["modelUrl"]);
inputSize8 = model14.inputs[0].shape ? model14.inputs[0].shape[2] : 0;
if (inputSize8 < 64)
inputSize8 = 256;
return model14;
}
async function parseSinglePose(res, config3, image) {
const kpt4 = res[0][0];
const keypoints = [];
let score = 0;
for (let id2 = 0; id2 < kpt4.length; id2++) {
score = kpt4[id2][2];
if (score > config3.body.minConfidence) {
const positionRaw = [kpt4[id2][1], kpt4[id2][0]];
keypoints.push({
score: Math.round(100 * score) / 100,
part: kpt3[id2],
positionRaw,
position: [
Math.round((image.shape[2] || 0) * positionRaw[0]),
Math.round((image.shape[1] || 0) * positionRaw[1])
]
});
}
}
score = keypoints.reduce((prev, curr) => curr.score > prev ? curr.score : prev, 0);
const bodies = [];
const newBox = calc(keypoints.map((pt2) => pt2.position), [image.shape[2], image.shape[1]]);
const annotations2 = {};
for (const [name, indexes] of Object.entries(connected3)) {
const pt2 = [];
for (let i = 0; i < indexes.length - 1; i++) {
const pt0 = keypoints.find((kp2) => kp2.part === indexes[i]);
const pt1 = keypoints.find((kp2) => kp2.part === indexes[i + 1]);
if (pt0 && pt1 && pt0.score > (config3.body.minConfidence || 0) && pt1.score > (config3.body.minConfidence || 0))
pt2.push([pt0.position, pt1.position]);
}
annotations2[name] = pt2;
}
const body4 = { id: 0, score, box: newBox.box, boxRaw: newBox.boxRaw, keypoints, annotations: annotations2 };
bodyParts(body4);
bodies.push(body4);
return bodies;
}
async function parseMultiPose(res, config3, image) {
const bodies = [];
for (let id2 = 0; id2 < res[0].length; id2++) {
const kpt4 = res[0][id2];
const totalScore = Math.round(100 * kpt4[51 + 4]) / 100;
if (totalScore > config3.body.minConfidence) {
const keypoints = [];
for (let i = 0; i < 17; i++) {
const score = kpt4[3 * i + 2];
if (score > config3.body.minConfidence) {
const positionRaw = [kpt4[3 * i + 1], kpt4[3 * i + 0]];
keypoints.push({
part: kpt3[i],
score: Math.round(100 * score) / 100,
positionRaw,
position: [Math.round((image.shape[2] || 0) * positionRaw[0]), Math.round((image.shape[1] || 0) * positionRaw[1])]
});
}
}
const newBox = calc(keypoints.map((pt2) => pt2.position), [image.shape[2], image.shape[1]]);
const annotations2 = {};
for (const [name, indexes] of Object.entries(connected3)) {
const pt2 = [];
for (let i = 0; i < indexes.length - 1; i++) {
const pt0 = keypoints.find((kp2) => kp2.part === indexes[i]);
const pt1 = keypoints.find((kp2) => kp2.part === indexes[i + 1]);
if (pt0 && pt1 && pt0.score > (config3.body.minConfidence || 0) && pt1.score > (config3.body.minConfidence || 0))
pt2.push([pt0.position, pt1.position]);
}
annotations2[name] = pt2;
}
const body4 = { id: id2, score: totalScore, box: newBox.box, boxRaw: newBox.boxRaw, keypoints: [...keypoints], annotations: annotations2 };
bodyParts(body4);
bodies.push(body4);
}
}
bodies.sort((a, b) => b.score - a.score);
if (bodies.length > config3.body.maxDetected)
bodies.length = config3.body.maxDetected;
return bodies;
}
async function predict15(input, config3) {
if (!model14 || !(model14 == null ? void 0 : model14.inputs[0].shape))
return [];
if (!config3.skipAllowed)
cache6.boxes.length = 0;
skipped13++;
const skipTime = (config3.body.skipTime || 0) > now() - cache6.last;
const skipFrame = skipped13 < (config3.body.skipFrames || 0);
if (config3.skipAllowed && skipTime && skipFrame) {
return cache6.bodies;
}
return new Promise(async (resolve) => {
const t = {};
skipped13 = 0;
t.input = padInput(input, inputSize8);
t.res = model14 == null ? void 0 : model14.execute(t.input);
cache6.last = now();
const res = await t.res.array();
cache6.bodies = t.res.shape[2] === 17 ? await parseSinglePose(res, config3, input) : await parseMultiPose(res, config3, input);
for (const body4 of cache6.bodies) {
rescaleBody(body4, [input.shape[2] || 1, input.shape[1] || 1]);
jitter(body4.keypoints);
}
Object.keys(t).forEach((tensor) => De(t[tensor]));
resolve(cache6.bodies);
});
}
// src/object/nanodet.ts
var model15;
var last9 = [];
var lastTime14 = 0;
var skipped14 = Number.MAX_SAFE_INTEGER;
var inputSize9 = 0;
var scaleBox = 2.5;
async function load16(config3) {
if (!model15 || env.initial) {
model15 = await loadModel(config3.object.modelPath);
const inputs = Object.values(model15.modelSignature["inputs"]);
inputSize9 = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : 0;
} else if (config3.debug)
log("cached model:", model15["modelUrl"]);
return model15;
}
async function process4(res, outputShape, config3) {
let id2 = 0;
let results = [];
for (const strideSize of [1, 2, 4]) {
q(async () => {
const baseSize = strideSize * 13;
const scoresT = br(res.find((a) => a.shape[1] === baseSize ** 2 && (a.shape[2] || 0) === labels.length));
const featuresT = br(res.find((a) => a.shape[1] === baseSize ** 2 && (a.shape[2] || 0) < labels.length));
const boxesMax = featuresT.reshape([-1, 4, featuresT.shape[1] / 4]);
const boxIdx = await boxesMax.argMax(2).array();
const scores = await scoresT.array();
for (let i = 0; i < scoresT.shape[0]; i++) {
for (let j = 0; j < scoresT.shape[1]; j++) {
const score = scores[i][j];
if (score > (config3.object.minConfidence || 0) && j !== 61) {
const cx = (0.5 + Math.trunc(i % baseSize)) / baseSize;
const cy2 = (0.5 + Math.trunc(i / baseSize)) / baseSize;
const boxOffset = boxIdx[i].map((a) => a * (baseSize / strideSize / inputSize9));
const [x, y] = [
cx - scaleBox / strideSize * boxOffset[0],
cy2 - scaleBox / strideSize * boxOffset[1]
];
const [w10, h] = [
cx + scaleBox / strideSize * boxOffset[2] - x,
cy2 + scaleBox / strideSize * boxOffset[3] - y
];
let boxRaw = [x, y, w10, h];
boxRaw = boxRaw.map((a) => Math.max(0, Math.min(a, 1)));
const box = [
boxRaw[0] * outputShape[0],
boxRaw[1] * outputShape[1],
boxRaw[2] * outputShape[0],
boxRaw[3] * outputShape[1]
];
const result = {
id: id2++,
score: Math.round(100 * score) / 100,
class: j + 1,
label: labels[j].label,
box: box.map((a) => Math.trunc(a)),
boxRaw
};
results.push(result);
}
}
}
});
}
res.forEach((t) => De(t));
const nmsBoxes = results.map((a) => [a.boxRaw[1], a.boxRaw[0], a.boxRaw[3], a.boxRaw[2]]);
const nmsScores = results.map((a) => a.score);
let nmsIdx = [];
if (nmsBoxes && nmsBoxes.length > 0) {
const nms = await Kn.nonMaxSuppressionAsync(nmsBoxes, nmsScores, config3.object.maxDetected, config3.object.iouThreshold, config3.object.minConfidence);
nmsIdx = await nms.data();
De(nms);
}
results = results.filter((_val, idx) => nmsIdx.includes(idx)).sort((a, b) => b.score - a.score);
return results;
}
async function predict16(image, config3) {
const skipTime = (config3.object.skipTime || 0) > now() - lastTime14;
const skipFrame = skipped14 < (config3.object.skipFrames || 0);
if (config3.skipAllowed && skipTime && skipFrame && last9.length > 0) {
skipped14++;
return last9;
}
skipped14 = 0;
if (!env.kernels.includes("mod") || !env.kernels.includes("sparsetodense"))
return last9;
return new Promise(async (resolve) => {
const outputSize2 = [image.shape[2] || 0, image.shape[1] || 0];
const resize = Kn.resizeBilinear(image, [inputSize9, inputSize9], false);
const norm = xe(resize, constants.tf255);
const transpose = norm.transpose([0, 3, 1, 2]);
De(norm);
De(resize);
let objectT;
if (config3.object.enabled)
objectT = model15.execute(transpose);
lastTime14 = now();
De(transpose);
const obj = await process4(objectT, outputSize2, config3);
last9 = obj;
resolve(obj);
});
}
// src/body/posenetutils.ts
var partNames = [
"nose",
"leftEye",
"rightEye",
"leftEar",
"rightEar",
"leftShoulder",
"rightShoulder",
"leftElbow",
"rightElbow",
"leftWrist",
"rightWrist",
"leftHip",
"rightHip",
"leftKnee",
"rightKnee",
"leftAnkle",
"rightAnkle"
];
var count = partNames.length;
var partIds = partNames.reduce((result, jointName, i) => {
result[jointName] = i;
return result;
}, {});
var connectedPartNames = [
["leftHip", "leftShoulder"],
["leftElbow", "leftShoulder"],
["leftElbow", "leftWrist"],
["leftHip", "leftKnee"],
["leftKnee", "leftAnkle"],
["rightHip", "rightShoulder"],
["rightElbow", "rightShoulder"],
["rightElbow", "rightWrist"],
["rightHip", "rightKnee"],
["rightKnee", "rightAnkle"],
["leftShoulder", "rightShoulder"],
["leftHip", "rightHip"]
];
var connectedPartIndices = connectedPartNames.map(([jointNameA, jointNameB]) => [partIds[jointNameA], partIds[jointNameB]]);
var poseChain = [
["nose", "leftEye"],
["leftEye", "leftEar"],
["nose", "rightEye"],
["rightEye", "rightEar"],
["nose", "leftShoulder"],
["leftShoulder", "leftElbow"],
["leftElbow", "leftWrist"],
["leftShoulder", "leftHip"],
["leftHip", "leftKnee"],
["leftKnee", "leftAnkle"],
["nose", "rightShoulder"],
["rightShoulder", "rightElbow"],
["rightElbow", "rightWrist"],
["rightShoulder", "rightHip"],
["rightHip", "rightKnee"],
["rightKnee", "rightAnkle"]
];
function getBoundingBox(keypoints) {
const coord = keypoints.reduce(({ maxX, maxY, minX, minY }, { position: { x, y } }) => ({
maxX: Math.max(maxX, x),
maxY: Math.max(maxY, y),
minX: Math.min(minX, x),
minY: Math.min(minY, y)
}), {
maxX: Number.NEGATIVE_INFINITY,
maxY: Number.NEGATIVE_INFINITY,
minX: Number.POSITIVE_INFINITY,
minY: Number.POSITIVE_INFINITY
});
return [coord.minX, coord.minY, coord.maxX - coord.minX, coord.maxY - coord.minY];
}
function scalePoses(poses, [height, width], [inputResolutionHeight, inputResolutionWidth]) {
const scaleY = height / inputResolutionHeight;
const scaleX = width / inputResolutionWidth;
const scalePose = (pose, i) => ({
id: i,
score: pose.score,
boxRaw: [pose.box[0] / inputResolutionWidth, pose.box[1] / inputResolutionHeight, pose.box[2] / inputResolutionWidth, pose.box[3] / inputResolutionHeight],
box: [Math.trunc(pose.box[0] * scaleX), Math.trunc(pose.box[1] * scaleY), Math.trunc(pose.box[2] * scaleX), Math.trunc(pose.box[3] * scaleY)],
keypoints: pose.keypoints.map(({ score, part, position }) => ({
score,
part,
position: [Math.trunc(position.x * scaleX), Math.trunc(position.y * scaleY)],
positionRaw: [position.x / inputResolutionHeight, position.y / inputResolutionHeight]
})),
annotations: {}
});
const scaledPoses = poses.map((pose, i) => scalePose(pose, i));
return scaledPoses;
}
var MaxHeap = class {
constructor(maxSize2, getElementValue) {
__publicField(this, "priorityQueue");
__publicField(this, "numberOfElements");
__publicField(this, "getElementValue");
this.priorityQueue = new Array(maxSize2);
this.numberOfElements = -1;
this.getElementValue = getElementValue;
}
enqueue(x) {
this.priorityQueue[++this.numberOfElements] = x;
this.swim(this.numberOfElements);
}
dequeue() {
const max = this.priorityQueue[0];
this.exchange(0, this.numberOfElements--);
this.sink(0);
this.priorityQueue[this.numberOfElements + 1] = null;
return max;
}
empty() {
return this.numberOfElements === -1;
}
size() {
return this.numberOfElements + 1;
}
all() {
return this.priorityQueue.slice(0, this.numberOfElements + 1);
}
max() {
return this.priorityQueue[0];
}
swim(k) {
while (k > 0 && this.less(Math.floor(k / 2), k)) {
this.exchange(k, Math.floor(k / 2));
k = Math.floor(k / 2);
}
}
sink(k) {
while (2 * k <= this.numberOfElements) {
let j = 2 * k;
if (j < this.numberOfElements && this.less(j, j + 1))
j++;
if (!this.less(k, j))
break;
this.exchange(k, j);
k = j;
}
}
getValueAt(i) {
return this.getElementValue(this.priorityQueue[i]);
}
less(i, j) {
return this.getValueAt(i) < this.getValueAt(j);
}
exchange(i, j) {
const t = this.priorityQueue[i];
this.priorityQueue[i] = this.priorityQueue[j];
this.priorityQueue[j] = t;
}
};
function getOffsetPoint(y, x, keypoint, offsets) {
return {
y: offsets.get(y, x, keypoint),
x: offsets.get(y, x, keypoint + count)
};
}
function getImageCoords(part, outputStride2, offsets) {
const { heatmapY, heatmapX, id: keypoint } = part;
const { y, x } = getOffsetPoint(heatmapY, heatmapX, keypoint, offsets);
return {
x: part.heatmapX * outputStride2 + x,
y: part.heatmapY * outputStride2 + y
};
}
function clamp(a, min, max) {
if (a < min)
return min;
if (a > max)
return max;
return a;
}
function squaredDistance(y12, x12, y22, x22) {
const dy2 = y22 - y12;
const dx = x22 - x12;
return dy2 * dy2 + dx * dx;
}
function addVectors(a, b) {
return { x: a.x + b.x, y: a.y + b.y };
}
// src/body/posenet.ts
var model16;
var poseNetOutputs = ["MobilenetV1/offset_2/BiasAdd", "MobilenetV1/heatmap_2/BiasAdd", "MobilenetV1/displacement_fwd_2/BiasAdd", "MobilenetV1/displacement_bwd_2/BiasAdd"];
var localMaximumRadius = 1;
var outputStride = 16;
var squaredNmsRadius = 50 ** 2;
function traverse(edgeId, sourceKeypoint, targetId, scores, offsets, displacements, offsetRefineStep = 2) {
const getDisplacement = (point2) => ({
y: displacements.get(point2.y, point2.x, edgeId),
x: displacements.get(point2.y, point2.x, displacements.shape[2] / 2 + edgeId)
});
const getStridedIndexNearPoint = (point2, height2, width2) => ({
y: clamp(Math.round(point2.y / outputStride), 0, height2 - 1),
x: clamp(Math.round(point2.x / outputStride), 0, width2 - 1)
});
const [height, width] = scores.shape;
const sourceKeypointIndices = getStridedIndexNearPoint(sourceKeypoint.position, height, width);
const displacement = getDisplacement(sourceKeypointIndices);
const displacedPoint = addVectors(sourceKeypoint.position, displacement);
let targetKeypoint = displacedPoint;
for (let i = 0; i < offsetRefineStep; i++) {
const targetKeypointIndices = getStridedIndexNearPoint(targetKeypoint, height, width);
const offsetPoint = getOffsetPoint(targetKeypointIndices.y, targetKeypointIndices.x, targetId, offsets);
targetKeypoint = addVectors({ x: targetKeypointIndices.x * outputStride, y: targetKeypointIndices.y * outputStride }, { x: offsetPoint.x, y: offsetPoint.y });
}
const targetKeyPointIndices = getStridedIndexNearPoint(targetKeypoint, height, width);
const score = scores.get(targetKeyPointIndices.y, targetKeyPointIndices.x, targetId);
return { position: targetKeypoint, part: partNames[targetId], score };
}
function decodePose(root, scores, offsets, displacementsFwd, displacementsBwd) {
const tuples = poseChain.map(([parentJoinName, childJoinName]) => [partIds[parentJoinName], partIds[childJoinName]]);
const edgesFwd = tuples.map(([, childJointId]) => childJointId);
const edgesBwd = tuples.map(([parentJointId]) => parentJointId);
const numParts = scores.shape[2];
const numEdges = edgesFwd.length;
const keypoints = new Array(numParts);
const rootPoint = getImageCoords(root.part, outputStride, offsets);
keypoints[root.part.id] = {
score: root.score,
part: partNames[root.part.id],
position: rootPoint
};
for (let edge = numEdges - 1; edge >= 0; --edge) {
const sourceId = edgesFwd[edge];
const targetId = edgesBwd[edge];
if (keypoints[sourceId] && !keypoints[targetId]) {
keypoints[targetId] = traverse(edge, keypoints[sourceId], targetId, scores, offsets, displacementsBwd);
}
}
for (let edge = 0; edge < numEdges; ++edge) {
const sourceId = edgesBwd[edge];
const targetId = edgesFwd[edge];
if (keypoints[sourceId] && !keypoints[targetId]) {
keypoints[targetId] = traverse(edge, keypoints[sourceId], targetId, scores, offsets, displacementsFwd);
}
}
return keypoints;
}
function scoreIsMaximumInLocalWindow(keypointId, score, heatmapY, heatmapX, scores) {
const [height, width] = scores.shape;
let localMaximum = true;
const yStart = Math.max(heatmapY - localMaximumRadius, 0);
const yEnd = Math.min(heatmapY + localMaximumRadius + 1, height);
for (let yCurrent = yStart; yCurrent < yEnd; ++yCurrent) {
const xStart = Math.max(heatmapX - localMaximumRadius, 0);
const xEnd = Math.min(heatmapX + localMaximumRadius + 1, width);
for (let xCurrent = xStart; xCurrent < xEnd; ++xCurrent) {
if (scores.get(yCurrent, xCurrent, keypointId) > score) {
localMaximum = false;
break;
}
}
if (!localMaximum)
break;
}
return localMaximum;
}
function buildPartWithScoreQueue(minConfidence2, scores) {
const [height, width, numKeypoints] = scores.shape;
const queue = new MaxHeap(height * width * numKeypoints, ({ score }) => score);
for (let heatmapY = 0; heatmapY < height; ++heatmapY) {
for (let heatmapX = 0; heatmapX < width; ++heatmapX) {
for (let keypointId = 0; keypointId < numKeypoints; ++keypointId) {
const score = scores.get(heatmapY, heatmapX, keypointId);
if (score < minConfidence2)
continue;
if (scoreIsMaximumInLocalWindow(keypointId, score, heatmapY, heatmapX, scores))
queue.enqueue({ score, part: { heatmapY, heatmapX, id: keypointId } });
}
}
}
return queue;
}
function withinRadius(poses, { x, y }, keypointId) {
return poses.some(({ keypoints }) => {
var _a2;
const correspondingKeypoint = (_a2 = keypoints[keypointId]) == null ? void 0 : _a2.position;
if (!correspondingKeypoint)
return false;
return squaredDistance(y, x, correspondingKeypoint.y, correspondingKeypoint.x) <= squaredNmsRadius;
});
}
function getInstanceScore(existingPoses, keypoints) {
const notOverlappedKeypointScores = keypoints.reduce((result, { position, score }, keypointId) => {
if (!withinRadius(existingPoses, position, keypointId))
result += score;
return result;
}, 0);
return notOverlappedKeypointScores / keypoints.length;
}
function decode(offsets, scores, displacementsFwd, displacementsBwd, maxDetected, minConfidence2) {
const poses = [];
const queue = buildPartWithScoreQueue(minConfidence2, scores);
while (poses.length < maxDetected && !queue.empty()) {
const root = queue.dequeue();
const rootImageCoords = getImageCoords(root.part, outputStride, offsets);
if (withinRadius(poses, rootImageCoords, root.part.id))
continue;
let keypoints = decodePose(root, scores, offsets, displacementsFwd, displacementsBwd);
keypoints = keypoints.filter((a) => a.score > minConfidence2);
const score = getInstanceScore(poses, keypoints);
const box = getBoundingBox(keypoints);
if (score > minConfidence2)
poses.push({ keypoints, box, score: Math.round(100 * score) / 100 });
}
return poses;
}
async function predict17(input, config3) {
const res = q(() => {
if (!model16.inputs[0].shape)
return [];
const resized = Kn.resizeBilinear(input, [model16.inputs[0].shape[2], model16.inputs[0].shape[1]]);
const normalized = ge(xe(le(resized, "float32"), 127.5), 1);
const results = model16.execute(normalized, poseNetOutputs);
const results3d = results.map((y) => br(y, [0]));
results3d[1] = qs(results3d[1]);
return results3d;
});
const buffers = await Promise.all(res.map((tensor) => tensor.buffer()));
for (const t of res)
De(t);
const decoded = await decode(buffers[0], buffers[1], buffers[2], buffers[3], config3.body.maxDetected, config3.body.minConfidence);
if (!model16.inputs[0].shape)
return [];
const scaled = scalePoses(decoded, [input.shape[1], input.shape[2]], [model16.inputs[0].shape[2], model16.inputs[0].shape[1]]);
return scaled;
}
async function load17(config3) {
if (!model16 || env.initial)
model16 = await loadModel(config3.body.modelPath);
else if (config3.debug)
log("cached model:", model16["modelUrl"]);
return model16;
}
// src/segmentation/segmentation.ts
var model17;
var busy = false;
async function load18(config3) {
if (!model17 || env.initial)
model17 = await loadModel(config3.segmentation.modelPath);
else if (config3.debug)
log("cached model:", model17["modelUrl"]);
return model17;
}
async function process5(input, background, config3) {
var _a2, _b2;
if (busy)
return { data: [], canvas: null, alpha: null };
busy = true;
if (!model17)
await load18(config3);
const inputImage = await process2(input, config3);
const width = ((_a2 = inputImage.tensor) == null ? void 0 : _a2.shape[2]) || 0;
const height = ((_b2 = inputImage.tensor) == null ? void 0 : _b2.shape[1]) || 0;
if (!inputImage.tensor)
return { data: [], canvas: null, alpha: null };
const t = {};
t.resize = Kn.resizeBilinear(inputImage.tensor, [model17.inputs[0].shape ? model17.inputs[0].shape[1] : 0, model17.inputs[0].shape ? model17.inputs[0].shape[2] : 0], false);
De(inputImage.tensor);
t.norm = xe(t.resize, constants.tf255);
t.res = model17.execute(t.norm);
t.squeeze = br(t.res, 0);
if (t.squeeze.shape[2] === 2) {
t.softmax = xb(t.squeeze);
[t.bg, t.fg] = Fs(t.softmax, 2);
t.expand = Pn(t.fg, 2);
t.pad = Pn(t.expand, 0);
t.crop = Kn.cropAndResize(t.pad, [[0, 0, 0.5, 0.5]], [0], [width, height]);
t.data = br(t.crop, 0);
} else {
t.data = Kn.resizeBilinear(t.squeeze, [height, width]);
}
const data = Array.from(await t.data.data());
if (env.node && !env.Canvas && typeof ImageData === "undefined") {
if (config3.debug)
log("canvas support missing");
Object.keys(t).forEach((tensor) => De(t[tensor]));
return { data, canvas: null, alpha: null };
}
const alphaCanvas = canvas(width, height);
if (Gk)
await Gk.toPixels(t.data, alphaCanvas);
const alphaCtx = alphaCanvas.getContext("2d");
if (config3.segmentation.blur && config3.segmentation.blur > 0)
alphaCtx.filter = `blur(${config3.segmentation.blur}px)`;
const alphaData = alphaCtx.getImageData(0, 0, width, height);
const compositeCanvas = canvas(width, height);
const compositeCtx = compositeCanvas.getContext("2d");
if (inputImage.canvas)
compositeCtx.drawImage(inputImage.canvas, 0, 0);
compositeCtx.globalCompositeOperation = "darken";
if (config3.segmentation.blur && config3.segmentation.blur > 0)
compositeCtx.filter = `blur(${config3.segmentation.blur}px)`;
compositeCtx.drawImage(alphaCanvas, 0, 0);
compositeCtx.globalCompositeOperation = "source-over";
compositeCtx.filter = "none";
const compositeData = compositeCtx.getImageData(0, 0, width, height);
for (let i = 0; i < width * height; i++)
compositeData.data[4 * i + 3] = alphaData.data[4 * i + 0];
compositeCtx.putImageData(compositeData, 0, 0);
let mergedCanvas = null;
if (background && compositeCanvas) {
mergedCanvas = canvas(width, height);
const bgImage = await process2(background, config3);
De(bgImage.tensor);
const ctxMerge = mergedCanvas.getContext("2d");
ctxMerge.drawImage(bgImage.canvas, 0, 0, mergedCanvas.width, mergedCanvas.height);
ctxMerge.drawImage(compositeCanvas, 0, 0);
}
Object.keys(t).forEach((tensor) => De(t[tensor]));
busy = false;
return { data, canvas: compositeCanvas, alpha: alphaCanvas };
}
// src/models.ts
var Models = class {
constructor() {
__publicField(this, "ssrnetage", null);
__publicField(this, "gear", null);
__publicField(this, "blazeposedetect", null);
__publicField(this, "blazepose", null);
__publicField(this, "centernet", null);
__publicField(this, "efficientpose", null);
__publicField(this, "mobilefacenet", null);
__publicField(this, "emotion", null);
__publicField(this, "facedetect", null);
__publicField(this, "faceiris", null);
__publicField(this, "facemesh", null);
__publicField(this, "faceres", null);
__publicField(this, "ssrnetgender", null);
__publicField(this, "handpose", null);
__publicField(this, "handskeleton", null);
__publicField(this, "handtrack", null);
__publicField(this, "liveness", null);
__publicField(this, "movenet", null);
__publicField(this, "nanodet", null);
__publicField(this, "posenet", null);
__publicField(this, "segmentation", null);
__publicField(this, "antispoof", null);
}
};
function reset(instance) {
for (const model18 of Object.keys(instance.models))
instance.models[model18] = null;
}
async function load19(instance) {
var _a2, _b2, _c, _d2, _e2, _f, _g2, _h, _i2, _j2, _k2, _l2, _m2, _n2, _o, _p2, _q2, _r2, _s2, _t2, _u2, _v2, _w2, _x2, _y2, _z2, _A2, _B2, _C2, _D2, _E2;
if (env.initial)
reset(instance);
if (instance.config.hand.enabled) {
if (!instance.models.handpose && ((_b2 = (_a2 = instance.config.hand.detector) == null ? void 0 : _a2.modelPath) == null ? void 0 : _b2.includes("handdetect")))
[instance.models.handpose, instance.models.handskeleton] = await load13(instance.config);
if (!instance.models.handskeleton && instance.config.hand.landmarks && ((_d2 = (_c = instance.config.hand.detector) == null ? void 0 : _c.modelPath) == null ? void 0 : _d2.includes("handdetect")))
[instance.models.handpose, instance.models.handskeleton] = await load13(instance.config);
}
if (instance.config.body.enabled && !instance.models.blazepose && ((_f = (_e2 = instance.config.body) == null ? void 0 : _e2.modelPath) == null ? void 0 : _f.includes("blazepose")))
instance.models.blazepose = loadPose(instance.config);
if (instance.config.body.enabled && !instance.models.blazeposedetect && instance.config.body["detector"] && instance.config.body["detector"]["modelPath"])
instance.models.blazeposedetect = loadDetect(instance.config);
if (instance.config.body.enabled && !instance.models.efficientpose && ((_h = (_g2 = instance.config.body) == null ? void 0 : _g2.modelPath) == null ? void 0 : _h.includes("efficientpose")))
instance.models.efficientpose = load7(instance.config);
if (instance.config.body.enabled && !instance.models.movenet && ((_j2 = (_i2 = instance.config.body) == null ? void 0 : _i2.modelPath) == null ? void 0 : _j2.includes("movenet")))
instance.models.movenet = load15(instance.config);
if (instance.config.body.enabled && !instance.models.posenet && ((_l2 = (_k2 = instance.config.body) == null ? void 0 : _k2.modelPath) == null ? void 0 : _l2.includes("posenet")))
instance.models.posenet = load17(instance.config);
if (instance.config.face.enabled && !instance.models.facedetect)
instance.models.facedetect = load5(instance.config);
if (instance.config.face.enabled && ((_m2 = instance.config.face.antispoof) == null ? void 0 : _m2.enabled) && !instance.models.antispoof)
instance.models.antispoof = load4(instance.config);
if (instance.config.face.enabled && ((_n2 = instance.config.face.liveness) == null ? void 0 : _n2.enabled) && !instance.models.liveness)
instance.models.liveness = load14(instance.config);
if (instance.config.face.enabled && ((_o = instance.config.face.description) == null ? void 0 : _o.enabled) && !instance.models.faceres)
instance.models.faceres = load12(instance.config);
if (instance.config.face.enabled && ((_p2 = instance.config.face.emotion) == null ? void 0 : _p2.enabled) && !instance.models.emotion)
instance.models.emotion = load8(instance.config);
if (instance.config.face.enabled && ((_q2 = instance.config.face.iris) == null ? void 0 : _q2.enabled) && !((_r2 = instance.config.face.attention) == null ? void 0 : _r2.enabled) && !instance.models.faceiris)
instance.models.faceiris = load10(instance.config);
if (instance.config.face.enabled && ((_s2 = instance.config.face.mesh) == null ? void 0 : _s2.enabled) && !instance.models.facemesh)
instance.models.facemesh = load11(instance.config);
if (instance.config.face.enabled && ((_t2 = instance.config.face["gear"]) == null ? void 0 : _t2.enabled) && !instance.models.gear)
instance.models.gear = load(instance.config);
if (instance.config.face.enabled && ((_u2 = instance.config.face["ssrnet"]) == null ? void 0 : _u2.enabled) && !instance.models.ssrnetage)
instance.models.ssrnetage = load2(instance.config);
if (instance.config.face.enabled && ((_v2 = instance.config.face["ssrnet"]) == null ? void 0 : _v2.enabled) && !instance.models.ssrnetgender)
instance.models.ssrnetgender = load3(instance.config);
if (instance.config.face.enabled && ((_w2 = instance.config.face["mobilefacenet"]) == null ? void 0 : _w2.enabled) && !instance.models.mobilefacenet)
instance.models.mobilefacenet = load9(instance.config);
if (instance.config.hand.enabled && !instance.models.handtrack && ((_y2 = (_x2 = instance.config.hand.detector) == null ? void 0 : _x2.modelPath) == null ? void 0 : _y2.includes("handtrack")))
instance.models.handtrack = loadDetect2(instance.config);
if (instance.config.hand.enabled && instance.config.hand.landmarks && !instance.models.handskeleton && ((_A2 = (_z2 = instance.config.hand.detector) == null ? void 0 : _z2.modelPath) == null ? void 0 : _A2.includes("handtrack")))
instance.models.handskeleton = loadSkeleton(instance.config);
if (instance.config.object.enabled && !instance.models.centernet && ((_C2 = (_B2 = instance.config.object) == null ? void 0 : _B2.modelPath) == null ? void 0 : _C2.includes("centernet")))
instance.models.centernet = load6(instance.config);
if (instance.config.object.enabled && !instance.models.nanodet && ((_E2 = (_D2 = instance.config.object) == null ? void 0 : _D2.modelPath) == null ? void 0 : _E2.includes("nanodet")))
instance.models.nanodet = load16(instance.config);
if (instance.config.segmentation.enabled && !instance.models.segmentation)
instance.models.segmentation = load18(instance.config);
for await (const model18 of Object.keys(instance.models)) {
if (instance.models[model18] && typeof instance.models[model18] !== "undefined")
instance.models[model18] = await instance.models[model18];
}
}
async function validate2(instance) {
const simpleOps = ["const", "placeholder", "noop", "pad", "squeeze", "add", "sub", "mul", "div"];
for (const defined of Object.keys(instance.models)) {
const model18 = instance.models[defined];
if (!model18)
continue;
const ops = [];
const executor = model18 == null ? void 0 : model18.executor;
if (executor && executor.graph.nodes) {
for (const kernel of Object.values(executor.graph.nodes)) {
const op2 = kernel.op.toLowerCase();
if (!ops.includes(op2))
ops.push(op2);
}
} else {
if (!executor && instance.config.debug)
log("model signature not determined:", defined);
}
const missing = [];
for (const op2 of ops) {
if (!simpleOps.includes(op2) && !instance.env.kernels.includes(op2) && !instance.env.kernels.includes(op2.replace("_", "")) && !instance.env.kernels.includes(op2.replace("native", "")) && !instance.env.kernels.includes(op2.replace("v2", ""))) {
missing.push(op2);
}
}
if (instance.config.debug && missing.length > 0)
log("model validation failed:", defined, missing);
}
}
// src/tfjs/humangl.ts
var config2 = {
name: "humangl",
priority: 999,
canvas: null,
gl: null,
extensions: [],
webGLattr: {
alpha: false,
antialias: false,
premultipliedAlpha: false,
preserveDrawingBuffer: false,
depth: false,
stencil: false,
failIfMajorPerformanceCaveat: false,
desynchronized: true
}
};
function extensions() {
const gl2 = config2.gl;
if (!gl2)
return;
config2.extensions = gl2.getSupportedExtensions();
}
async function register(instance) {
var _a2;
if (instance.config.backend !== "humangl")
return;
if (config2.name in ds().registry && (!config2.gl || !config2.gl.getParameter(config2.gl.VERSION))) {
log("error: humangl backend invalid context");
reset(instance);
}
if (!Vpe(config2.name)) {
try {
config2.canvas = await canvas(100, 100);
} catch (err) {
log("error: cannot create canvas:", err);
return;
}
try {
config2.gl = (_a2 = config2.canvas) == null ? void 0 : _a2.getContext("webgl2", config2.webGLattr);
const glv2 = config2.gl.getParameter(config2.gl.VERSION).includes("2.0");
if (!glv2) {
log("override: using fallback webgl backend as webgl 2.0 is not detected");
instance.config.backend = "webgl";
return;
}
if (config2.canvas) {
config2.canvas.addEventListener("webglcontextlost", async (e) => {
log("error: humangl:", e.type);
log("possible browser memory leak using webgl or conflict with multiple backend registrations");
instance.emit("error");
throw new Error("backend error: webgl context lost");
});
config2.canvas.addEventListener("webglcontextrestored", (e) => {
log("error: humangl context restored:", e);
});
config2.canvas.addEventListener("webglcontextcreationerror", (e) => {
log("error: humangl context create:", e);
});
}
} catch (err) {
log("error: cannot get WebGL context:", err);
return;
}
try {
sK(2, config2.gl);
} catch (err) {
log("error: cannot set WebGL context:", err);
return;
}
try {
const ctx = new am(config2.gl);
xp(config2.name, () => new n2(ctx), config2.priority);
} catch (err) {
log("error: cannot register WebGL backend:", err);
return;
}
try {
const kernels = cm("webgl");
kernels.forEach((kernelConfig) => {
const newKernelConfig = { ...kernelConfig, backendName: config2.name };
Ol(newKernelConfig);
});
} catch (err) {
log("error: cannot update WebGL backend registration:", err);
return;
}
const current = $A().getGPGPUContext ? $A().getGPGPUContext().gl : null;
if (current) {
log(`humangl webgl version:${current.getParameter(current.VERSION)} renderer:${current.getParameter(current.RENDERER)}`);
} else {
log("error: no current gl context:", current, config2.gl);
return;
}
try {
fk.set("WEBGL_VERSION", 2);
} catch (err) {
log("error: cannot set WebGL backend flags:", err);
return;
}
extensions();
log("backend registered:", config2.name);
}
}
// src/tfjs/backend.ts
function registerCustomOps() {
if (!env.kernels.includes("mod")) {
const kernelMod = {
kernelName: "Mod",
backendName: Mpe(),
kernelFunc: (op2) => q(() => ge(op2.inputs.a, V(xe(op2.inputs.a, op2.inputs.b), op2.inputs.b)))
};
Ol(kernelMod);
env.kernels.push("mod");
}
if (!env.kernels.includes("floormod")) {
const kernelMod = {
kernelName: "FloorMod",
backendName: Mpe(),
kernelFunc: (op2) => q(() => uS(op2.inputs.a / op2.inputs.b) * op2.inputs.b + XD(op2.inputs.a, op2.inputs.b))
};
Ol(kernelMod);
env.kernels.push("floormod");
}
}
async function check(instance, force = false) {
instance.state = "backend";
if (force || env.initial || instance.config.backend && instance.config.backend.length > 0 && Mpe() !== instance.config.backend) {
const timeStamp = now();
if (instance.config.backend && instance.config.backend.length > 0) {
if (typeof window === "undefined" && typeof WorkerGlobalScope !== "undefined" && instance.config.debug) {
if (instance.config.debug)
log("running inside web worker");
}
if (env.browser && instance.config.backend === "tensorflow") {
if (instance.config.debug)
log("override: backend set to tensorflow while running in browser");
instance.config.backend = "humangl";
}
if (env.node && (instance.config.backend === "webgl" || instance.config.backend === "humangl")) {
if (instance.config.debug)
log(`override: backend set to ${instance.config.backend} while running in nodejs`);
instance.config.backend = "tensorflow";
}
if (env.browser && instance.config.backend === "webgpu") {
if (typeof navigator === "undefined" || typeof navigator["gpu"] === "undefined") {
log("override: backend set to webgpu but browser does not support webgpu");
instance.config.backend = "humangl";
} else {
const adapter = await navigator["gpu"].requestAdapter();
if (instance.config.debug)
log("enumerated webgpu adapter:", adapter);
if (!adapter) {
log("override: backend set to webgpu but browser reports no available gpu");
instance.config.backend = "humangl";
} else {
const adapterInfo = "requestAdapterInfo" in adapter ? await adapter.requestAdapterInfo() : void 0;
log("webgpu adapter info:", adapterInfo);
}
}
}
if (instance.config.backend === "humangl")
await register(instance);
const available = Object.keys(ds().registryFactory);
if (instance.config.debug)
log("available backends:", available);
if (!available.includes(instance.config.backend)) {
log(`error: backend ${instance.config.backend} not found in registry`);
instance.config.backend = env.node ? "tensorflow" : "webgl";
if (instance.config.debug)
log(`override: setting backend ${instance.config.backend}`);
}
if (instance.config.debug)
log("setting backend:", instance.config.backend);
if (instance.config.backend === "wasm") {
try {
K().set("CANVAS2D_WILL_READ_FREQUENTLY", true);
} catch (e) {
}
if (instance.config.debug)
log("wasm path:", instance.config.wasmPath);
if (typeof (tfjs_esm_exports == null ? void 0 : tfjs_esm_exports.setWasmPaths) !== "undefined")
await Bhe(instance.config.wasmPath, instance.config.wasmPlatformFetch);
else
throw new Error("backend error: attempting to use wasm backend but wasm path is not set");
const simd = await K().getAsync("WASM_HAS_SIMD_SUPPORT");
const mt2 = await K().getAsync("WASM_HAS_MULTITHREAD_SUPPORT");
if (instance.config.debug)
log(`wasm execution: ${simd ? "SIMD" : "no SIMD"} ${mt2 ? "multithreaded" : "singlethreaded"}`);
if (instance.config.debug && !simd)
log("warning: wasm simd support is not enabled");
}
try {
await zpe(instance.config.backend);
await Lpe();
init();
} catch (err) {
log("error: cannot set backend:", instance.config.backend, err);
return false;
}
}
if (Mpe() === "humangl") {
fk.set("CHECK_COMPUTATION_FOR_ERRORS", false);
fk.set("WEBGL_CPU_FORWARD", true);
fk.set("WEBGL_USE_SHAPES_UNIFORMS", true);
fk.set("CPU_HANDOFF_SIZE_THRESHOLD", 256);
if (typeof instance.config["deallocate"] !== "undefined" && instance.config["deallocate"]) {
log("changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:", true);
fk.set("WEBGL_DELETE_TEXTURE_THRESHOLD", 0);
}
if ($A().getGPGPUContext) {
const gl2 = await $A().getGPGPUContext().gl;
if (instance.config.debug)
log(`gl version:${gl2.getParameter(gl2.VERSION)} renderer:${gl2.getParameter(gl2.RENDERER)}`);
}
}
if (Mpe() === "webgpu") {
}
Epe();
await Lpe();
instance.performance.initBackend = Math.trunc(now() - timeStamp);
instance.config.backend = Mpe();
await env.updateBackend();
registerCustomOps();
}
return true;
}
function fakeOps(kernelNames, config3) {
for (const kernelName of kernelNames) {
const kernelConfig = {
kernelName,
backendName: config3.backend,
kernelFunc: () => {
if (config3.debug)
log("kernelFunc", kernelName, config3.backend);
}
};
Ol(kernelConfig);
}
env.kernels = cm(Mpe()).map((kernel) => kernel.kernelName.toLowerCase());
}
// src/draw/draw.ts
var draw_exports = {};
__export(draw_exports, {
all: () => all,
body: () => body,
canvas: () => canvas2,
face: () => face,
gesture: () => gesture,
hand: () => hand,
object: () => object,
options: () => options3,
person: () => person
});
// src/draw/primitives.ts
var getCanvasContext = (input) => {
if (!input)
log("draw error: invalid canvas");
else if (!input.getContext)
log("draw error: canvas context not defined");
else {
const ctx = input.getContext("2d");
if (!ctx)
log("draw error: cannot get canvas context");
else
return ctx;
}
return null;
};
var rad2deg = (theta) => Math.round(theta * 180 / Math.PI);
var colorDepth = (z10, opt2) => {
if (!opt2.useDepth || typeof z10 === "undefined")
return opt2.color;
const rgb2 = Uint8ClampedArray.from([127 + 2 * z10, 127 - 2 * z10, 255]);
const color = `rgba(${rgb2[0]}, ${rgb2[1]}, ${rgb2[2]}, ${opt2.alpha})`;
return color;
};
function point(ctx, x, y, z10, localOptions) {
ctx.fillStyle = colorDepth(z10, localOptions);
ctx.beginPath();
ctx.arc(x, y, localOptions.pointSize, 0, 2 * Math.PI);
ctx.fill();
}
function rect(ctx, x, y, width, height, localOptions) {
ctx.beginPath();
ctx.lineWidth = localOptions.lineWidth;
if (localOptions.useCurves) {
const cx = (x + x + width) / 2;
const cy2 = (y + y + height) / 2;
ctx.ellipse(cx, cy2, width / 2, height / 2, 0, 0, 2 * Math.PI);
} else {
ctx.moveTo(x + localOptions.roundRect, y);
ctx.lineTo(x + width - localOptions.roundRect, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + localOptions.roundRect);
ctx.lineTo(x + width, y + height - localOptions.roundRect);
ctx.quadraticCurveTo(x + width, y + height, x + width - localOptions.roundRect, y + height);
ctx.lineTo(x + localOptions.roundRect, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - localOptions.roundRect);
ctx.lineTo(x, y + localOptions.roundRect);
ctx.quadraticCurveTo(x, y, x + localOptions.roundRect, y);
ctx.closePath();
}
ctx.stroke();
}
function lines(ctx, points, localOptions) {
if (points.length < 2)
return;
ctx.beginPath();
ctx.moveTo(points[0][0], points[0][1]);
for (const pt2 of points) {
ctx.strokeStyle = colorDepth(pt2[2], localOptions);
ctx.lineTo(Math.trunc(pt2[0]), Math.trunc(pt2[1]));
}
ctx.stroke();
if (localOptions.fillPolygons) {
ctx.closePath();
ctx.fill();
}
}
function curves(ctx, points, localOptions) {
if (points.length < 2)
return;
ctx.lineWidth = localOptions.lineWidth;
if (!localOptions.useCurves || points.length <= 2) {
lines(ctx, points, localOptions);
return;
}
ctx.moveTo(points[0][0], points[0][1]);
for (let i = 0; i < points.length - 2; i++) {
const xc = (points[i][0] + points[i + 1][0]) / 2;
const yc = (points[i][1] + points[i + 1][1]) / 2;
ctx.quadraticCurveTo(points[i][0], points[i][1], xc, yc);
}
ctx.quadraticCurveTo(points[points.length - 2][0], points[points.length - 2][1], points[points.length - 1][0], points[points.length - 1][1]);
ctx.stroke();
if (localOptions.fillPolygons) {
ctx.closePath();
ctx.fill();
}
}
function arrow(ctx, from, to2, radius = 5) {
let angle;
let x;
let y;
ctx.beginPath();
ctx.moveTo(from[0], from[1]);
ctx.lineTo(to2[0], to2[1]);
angle = Math.atan2(to2[1] - from[1], to2[0] - from[0]);
x = radius * Math.cos(angle) + to2[0];
y = radius * Math.sin(angle) + to2[1];
ctx.moveTo(x, y);
angle += 1 / 3 * (2 * Math.PI);
x = radius * Math.cos(angle) + to2[0];
y = radius * Math.sin(angle) + to2[1];
ctx.lineTo(x, y);
angle += 1 / 3 * (2 * Math.PI);
x = radius * Math.cos(angle) + to2[0];
y = radius * Math.sin(angle) + to2[1];
ctx.lineTo(x, y);
ctx.closePath();
ctx.stroke();
ctx.fill();
}
// src/draw/options.ts
var options3 = {
color: "rgba(173, 216, 230, 0.6)",
labelColor: "rgba(173, 216, 230, 1)",
shadowColor: "black",
alpha: 0.5,
font: 'small-caps 16px "Segoe UI"',
lineHeight: 18,
lineWidth: 4,
pointSize: 2,
roundRect: 8,
drawPoints: false,
drawLabels: true,
drawBoxes: true,
drawAttention: true,
drawGestures: true,
drawPolygons: true,
drawGaze: true,
fillPolygons: false,
useDepth: true,
useCurves: false
};
// src/draw/face.ts
var opt;
function drawLabels(f, ctx) {
if (opt.drawLabels) {
const labels2 = [];
labels2.push(`face: ${Math.trunc(100 * f.score)}%`);
if (f.genderScore)
labels2.push(`${f.gender || ""} ${Math.trunc(100 * f.genderScore)}%`);
if (f.age)
labels2.push(`age: ${f.age || ""}`);
if (f.iris)
labels2.push(`distance: ${f.iris}`);
if (f.real)
labels2.push(`real: ${Math.trunc(100 * f.real)}%`);
if (f.live)
labels2.push(`live: ${Math.trunc(100 * f.live)}%`);
if (f.emotion && f.emotion.length > 0) {
const emotion = f.emotion.map((a) => `${Math.trunc(100 * a.score)}% ${a.emotion}`);
if (emotion.length > 3)
emotion.length = 3;
labels2.push(emotion.join(" "));
}
if (f.rotation && f.rotation.angle && f.rotation.gaze) {
if (f.rotation.angle.roll)
labels2.push(`roll: ${rad2deg(f.rotation.angle.roll)}\xB0 yaw:${rad2deg(f.rotation.angle.yaw)}\xB0 pitch:${rad2deg(f.rotation.angle.pitch)}\xB0`);
if (f.rotation.gaze.bearing)
labels2.push(`gaze: ${rad2deg(f.rotation.gaze.bearing)}\xB0`);
}
if (labels2.length === 0)
labels2.push("face");
ctx.fillStyle = opt.color;
for (let i = labels2.length - 1; i >= 0; i--) {
const x = Math.max(f.box[0], 0);
const y = i * opt.lineHeight + f.box[1];
if (opt.shadowColor && opt.shadowColor !== "") {
ctx.fillStyle = opt.shadowColor;
ctx.fillText(labels2[i], x + 5, y + 16);
}
ctx.fillStyle = opt.labelColor;
ctx.fillText(labels2[i], x + 4, y + 15);
}
}
}
function drawIrisElipse(f, ctx) {
if (f.annotations && f.annotations["leftEyeIris"] && f.annotations["leftEyeIris"][0]) {
ctx.strokeStyle = opt.useDepth ? "rgba(255, 200, 255, 0.3)" : opt.color;
ctx.beginPath();
const sizeX = Math.abs(f.annotations["leftEyeIris"][3][0] - f.annotations["leftEyeIris"][1][0]) / 2;
const sizeY = Math.abs(f.annotations["leftEyeIris"][4][1] - f.annotations["leftEyeIris"][2][1]) / 2;
ctx.ellipse(f.annotations["leftEyeIris"][0][0], f.annotations["leftEyeIris"][0][1], sizeX, sizeY, 0, 0, 2 * Math.PI);
ctx.stroke();
if (opt.fillPolygons) {
ctx.fillStyle = opt.useDepth ? "rgba(255, 255, 200, 0.3)" : opt.color;
ctx.fill();
}
}
if (f.annotations && f.annotations["rightEyeIris"] && f.annotations["rightEyeIris"][0]) {
ctx.strokeStyle = opt.useDepth ? "rgba(255, 200, 255, 0.3)" : opt.color;
ctx.beginPath();
const sizeX = Math.abs(f.annotations["rightEyeIris"][3][0] - f.annotations["rightEyeIris"][1][0]) / 2;
const sizeY = Math.abs(f.annotations["rightEyeIris"][4][1] - f.annotations["rightEyeIris"][2][1]) / 2;
ctx.ellipse(f.annotations["rightEyeIris"][0][0], f.annotations["rightEyeIris"][0][1], sizeX, sizeY, 0, 0, 2 * Math.PI);
ctx.stroke();
if (opt.fillPolygons) {
ctx.fillStyle = opt.useDepth ? "rgba(255, 255, 200, 0.3)" : opt.color;
ctx.fill();
}
}
}
function drawGazeSpheres(f, ctx) {
var _a2;
if (opt.drawGaze && ((_a2 = f.rotation) == null ? void 0 : _a2.angle) && typeof Path2D !== "undefined") {
ctx.strokeStyle = "pink";
const valX = f.box[0] + f.box[2] / 2 - f.box[3] * rad2deg(f.rotation.angle.yaw) / 90;
const valY = f.box[1] + f.box[3] / 2 + f.box[2] * rad2deg(f.rotation.angle.pitch) / 90;
const pathV = new Path2D(`
M ${f.box[0] + f.box[2] / 2} ${f.box[1]}
C
${valX} ${f.box[1]},
${valX} ${f.box[1] + f.box[3]},
${f.box[0] + f.box[2] / 2} ${f.box[1] + f.box[3]}
`);
const pathH = new Path2D(`
M ${f.box[0]} ${f.box[1] + f.box[3] / 2}
C
${f.box[0]} ${valY},
${f.box[0] + f.box[2]} ${valY},
${f.box[0] + f.box[2]} ${f.box[1] + f.box[3] / 2}
`);
ctx.stroke(pathH);
ctx.stroke(pathV);
}
}
function drawGazeArrows(f, ctx) {
var _a2, _b2, _c, _d2;
if (opt.drawGaze && ((_b2 = (_a2 = f.rotation) == null ? void 0 : _a2.gaze) == null ? void 0 : _b2.strength) && ((_d2 = (_c = f.rotation) == null ? void 0 : _c.gaze) == null ? void 0 : _d2.bearing) && f.annotations["leftEyeIris"] && f.annotations["rightEyeIris"] && f.annotations["leftEyeIris"][0] && f.annotations["rightEyeIris"][0]) {
ctx.strokeStyle = "pink";
ctx.fillStyle = "pink";
const leftGaze = [
f.annotations["leftEyeIris"][0][0] + Math.sin(f.rotation.gaze.bearing) * f.rotation.gaze.strength * f.box[3],
f.annotations["leftEyeIris"][0][1] + Math.cos(f.rotation.gaze.bearing) * f.rotation.gaze.strength * f.box[2]
];
arrow(ctx, [f.annotations["leftEyeIris"][0][0], f.annotations["leftEyeIris"][0][1]], [leftGaze[0], leftGaze[1]], 4);
const rightGaze = [
f.annotations["rightEyeIris"][0][0] + Math.sin(f.rotation.gaze.bearing) * f.rotation.gaze.strength * f.box[3],
f.annotations["rightEyeIris"][0][1] + Math.cos(f.rotation.gaze.bearing) * f.rotation.gaze.strength * f.box[2]
];
arrow(ctx, [f.annotations["rightEyeIris"][0][0], f.annotations["rightEyeIris"][0][1]], [rightGaze[0], rightGaze[1]], 4);
}
}
function drawFacePolygons(f, ctx) {
if (opt.drawPolygons && f.mesh.length >= 468) {
ctx.lineWidth = 1;
for (let i = 0; i < TRI468.length / 3; i++) {
const points = [TRI468[i * 3 + 0], TRI468[i * 3 + 1], TRI468[i * 3 + 2]].map((index2) => f.mesh[index2]);
lines(ctx, points, opt);
}
drawIrisElipse(f, ctx);
}
}
function drawFacePoints(f, ctx) {
if (opt.drawPoints && f.mesh.length >= 468) {
for (let i = 0; i < f.mesh.length; i++) {
point(ctx, f.mesh[i][0], f.mesh[i][1], f.mesh[i][2], opt);
if (opt.drawAttention) {
if (LANDMARKS_REFINEMENT_LIPS_CONFIG.includes(i))
point(ctx, f.mesh[i][0], f.mesh[i][1], f.mesh[i][2] + 127, opt);
if (LANDMARKS_REFINEMENT_LEFT_EYE_CONFIG.includes(i))
point(ctx, f.mesh[i][0], f.mesh[i][1], f.mesh[i][2] - 127, opt);
if (LANDMARKS_REFINEMENT_RIGHT_EYE_CONFIG.includes(i))
point(ctx, f.mesh[i][0], f.mesh[i][1], f.mesh[i][2] - 127, opt);
}
}
}
}
function drawFaceBoxes(f, ctx) {
if (opt.drawBoxes) {
rect(ctx, f.box[0], f.box[1], f.box[2], f.box[3], opt);
}
}
async function face(inCanvas2, result, drawOptions) {
opt = mergeDeep(options3, drawOptions);
if (!result || !inCanvas2)
return;
const ctx = getCanvasContext(inCanvas2);
if (!ctx)
return;
ctx.font = opt.font;
ctx.strokeStyle = opt.color;
ctx.fillStyle = opt.color;
for (const f of result) {
drawFaceBoxes(f, ctx);
drawLabels(f, ctx);
if (f.mesh && f.mesh.length > 0) {
drawFacePoints(f, ctx);
drawFacePolygons(f, ctx);
drawGazeSpheres(f, ctx);
drawGazeArrows(f, ctx);
}
}
}
// src/draw/body.ts
async function body(inCanvas2, result, drawOptions) {
var _a2;
const localOptions = mergeDeep(options3, drawOptions);
if (!result || !inCanvas2)
return;
const ctx = getCanvasContext(inCanvas2);
if (!ctx)
return;
ctx.lineJoin = "round";
for (let i = 0; i < result.length; i++) {
ctx.strokeStyle = localOptions.color;
ctx.fillStyle = localOptions.color;
ctx.lineWidth = localOptions.lineWidth;
ctx.font = localOptions.font;
if (localOptions.drawBoxes && result[i].box && ((_a2 = result[i].box) == null ? void 0 : _a2.length) === 4) {
rect(ctx, result[i].box[0], result[i].box[1], result[i].box[2], result[i].box[3], localOptions);
if (localOptions.drawLabels) {
if (localOptions.shadowColor && localOptions.shadowColor !== "") {
ctx.fillStyle = localOptions.shadowColor;
ctx.fillText(`body ${100 * result[i].score}%`, result[i].box[0] + 3, 1 + result[i].box[1] + localOptions.lineHeight, result[i].box[2]);
}
ctx.fillStyle = localOptions.labelColor;
ctx.fillText(`body ${100 * result[i].score}%`, result[i].box[0] + 2, 0 + result[i].box[1] + localOptions.lineHeight, result[i].box[2]);
}
}
if (localOptions.drawPoints && result[i].keypoints) {
for (let pt2 = 0; pt2 < result[i].keypoints.length; pt2++) {
if (!result[i].keypoints[pt2].score || result[i].keypoints[pt2].score === 0)
continue;
ctx.fillStyle = colorDepth(result[i].keypoints[pt2].position[2], localOptions);
point(ctx, result[i].keypoints[pt2].position[0], result[i].keypoints[pt2].position[1], 0, localOptions);
}
}
if (localOptions.drawLabels && result[i].keypoints) {
ctx.font = localOptions.font;
for (const pt2 of result[i].keypoints) {
if (!pt2.score || pt2.score === 0)
continue;
ctx.fillStyle = colorDepth(pt2.position[2], localOptions);
ctx.fillText(`${pt2.part} ${Math.trunc(100 * pt2.score)}%`, pt2.position[0] + 4, pt2.position[1] + 4);
}
}
if (localOptions.drawPolygons && result[i].keypoints && result[i].annotations) {
for (const part of Object.values(result[i].annotations)) {
for (const connected4 of part)
curves(ctx, connected4, localOptions);
}
}
}
}
// src/draw/hand.ts
async function hand(inCanvas2, result, drawOptions) {
const localOptions = mergeDeep(options3, drawOptions);
if (!result || !inCanvas2)
return;
const ctx = getCanvasContext(inCanvas2);
if (!ctx)
return;
ctx.lineJoin = "round";
ctx.font = localOptions.font;
for (const h of result) {
if (localOptions.drawBoxes) {
ctx.strokeStyle = localOptions.color;
ctx.fillStyle = localOptions.color;
rect(ctx, h.box[0], h.box[1], h.box[2], h.box[3], localOptions);
if (localOptions.drawLabels) {
if (localOptions.shadowColor && localOptions.shadowColor !== "") {
ctx.fillStyle = localOptions.shadowColor;
ctx.fillText(`hand:${Math.trunc(100 * h.score)}%`, h.box[0] + 3, 1 + h.box[1] + localOptions.lineHeight, h.box[2]);
}
ctx.fillStyle = localOptions.labelColor;
ctx.fillText(`hand:${Math.trunc(100 * h.score)}%`, h.box[0] + 2, 0 + h.box[1] + localOptions.lineHeight, h.box[2]);
}
ctx.stroke();
}
if (localOptions.drawPoints) {
if (h.keypoints && h.keypoints.length > 0) {
for (const pt2 of h.keypoints) {
ctx.fillStyle = colorDepth(pt2[2], localOptions);
point(ctx, pt2[0], pt2[1], 0, localOptions);
}
}
}
if (localOptions.drawLabels && h.annotations) {
const addHandLabel = (part, title) => {
if (!part || part.length === 0 || !part[0])
return;
const z10 = part[part.length - 1][2] || -256;
ctx.fillStyle = colorDepth(z10, localOptions);
ctx.fillText(title, part[part.length - 1][0] + 4, part[part.length - 1][1] + 4);
};
ctx.font = localOptions.font;
addHandLabel(h.annotations["index"], "index");
addHandLabel(h.annotations["middle"], "middle");
addHandLabel(h.annotations["ring"], "ring");
addHandLabel(h.annotations["pinky"], "pinky");
addHandLabel(h.annotations["thumb"], "thumb");
addHandLabel(h.annotations["palm"], "palm");
}
if (localOptions.drawPolygons && h.annotations) {
const addHandLine = (part) => {
if (!part || part.length === 0 || !part[0])
return;
for (let i = 0; i < part.length; i++) {
ctx.beginPath();
const z10 = part[i][2] || 0;
ctx.strokeStyle = colorDepth(i * z10, localOptions);
ctx.moveTo(part[i > 0 ? i - 1 : 0][0], part[i > 0 ? i - 1 : 0][1]);
ctx.lineTo(part[i][0], part[i][1]);
ctx.stroke();
}
};
ctx.lineWidth = localOptions.lineWidth;
addHandLine(h.annotations["index"]);
addHandLine(h.annotations["middle"]);
addHandLine(h.annotations["ring"]);
addHandLine(h.annotations["pinky"]);
addHandLine(h.annotations["thumb"]);
}
}
}
// src/draw/object.ts
async function object(inCanvas2, result, drawOptions) {
const localOptions = mergeDeep(options3, drawOptions);
if (!result || !inCanvas2)
return;
const ctx = getCanvasContext(inCanvas2);
if (!ctx)
return;
ctx.lineJoin = "round";
ctx.font = localOptions.font;
for (const h of result) {
if (localOptions.drawBoxes) {
ctx.strokeStyle = localOptions.color;
ctx.fillStyle = localOptions.color;
rect(ctx, h.box[0], h.box[1], h.box[2], h.box[3], localOptions);
if (localOptions.drawLabels) {
const label = `${h.label} ${Math.round(100 * h.score)}%`;
if (localOptions.shadowColor && localOptions.shadowColor !== "") {
ctx.fillStyle = localOptions.shadowColor;
ctx.fillText(label, h.box[0] + 3, 1 + h.box[1] + localOptions.lineHeight, h.box[2]);
}
ctx.fillStyle = localOptions.labelColor;
ctx.fillText(label, h.box[0] + 2, 0 + h.box[1] + localOptions.lineHeight, h.box[2]);
}
ctx.stroke();
}
}
}
// src/draw/gesture.ts
async function gesture(inCanvas2, result, drawOptions) {
const localOptions = mergeDeep(options3, drawOptions);
if (!result || !inCanvas2)
return;
if (localOptions.drawGestures) {
const ctx = getCanvasContext(inCanvas2);
if (!ctx)
return;
ctx.font = localOptions.font;
ctx.fillStyle = localOptions.color;
let i = 1;
for (let j = 0; j < result.length; j++) {
let where = [];
let what = [];
[where, what] = Object.entries(result[j]);
if (what.length > 1 && what[1].length > 0) {
const who = where[1] > 0 ? `#${where[1]}` : "";
const label = `${where[0]} ${who}: ${what[1]}`;
if (localOptions.shadowColor && localOptions.shadowColor !== "") {
ctx.fillStyle = localOptions.shadowColor;
ctx.fillText(label, 8, 2 + i * localOptions.lineHeight);
}
ctx.fillStyle = localOptions.labelColor;
ctx.fillText(label, 6, 0 + i * localOptions.lineHeight);
i += 1;
}
}
}
}
// src/draw/draw.ts
var drawTime = 0;
async function person(inCanvas2, result, drawOptions) {
const localOptions = mergeDeep(options3, drawOptions);
if (!result || !inCanvas2)
return;
const ctx = getCanvasContext(inCanvas2);
if (!ctx)
return;
ctx.lineJoin = "round";
ctx.font = localOptions.font;
for (let i = 0; i < result.length; i++) {
if (localOptions.drawBoxes) {
ctx.strokeStyle = localOptions.color;
ctx.fillStyle = localOptions.color;
rect(ctx, result[i].box[0], result[i].box[1], result[i].box[2], result[i].box[3], localOptions);
if (localOptions.drawLabels) {
const label = `person #${i}`;
if (localOptions.shadowColor && localOptions.shadowColor !== "") {
ctx.fillStyle = localOptions.shadowColor;
ctx.fillText(label, result[i].box[0] + 3, 1 + result[i].box[1] + localOptions.lineHeight, result[i].box[2]);
}
ctx.fillStyle = localOptions.labelColor;
ctx.fillText(label, result[i].box[0] + 2, 0 + result[i].box[1] + localOptions.lineHeight, result[i].box[2]);
}
ctx.stroke();
}
}
}
async function canvas2(input, output) {
if (!input || !output)
return;
const ctx = getCanvasContext(output);
if (!ctx)
return;
ctx.drawImage(input, 0, 0);
}
async function all(inCanvas2, result, drawOptions) {
if (!result || !result.performance || !result || !inCanvas2)
return null;
const timeStamp = now();
const localOptions = mergeDeep(options3, drawOptions);
const promise = Promise.all([
face(inCanvas2, result.face, localOptions),
body(inCanvas2, result.body, localOptions),
hand(inCanvas2, result.hand, localOptions),
object(inCanvas2, result.object, localOptions),
gesture(inCanvas2, result.gesture, localOptions)
]);
drawTime = env.perfadd ? drawTime + Math.round(now() - timeStamp) : Math.round(now() - timeStamp);
result.performance.draw = drawTime;
return promise;
}
// src/face/mask.ts
var expandFact = 0.1;
var alpha = 0.5;
function insidePoly(x, y, polygon) {
let inside = false;
let j = polygon.length - 1;
for (let i = 0; i < polygon.length; j = i++) {
if (polygon[i].y > y !== polygon[j].y > y && x < (polygon[j].x - polygon[i].x) * (y - polygon[i].y) / (polygon[j].y - polygon[i].y) + polygon[i].x)
inside = !inside;
}
return inside;
}
async function mask(face4) {
if (!face4.tensor)
return face4.tensor;
if (!face4.mesh || face4.mesh.length < 100)
return face4.tensor;
const width = face4.tensor.shape[2] || 0;
const height = face4.tensor.shape[1] || 0;
const buffer = await face4.tensor.buffer();
let silhouette = [];
for (const pt2 of meshAnnotations.silhouette)
silhouette.push({ x: (face4.mesh[pt2][0] - face4.box[0]) / face4.box[2], y: (face4.mesh[pt2][1] - face4.box[1]) / face4.box[3] });
if (expandFact && expandFact > 0)
silhouette = silhouette.map((pt2) => ({ x: pt2.x > 0.5 ? pt2.x + expandFact : pt2.x - expandFact, y: pt2.y > 0.5 ? pt2.y + expandFact : pt2.y - expandFact }));
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const inside = insidePoly(x / width, y / width, silhouette);
if (!inside) {
buffer.set(alpha * buffer.get(0, y, x, 0), 0, y, x, 0);
buffer.set(alpha * buffer.get(0, y, x, 1), 0, y, x, 1);
buffer.set(alpha * buffer.get(0, y, x, 2), 0, y, x, 2);
}
}
}
const output = buffer.toTensor();
De(buffer);
return output;
}
// src/face/angles.ts
var calculateGaze = (face4) => {
const radians = (pt1, pt2) => Math.atan2(pt1[1] - pt2[1], pt1[0] - pt2[0]);
if (!face4.annotations["rightEyeIris"] || !face4.annotations["leftEyeIris"])
return { bearing: 0, strength: 0 };
const offsetIris = [0, -0.1];
const eyeRatio = 1;
const left = (face4.mesh[33][2] || 0) > (face4.mesh[263][2] || 0);
const irisCenter = left ? face4.mesh[473] : face4.mesh[468];
const eyeCenter = left ? [(face4.mesh[133][0] + face4.mesh[33][0]) / 2, (face4.mesh[133][1] + face4.mesh[33][1]) / 2] : [(face4.mesh[263][0] + face4.mesh[362][0]) / 2, (face4.mesh[263][1] + face4.mesh[362][1]) / 2];
const eyeSize = left ? [face4.mesh[133][0] - face4.mesh[33][0], face4.mesh[23][1] - face4.mesh[27][1]] : [face4.mesh[263][0] - face4.mesh[362][0], face4.mesh[253][1] - face4.mesh[257][1]];
const eyeDiff = [
(eyeCenter[0] - irisCenter[0]) / eyeSize[0] - offsetIris[0],
eyeRatio * (irisCenter[1] - eyeCenter[1]) / eyeSize[1] - offsetIris[1]
];
let strength = Math.sqrt(eyeDiff[0] * eyeDiff[0] + eyeDiff[1] * eyeDiff[1]);
strength = Math.min(strength, face4.boxRaw[2] / 2, face4.boxRaw[3] / 2);
const bearing = (radians([0, 0], eyeDiff) + Math.PI / 2) % Math.PI;
return { bearing, strength };
};
var calculateFaceAngle = (face4, imageSize) => {
const normalize = (v) => {
const length = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
v[0] /= length;
v[1] /= length;
v[2] /= length;
return v;
};
const subVectors = (a, b) => {
const x = a[0] - b[0];
const y = a[1] - b[1];
const z10 = a[2] - b[2];
return [x, y, z10];
};
const crossVectors = (a, b) => {
const x = a[1] * b[2] - a[2] * b[1];
const y = a[2] * b[0] - a[0] * b[2];
const z10 = a[0] * b[1] - a[1] * b[0];
return [x, y, z10];
};
const rotationMatrixToEulerAngle = (r) => {
const [r00, _r01, _r02, r10, r11, r12, r20, r21, r22] = r;
let thetaX;
let thetaY;
let thetaZ;
if (r10 < 1) {
if (r10 > -1) {
thetaZ = Math.asin(r10);
thetaY = Math.atan2(-r20, r00);
thetaX = Math.atan2(-r12, r11);
} else {
thetaZ = -Math.PI / 2;
thetaY = -Math.atan2(r21, r22);
thetaX = 0;
}
} else {
thetaZ = Math.PI / 2;
thetaY = Math.atan2(r21, r22);
thetaX = 0;
}
if (isNaN(thetaX))
thetaX = 0;
if (isNaN(thetaY))
thetaY = 0;
if (isNaN(thetaZ))
thetaZ = 0;
return { pitch: 2 * -thetaX, yaw: 2 * -thetaY, roll: 2 * -thetaZ };
};
const mesh = face4.meshRaw;
if (!mesh || mesh.length < 300)
return { angle: { pitch: 0, yaw: 0, roll: 0 }, matrix: [1, 0, 0, 0, 1, 0, 0, 0, 1], gaze: { bearing: 0, strength: 0 } };
const size2 = Math.max(face4.boxRaw[2] * imageSize[0], face4.boxRaw[3] * imageSize[1]) / 1.5;
const pts = [mesh[10], mesh[152], mesh[234], mesh[454]].map((pt2) => [pt2[0] * imageSize[0] / size2, pt2[1] * imageSize[1] / size2, pt2[2]]);
const y_axis = normalize(subVectors(pts[1], pts[0]));
let x_axis = normalize(subVectors(pts[3], pts[2]));
const z_axis = normalize(crossVectors(x_axis, y_axis));
x_axis = crossVectors(y_axis, z_axis);
const matrix = [
x_axis[0],
x_axis[1],
x_axis[2],
y_axis[0],
y_axis[1],
y_axis[2],
z_axis[0],
z_axis[1],
z_axis[2]
];
const angle = rotationMatrixToEulerAngle(matrix);
const gaze = mesh.length === 478 ? calculateGaze(face4) : { bearing: 0, strength: 0 };
return { angle, matrix, gaze };
};
// src/face/face.ts
var detectFace = async (instance, input) => {
var _a2, _b2, _c, _d2, _e2, _f, _g2, _h, _i2, _j2, _k2, _l2, _m2, _n2, _o, _p2, _q2, _r2, _s2, _t2, _u2, _v2;
let timeStamp = now();
let ageRes;
let gearRes;
let genderRes;
let emotionRes;
let mobilefacenetRes;
let antispoofRes;
let livenessRes;
let descRes;
const faceRes = [];
instance.state = "run:face";
const faces = await predict10(input, instance.config);
instance.performance.face = env.perfadd ? (instance.performance.face || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
if (!input.shape || input.shape.length !== 4)
return [];
if (!faces)
return [];
for (let i = 0; i < faces.length; i++) {
instance.analyze("Get Face");
if (!faces[i].tensor || faces[i].tensor["isDisposedInternal"]) {
log("Face object is disposed:", faces[i].tensor);
continue;
}
if ((_a2 = instance.config.face.detector) == null ? void 0 : _a2.mask) {
const masked = await mask(faces[i]);
De(faces[i].tensor);
faces[i].tensor = masked;
}
const rotation = faces[i].mesh && faces[i].mesh.length > 200 ? calculateFaceAngle(faces[i], [input.shape[2], input.shape[1]]) : null;
instance.analyze("Start Emotion:");
if (instance.config.async) {
emotionRes = ((_b2 = instance.config.face.emotion) == null ? void 0 : _b2.enabled) ? predict8(faces[i].tensor || ms([]), instance.config, i, faces.length) : [];
} else {
instance.state = "run:emotion";
timeStamp = now();
emotionRes = ((_c = instance.config.face.emotion) == null ? void 0 : _c.enabled) ? await predict8(faces[i].tensor || ms([]), instance.config, i, faces.length) : [];
instance.performance.emotion = env.perfadd ? (instance.performance.emotion || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
}
instance.analyze("End Emotion:");
instance.analyze("Start AntiSpoof:");
if (instance.config.async) {
antispoofRes = ((_d2 = instance.config.face.antispoof) == null ? void 0 : _d2.enabled) ? predict4(faces[i].tensor || ms([]), instance.config, i, faces.length) : 0;
} else {
instance.state = "run:antispoof";
timeStamp = now();
antispoofRes = ((_e2 = instance.config.face.antispoof) == null ? void 0 : _e2.enabled) ? await predict4(faces[i].tensor || ms([]), instance.config, i, faces.length) : 0;
instance.performance.antispoof = env.perfadd ? (instance.performance.antispoof || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
}
instance.analyze("End AntiSpoof:");
instance.analyze("Start Liveness:");
if (instance.config.async) {
livenessRes = ((_f = instance.config.face.liveness) == null ? void 0 : _f.enabled) ? predict14(faces[i].tensor || ms([]), instance.config, i, faces.length) : 0;
} else {
instance.state = "run:liveness";
timeStamp = now();
livenessRes = ((_g2 = instance.config.face.liveness) == null ? void 0 : _g2.enabled) ? await predict14(faces[i].tensor || ms([]), instance.config, i, faces.length) : 0;
instance.performance.liveness = env.perfadd ? (instance.performance.antispoof || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
}
instance.analyze("End Liveness:");
instance.analyze("Start GEAR:");
if (instance.config.async) {
gearRes = ((_h = instance.config.face["gear"]) == null ? void 0 : _h.enabled) ? predict(faces[i].tensor || ms([]), instance.config, i, faces.length) : null;
} else {
instance.state = "run:gear";
timeStamp = now();
gearRes = ((_i2 = instance.config.face["gear"]) == null ? void 0 : _i2.enabled) ? await predict(faces[i].tensor || ms([]), instance.config, i, faces.length) : null;
instance.performance.gear = Math.trunc(now() - timeStamp);
}
instance.analyze("End GEAR:");
instance.analyze("Start SSRNet:");
if (instance.config.async) {
ageRes = ((_j2 = instance.config.face["ssrnet"]) == null ? void 0 : _j2.enabled) ? predict2(faces[i].tensor || ms([]), instance.config, i, faces.length) : null;
genderRes = ((_k2 = instance.config.face["ssrnet"]) == null ? void 0 : _k2.enabled) ? predict3(faces[i].tensor || ms([]), instance.config, i, faces.length) : null;
} else {
instance.state = "run:ssrnet";
timeStamp = now();
ageRes = ((_l2 = instance.config.face["ssrnet"]) == null ? void 0 : _l2.enabled) ? await predict2(faces[i].tensor || ms([]), instance.config, i, faces.length) : null;
genderRes = ((_m2 = instance.config.face["ssrnet"]) == null ? void 0 : _m2.enabled) ? await predict3(faces[i].tensor || ms([]), instance.config, i, faces.length) : null;
instance.performance.ssrnet = Math.trunc(now() - timeStamp);
}
instance.analyze("End SSRNet:");
instance.analyze("Start MobileFaceNet:");
if (instance.config.async) {
mobilefacenetRes = ((_n2 = instance.config.face["mobilefacenet"]) == null ? void 0 : _n2.enabled) ? predict9(faces[i].tensor || ms([]), instance.config, i, faces.length) : null;
} else {
instance.state = "run:mobilefacenet";
timeStamp = now();
mobilefacenetRes = ((_o = instance.config.face["mobilefacenet"]) == null ? void 0 : _o.enabled) ? await predict9(faces[i].tensor || ms([]), instance.config, i, faces.length) : null;
instance.performance.mobilefacenet = Math.trunc(now() - timeStamp);
}
instance.analyze("End MobileFaceNet:");
instance.analyze("Start Description:");
if (instance.config.async) {
descRes = ((_p2 = instance.config.face.description) == null ? void 0 : _p2.enabled) ? predict11(faces[i].tensor || ms([]), instance.config, i, faces.length) : null;
} else {
instance.state = "run:description";
timeStamp = now();
descRes = ((_q2 = instance.config.face.description) == null ? void 0 : _q2.enabled) ? await predict11(faces[i].tensor || ms([]), instance.config, i, faces.length) : null;
instance.performance.description = env.perfadd ? (instance.performance.description || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
}
instance.analyze("End Description:");
if (instance.config.async) {
[ageRes, genderRes, emotionRes, mobilefacenetRes, descRes, gearRes, antispoofRes, livenessRes] = await Promise.all([ageRes, genderRes, emotionRes, mobilefacenetRes, descRes, gearRes, antispoofRes, livenessRes]);
}
instance.analyze("Finish Face:");
if (((_r2 = instance.config.face["ssrnet"]) == null ? void 0 : _r2.enabled) && ageRes && genderRes) {
descRes = {
...descRes,
age: ageRes.age,
gender: genderRes.gender,
genderScore: genderRes.genderScore
};
}
if (((_s2 = instance.config.face["gear"]) == null ? void 0 : _s2.enabled) && gearRes) {
descRes = {
...descRes,
age: gearRes.age,
gender: gearRes.gender,
genderScore: gearRes.genderScore,
race: gearRes.race
};
}
if (((_t2 = instance.config.face["mobilefacenet"]) == null ? void 0 : _t2.enabled) && mobilefacenetRes) {
descRes.descriptor = mobilefacenetRes;
}
if (!((_u2 = instance.config.face.iris) == null ? void 0 : _u2.enabled)) {
}
const irisSize = faces[i].annotations && faces[i].annotations.leftEyeIris && faces[i].annotations.leftEyeIris[0] && faces[i].annotations.rightEyeIris && faces[i].annotations.rightEyeIris[0] && faces[i].annotations.leftEyeIris.length > 0 && faces[i].annotations.rightEyeIris.length > 0 && faces[i].annotations.leftEyeIris[0] !== null && faces[i].annotations.rightEyeIris[0] !== null ? Math.max(Math.abs(faces[i].annotations.leftEyeIris[3][0] - faces[i].annotations.leftEyeIris[1][0]), Math.abs(faces[i].annotations.rightEyeIris[4][1] - faces[i].annotations.rightEyeIris[2][1])) / input.shape[2] : 0;
const tensor = ((_v2 = instance.config.face.detector) == null ? void 0 : _v2.return) ? br(faces[i].tensor) : null;
De(faces[i].tensor);
if (faces[i].tensor)
delete faces[i].tensor;
const res = {
...faces[i],
id: i
};
if (descRes == null ? void 0 : descRes.age)
res.age = descRes.age;
if (descRes == null ? void 0 : descRes.gender)
res.gender = descRes.gender;
if (descRes == null ? void 0 : descRes.genderScore)
res.genderScore = descRes == null ? void 0 : descRes.genderScore;
if (descRes == null ? void 0 : descRes.descriptor)
res.embedding = descRes == null ? void 0 : descRes.descriptor;
if (descRes == null ? void 0 : descRes.race)
res.race = descRes == null ? void 0 : descRes.race;
if (emotionRes)
res.emotion = emotionRes;
if (antispoofRes)
res.real = antispoofRes;
if (livenessRes)
res.live = livenessRes;
if (irisSize && irisSize !== 0)
res.iris = Math.trunc(500 / irisSize / 11.7) / 100;
if (rotation)
res.rotation = rotation;
if (tensor)
res.tensor = tensor;
faceRes.push(res);
instance.analyze("End Face");
}
instance.analyze("End FaceMesh:");
if (instance.config.async) {
if (instance.performance.face)
delete instance.performance.face;
if (instance.performance.age)
delete instance.performance.age;
if (instance.performance.gender)
delete instance.performance.gender;
if (instance.performance.emotion)
delete instance.performance.emotion;
}
return faceRes;
};
// src/gesture/gesture.ts
var body2 = (res) => {
if (!res)
return [];
const gestures = [];
for (let i = 0; i < res.length; i++) {
const leftWrist = res[i].keypoints.find((a) => a.part === "leftWrist");
const rightWrist = res[i].keypoints.find((a) => a.part === "rightWrist");
const nose = res[i].keypoints.find((a) => a.part === "nose");
if (nose && leftWrist && rightWrist && leftWrist.position[1] < nose.position[1] && rightWrist.position[1] < nose.position[1])
gestures.push({ body: i, gesture: "i give up" });
else if (nose && leftWrist && leftWrist.position[1] < nose.position[1])
gestures.push({ body: i, gesture: "raise left hand" });
else if (nose && rightWrist && rightWrist.position[1] < nose.position[1])
gestures.push({ body: i, gesture: "raise right hand" });
const leftShoulder = res[i].keypoints.find((a) => a.part === "leftShoulder");
const rightShoulder = res[i].keypoints.find((a) => a.part === "rightShoulder");
if (leftShoulder && rightShoulder && Math.abs(leftShoulder.positionRaw[1] - rightShoulder.positionRaw[1]) > 0.1) {
gestures.push({ body: i, gesture: `leaning ${leftShoulder.position[1] > rightShoulder.position[1] ? "left" : "right"}` });
}
}
return gestures;
};
var face2 = (res) => {
if (!res)
return [];
const gestures = [];
for (let i = 0; i < res.length; i++) {
if (res[i].mesh && res[i].mesh.length > 450) {
const zDiff = (res[i].mesh[33][2] || 0) - (res[i].mesh[263][2] || 0);
const xDiff = res[i].mesh[33][0] - res[i].mesh[263][0];
if (Math.abs(zDiff / xDiff) <= 0.15)
gestures.push({ face: i, gesture: "facing center" });
else
gestures.push({ face: i, gesture: `facing ${zDiff < 0 ? "left" : "right"}` });
const openLeft = Math.abs(res[i].mesh[374][1] - res[i].mesh[386][1]) / Math.abs(res[i].mesh[443][1] - res[i].mesh[450][1]);
if (openLeft < 0.2)
gestures.push({ face: i, gesture: "blink left eye" });
const openRight = Math.abs(res[i].mesh[145][1] - res[i].mesh[159][1]) / Math.abs(res[i].mesh[223][1] - res[i].mesh[230][1]);
if (openRight < 0.2)
gestures.push({ face: i, gesture: "blink right eye" });
const mouthOpen = Math.min(100, 500 * Math.abs(res[i].mesh[13][1] - res[i].mesh[14][1]) / Math.abs(res[i].mesh[10][1] - res[i].mesh[152][1]));
if (mouthOpen > 10)
gestures.push({ face: i, gesture: `mouth ${Math.trunc(mouthOpen)}% open` });
const chinDepth = res[i].mesh[152][2] || 0;
if (Math.abs(chinDepth) > 10)
gestures.push({ face: i, gesture: `head ${chinDepth < 0 ? "up" : "down"}` });
}
}
return gestures;
};
var iris = (res) => {
if (!res)
return [];
const gestures = [];
for (let i = 0; i < res.length; i++) {
if (!res[i].annotations || !res[i].annotations.leftEyeIris || !res[i].annotations.leftEyeIris[0] || !res[i].annotations.rightEyeIris || !res[i].annotations.rightEyeIris[0])
continue;
const sizeXLeft = res[i].annotations.leftEyeIris[3][0] - res[i].annotations.leftEyeIris[1][0];
const sizeYLeft = res[i].annotations.leftEyeIris[4][1] - res[i].annotations.leftEyeIris[2][1];
const areaLeft = Math.abs(sizeXLeft * sizeYLeft);
const sizeXRight = res[i].annotations.rightEyeIris[3][0] - res[i].annotations.rightEyeIris[1][0];
const sizeYRight = res[i].annotations.rightEyeIris[4][1] - res[i].annotations.rightEyeIris[2][1];
const areaRight = Math.abs(sizeXRight * sizeYRight);
let center = false;
const difference = Math.abs(areaLeft - areaRight) / Math.max(areaLeft, areaRight);
if (difference < 0.25) {
center = true;
gestures.push({ iris: i, gesture: "facing center" });
}
const leftIrisCenterX = Math.abs(res[i].mesh[263][0] - res[i].annotations.leftEyeIris[0][0]) / res[i].box[2];
const rightIrisCenterX = Math.abs(res[i].mesh[33][0] - res[i].annotations.rightEyeIris[0][0]) / res[i].box[2];
if (leftIrisCenterX > 0.06 || rightIrisCenterX > 0.06)
center = false;
if (leftIrisCenterX > rightIrisCenterX) {
if (leftIrisCenterX > 0.05)
gestures.push({ iris: i, gesture: "looking right" });
} else {
if (rightIrisCenterX > 0.05)
gestures.push({ iris: i, gesture: "looking left" });
}
const rightIrisCenterY = Math.abs(res[i].mesh[145][1] - res[i].annotations.rightEyeIris[0][1]) / res[i].box[3];
const leftIrisCenterY = Math.abs(res[i].mesh[374][1] - res[i].annotations.leftEyeIris[0][1]) / res[i].box[3];
if (leftIrisCenterY < 0.01 || rightIrisCenterY < 0.01 || leftIrisCenterY > 0.022 || rightIrisCenterY > 0.022)
center = false;
if (leftIrisCenterY < 0.01 || rightIrisCenterY < 0.01)
gestures.push({ iris: i, gesture: "looking down" });
if (leftIrisCenterY > 0.022 || rightIrisCenterY > 0.022)
gestures.push({ iris: i, gesture: "looking up" });
if (center)
gestures.push({ iris: i, gesture: "looking center" });
}
return gestures;
};
var hand2 = (res) => {
if (!res)
return [];
const gestures = [];
for (let i = 0; i < res.length; i++) {
const fingers = [];
if (res[i]["annotations"]) {
for (const [finger, pos] of Object.entries(res[i]["annotations"])) {
if (finger !== "palmBase" && Array.isArray(pos) && pos[0])
fingers.push({ name: finger.toLowerCase(), position: pos[0] });
}
}
if (fingers && fingers.length > 0) {
const closest = fingers.reduce((best, a) => (best.position[2] || 0) < (a.position[2] || 0) ? best : a);
gestures.push({ hand: i, gesture: `${closest.name} forward` });
const highest = fingers.reduce((best, a) => best.position[1] < a.position[1] ? best : a);
gestures.push({ hand: i, gesture: `${highest.name} up` });
}
if (res[i]["keypoints"]) {
const poses = match(res[i]["keypoints"]);
for (const pose of poses)
gestures.push({ hand: i, gesture: pose.name });
}
}
return gestures;
};
// src/util/interpolate.ts
var bufferedResult = { face: [], body: [], hand: [], gesture: [], object: [], persons: [], performance: {}, timestamp: 0, error: null };
var interpolateTime = 0;
function calc2(newResult, config3) {
var _a2, _b2, _c, _d2, _e2, _f, _g2, _h, _i2, _j2, _k2, _l2, _m2, _n2, _o, _p2, _q2, _r2, _s2, _t2, _u2, _v2, _w2, _x2, _y2, _z2, _A2;
const t02 = now();
if (!newResult)
return { face: [], body: [], hand: [], gesture: [], object: [], persons: [], performance: {}, timestamp: 0, error: null };
const elapsed = Date.now() - newResult.timestamp;
const bufferedFactor = elapsed < 1e3 ? 8 - Math.log(elapsed + 1) : 1;
if (newResult.canvas)
bufferedResult.canvas = newResult.canvas;
if (newResult.error)
bufferedResult.error = newResult.error;
if (!bufferedResult.body || newResult.body.length !== bufferedResult.body.length) {
bufferedResult.body = JSON.parse(JSON.stringify(newResult.body));
} else {
for (let i = 0; i < newResult.body.length; i++) {
const box = newResult.body[i].box.map((newBoxCoord, j) => ((bufferedFactor - 1) * bufferedResult.body[i].box[j] + newBoxCoord) / bufferedFactor);
const boxRaw = newResult.body[i].boxRaw.map((newBoxCoord, j) => ((bufferedFactor - 1) * bufferedResult.body[i].boxRaw[j] + newBoxCoord) / bufferedFactor);
const keypoints = newResult.body[i].keypoints.map((newKpt, j) => {
var _a3, _b3, _c2, _d3, _e3, _f2, _g3, _h2, _i3;
return {
score: newKpt.score,
part: newKpt.part,
position: [
bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (bufferedResult.body[i].keypoints[j].position[0] || 0) + (newKpt.position[0] || 0)) / bufferedFactor : newKpt.position[0],
bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (bufferedResult.body[i].keypoints[j].position[1] || 0) + (newKpt.position[1] || 0)) / bufferedFactor : newKpt.position[1],
bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (bufferedResult.body[i].keypoints[j].position[2] || 0) + (newKpt.position[2] || 0)) / bufferedFactor : newKpt.position[2]
],
positionRaw: [
bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (bufferedResult.body[i].keypoints[j].positionRaw[0] || 0) + (newKpt.positionRaw[0] || 0)) / bufferedFactor : newKpt.positionRaw[0],
bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (bufferedResult.body[i].keypoints[j].positionRaw[1] || 0) + (newKpt.positionRaw[1] || 0)) / bufferedFactor : newKpt.positionRaw[1],
bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (bufferedResult.body[i].keypoints[j].positionRaw[2] || 0) + (newKpt.positionRaw[2] || 0)) / bufferedFactor : newKpt.positionRaw[2]
],
distance: [
bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (((_a3 = bufferedResult.body[i].keypoints[j].distance) == null ? void 0 : _a3[0]) || 0) + (((_b3 = newKpt.distance) == null ? void 0 : _b3[0]) || 0)) / bufferedFactor : (_c2 = newKpt.distance) == null ? void 0 : _c2[0],
bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (((_d3 = bufferedResult.body[i].keypoints[j].distance) == null ? void 0 : _d3[1]) || 0) + (((_e3 = newKpt.distance) == null ? void 0 : _e3[1]) || 0)) / bufferedFactor : (_f2 = newKpt.distance) == null ? void 0 : _f2[1],
bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (((_g3 = bufferedResult.body[i].keypoints[j].distance) == null ? void 0 : _g3[2]) || 0) + (((_h2 = newKpt.distance) == null ? void 0 : _h2[2]) || 0)) / bufferedFactor : (_i3 = newKpt.distance) == null ? void 0 : _i3[2]
]
};
});
const annotations2 = {};
let coords = { connected: {} };
if ((_b2 = (_a2 = config3.body) == null ? void 0 : _a2.modelPath) == null ? void 0 : _b2.includes("efficientpose"))
coords = efficientposecoords_exports;
else if ((_d2 = (_c = config3.body) == null ? void 0 : _c.modelPath) == null ? void 0 : _d2.includes("blazepose"))
coords = blazeposecoords_exports;
else if ((_f = (_e2 = config3.body) == null ? void 0 : _e2.modelPath) == null ? void 0 : _f.includes("movenet"))
coords = movenetcoords_exports;
for (const [name, indexes] of Object.entries(coords.connected)) {
const pt2 = [];
for (let j = 0; j < indexes.length - 1; j++) {
const pt0 = keypoints.find((kp2) => kp2.part === indexes[j]);
const pt1 = keypoints.find((kp2) => kp2.part === indexes[j + 1]);
if (pt0 && pt1)
pt2.push([pt0.position, pt1.position]);
}
annotations2[name] = pt2;
}
bufferedResult.body[i] = { ...newResult.body[i], box, boxRaw, keypoints, annotations: annotations2 };
}
}
if (!bufferedResult.hand || newResult.hand.length !== bufferedResult.hand.length) {
bufferedResult.hand = JSON.parse(JSON.stringify(newResult.hand));
} else {
for (let i = 0; i < newResult.hand.length; i++) {
const box = newResult.hand[i].box.map((b, j) => ((bufferedFactor - 1) * bufferedResult.hand[i].box[j] + b) / bufferedFactor);
const boxRaw = newResult.hand[i].boxRaw.map((b, j) => ((bufferedFactor - 1) * bufferedResult.hand[i].boxRaw[j] + b) / bufferedFactor);
if (bufferedResult.hand[i].keypoints.length !== newResult.hand[i].keypoints.length)
bufferedResult.hand[i].keypoints = newResult.hand[i].keypoints;
const keypoints = newResult.hand[i].keypoints && newResult.hand[i].keypoints.length > 0 ? newResult.hand[i].keypoints.map((landmark, j) => landmark.map((coord, k) => ((bufferedFactor - 1) * (bufferedResult.hand[i].keypoints[j][k] || 1) + (coord || 0)) / bufferedFactor)) : [];
let annotations2 = {};
if (Object.keys(bufferedResult.hand[i].annotations).length !== Object.keys(newResult.hand[i].annotations).length) {
bufferedResult.hand[i].annotations = newResult.hand[i].annotations;
annotations2 = bufferedResult.hand[i].annotations;
} else if (newResult.hand[i].annotations) {
for (const key of Object.keys(newResult.hand[i].annotations)) {
annotations2[key] = newResult.hand[i].annotations[key] && newResult.hand[i].annotations[key][0] ? newResult.hand[i].annotations[key].map((val, j) => val.map((coord, k) => ((bufferedFactor - 1) * bufferedResult.hand[i].annotations[key][j][k] + coord) / bufferedFactor)) : null;
}
}
bufferedResult.hand[i] = { ...newResult.hand[i], box, boxRaw, keypoints, annotations: annotations2 };
}
}
if (!bufferedResult.face || newResult.face.length !== bufferedResult.face.length) {
bufferedResult.face = JSON.parse(JSON.stringify(newResult.face));
} else {
for (let i = 0; i < newResult.face.length; i++) {
const box = newResult.face[i].box.map((b, j) => ((bufferedFactor - 1) * bufferedResult.face[i].box[j] + b) / bufferedFactor);
const boxRaw = newResult.face[i].boxRaw.map((b, j) => ((bufferedFactor - 1) * bufferedResult.face[i].boxRaw[j] + b) / bufferedFactor);
if (newResult.face[i].rotation) {
const rotation = { matrix: [0, 0, 0, 0, 0, 0, 0, 0, 0], angle: { roll: 0, yaw: 0, pitch: 0 }, gaze: { bearing: 0, strength: 0 } };
rotation.matrix = (_g2 = newResult.face[i].rotation) == null ? void 0 : _g2.matrix;
rotation.angle = {
roll: ((bufferedFactor - 1) * (((_i2 = (_h = bufferedResult.face[i].rotation) == null ? void 0 : _h.angle) == null ? void 0 : _i2.roll) || 0) + (((_k2 = (_j2 = newResult.face[i].rotation) == null ? void 0 : _j2.angle) == null ? void 0 : _k2.roll) || 0)) / bufferedFactor,
yaw: ((bufferedFactor - 1) * (((_m2 = (_l2 = bufferedResult.face[i].rotation) == null ? void 0 : _l2.angle) == null ? void 0 : _m2.yaw) || 0) + (((_o = (_n2 = newResult.face[i].rotation) == null ? void 0 : _n2.angle) == null ? void 0 : _o.yaw) || 0)) / bufferedFactor,
pitch: ((bufferedFactor - 1) * (((_q2 = (_p2 = bufferedResult.face[i].rotation) == null ? void 0 : _p2.angle) == null ? void 0 : _q2.pitch) || 0) + (((_s2 = (_r2 = newResult.face[i].rotation) == null ? void 0 : _r2.angle) == null ? void 0 : _s2.pitch) || 0)) / bufferedFactor
};
rotation.gaze = {
bearing: ((bufferedFactor - 1) * (((_u2 = (_t2 = bufferedResult.face[i].rotation) == null ? void 0 : _t2.gaze) == null ? void 0 : _u2.bearing) || 0) + (((_w2 = (_v2 = newResult.face[i].rotation) == null ? void 0 : _v2.gaze) == null ? void 0 : _w2.bearing) || 0)) / bufferedFactor,
strength: ((bufferedFactor - 1) * (((_y2 = (_x2 = bufferedResult.face[i].rotation) == null ? void 0 : _x2.gaze) == null ? void 0 : _y2.strength) || 0) + (((_A2 = (_z2 = newResult.face[i].rotation) == null ? void 0 : _z2.gaze) == null ? void 0 : _A2.strength) || 0)) / bufferedFactor
};
bufferedResult.face[i] = { ...newResult.face[i], rotation, box, boxRaw };
}
bufferedResult.face[i] = { ...newResult.face[i], box, boxRaw };
}
}
if (!bufferedResult.object || newResult.object.length !== bufferedResult.object.length) {
bufferedResult.object = JSON.parse(JSON.stringify(newResult.object));
} else {
for (let i = 0; i < newResult.object.length; i++) {
const box = newResult.object[i].box.map((b, j) => ((bufferedFactor - 1) * bufferedResult.object[i].box[j] + b) / bufferedFactor);
const boxRaw = newResult.object[i].boxRaw.map((b, j) => ((bufferedFactor - 1) * bufferedResult.object[i].boxRaw[j] + b) / bufferedFactor);
bufferedResult.object[i] = { ...newResult.object[i], box, boxRaw };
}
}
if (newResult.persons) {
const newPersons = newResult.persons;
if (!bufferedResult.persons || newPersons.length !== bufferedResult.persons.length) {
bufferedResult.persons = JSON.parse(JSON.stringify(newPersons));
} else {
for (let i = 0; i < newPersons.length; i++) {
bufferedResult.persons[i].box = newPersons[i].box.map((box, j) => ((bufferedFactor - 1) * bufferedResult.persons[i].box[j] + box) / bufferedFactor);
}
}
}
if (newResult.gesture)
bufferedResult.gesture = newResult.gesture;
const t12 = now();
interpolateTime = env.perfadd ? interpolateTime + Math.round(t12 - t02) : Math.round(t12 - t02);
if (newResult.performance)
bufferedResult.performance = { ...newResult.performance, interpolate: interpolateTime };
return bufferedResult;
}
// src/face/match.ts
var match_exports = {};
__export(match_exports, {
distance: () => distance,
match: () => match2,
similarity: () => similarity
});
function distance(descriptor1, descriptor2, options4 = { order: 2, multiplier: 25 }) {
let sum = 0;
for (let i = 0; i < descriptor1.length; i++) {
const diff = !options4.order || options4.order === 2 ? descriptor1[i] - descriptor2[i] : Math.abs(descriptor1[i] - descriptor2[i]);
sum += !options4.order || options4.order === 2 ? diff * diff : diff ** options4.order;
}
return (options4.multiplier || 20) * sum;
}
var normalizeDistance = (dist, order, min, max) => {
if (dist === 0)
return 1;
const root = order === 2 ? Math.sqrt(dist) : dist ** (1 / order);
const norm = (1 - root / 100 - min) / (max - min);
const clamp2 = Math.max(Math.min(norm, 1), 0);
return clamp2;
};
function similarity(descriptor1, descriptor2, options4 = { order: 2, multiplier: 25, min: 0.2, max: 0.8 }) {
const dist = distance(descriptor1, descriptor2, options4);
return normalizeDistance(dist, options4.order || 2, options4.min || 0, options4.max || 1);
}
function match2(descriptor, descriptors, options4 = { order: 2, multiplier: 25, threshold: 0, min: 0.2, max: 0.8 }) {
if (!Array.isArray(descriptor) || !Array.isArray(descriptors) || descriptor.length < 64 || descriptors.length === 0 || descriptor.length !== descriptors[0].length) {
return { index: -1, distance: Number.POSITIVE_INFINITY, similarity: 0 };
}
let lowestDistance = Number.MAX_SAFE_INTEGER;
let index2 = -1;
for (let i = 0; i < descriptors.length; i++) {
const res = distance(descriptor, descriptors[i], options4);
if (res < lowestDistance) {
lowestDistance = res;
index2 = i;
}
if (lowestDistance < (options4.threshold || 0))
break;
}
const normalizedSimilarity = normalizeDistance(lowestDistance, options4.order || 2, options4.min || 0, options4.max || 1);
return { index: index2, distance: lowestDistance, similarity: normalizedSimilarity };
}
// src/util/persons.ts
function join2(faces, bodies, hands, gestures, shape) {
var _a2, _b2, _c, _d2, _e2, _f, _g2, _h, _i2, _j2, _k2, _l2, _m2, _n2, _o, _p2;
let id2 = 0;
const persons = [];
for (const face4 of faces) {
const person2 = { id: id2++, face: face4, body: null, hands: { left: null, right: null }, gestures: [], box: [0, 0, 0, 0] };
for (const body4 of bodies) {
if (face4.box[0] > body4.box[0] && face4.box[0] < body4.box[0] + body4.box[2] && face4.box[1] + face4.box[3] > body4.box[1] && face4.box[1] + face4.box[3] < body4.box[1] + body4.box[3]) {
person2.body = body4;
}
}
if (person2.body) {
for (const hand3 of hands) {
if (hand3.box[0] + hand3.box[2] > person2.body.box[0] && hand3.box[0] + hand3.box[2] < person2.body.box[0] + person2.body.box[2] && hand3.box[1] + hand3.box[3] > person2.body.box[1] && hand3.box[1] + hand3.box[3] < person2.body.box[1] + person2.body.box[3]) {
if (person2.hands)
person2.hands.left = hand3;
}
if (hand3.box[0] < person2.body.box[0] + person2.body.box[2] && hand3.box[0] > person2.body.box[0] && hand3.box[1] + hand3.box[3] > person2.body.box[1] && hand3.box[1] + hand3.box[3] < person2.body.box[1] + person2.body.box[3]) {
if (person2.hands)
person2.hands.right = hand3;
}
}
}
for (const gesture2 of gestures) {
if (gesture2["face"] !== void 0 && gesture2["face"] === face4.id)
(_a2 = person2.gestures) == null ? void 0 : _a2.push(gesture2);
else if (gesture2["iris"] !== void 0 && gesture2["iris"] === face4.id)
(_b2 = person2.gestures) == null ? void 0 : _b2.push(gesture2);
else if (gesture2["body"] !== void 0 && gesture2["body"] === ((_c = person2.body) == null ? void 0 : _c.id))
(_d2 = person2.gestures) == null ? void 0 : _d2.push(gesture2);
else if (gesture2["hand"] !== void 0 && gesture2["hand"] === ((_f = (_e2 = person2.hands) == null ? void 0 : _e2.left) == null ? void 0 : _f.id))
(_g2 = person2.gestures) == null ? void 0 : _g2.push(gesture2);
else if (gesture2["hand"] !== void 0 && gesture2["hand"] === ((_i2 = (_h = person2.hands) == null ? void 0 : _h.right) == null ? void 0 : _i2.id))
(_j2 = person2.gestures) == null ? void 0 : _j2.push(gesture2);
}
const x = [];
const y = [];
const extractXY = (box) => {
if (box && box.length === 4) {
x.push(box[0], box[0] + box[2]);
y.push(box[1], box[1] + box[3]);
}
};
extractXY((_k2 = person2.face) == null ? void 0 : _k2.box);
extractXY((_l2 = person2.body) == null ? void 0 : _l2.box);
extractXY((_n2 = (_m2 = person2.hands) == null ? void 0 : _m2.left) == null ? void 0 : _n2.box);
extractXY((_p2 = (_o = person2.hands) == null ? void 0 : _o.right) == null ? void 0 : _p2.box);
const minX = Math.min(...x);
const minY = Math.min(...y);
person2.box = [minX, minY, Math.max(...x) - minX, Math.max(...y) - minY];
if (shape && shape[1] && shape[2])
person2.boxRaw = [person2.box[0] / shape[2], person2.box[1] / shape[1], person2.box[2] / shape[2], person2.box[3] / shape[1]];
persons.push(person2);
}
return persons;
}
// src/sample.ts
var face3 = `
/9j/4AAQSkZJRgABAQEAYABgAAD/4QBoRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUA
AAABAAAARgEoAAMAAAABAAIAAAExAAIAAAARAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQu
bmV0IDQuMi4xMwAA/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoUDg8MEBcUGBgXFBYWGh0lHxob
IxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgoKCgoKCgoKCgo
KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8AAEQgBAAEAAwEhAAIRAQMRAf/E
AB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAE
EQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZH
SElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1
tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEB
AQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXET
IjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFla
Y2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXG
x8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQMRAD8A+qaKACigApGOKAML
Xp8xlF5A7V4X8RtYs7PzfNImnx8sa8Kp9z3q2tEgp6angWs62ZZ5CTGoJ6DArGNz5p+UrID6EUrF
PUlW1EuN0XNW7PQ2L5j3JnoKXN0KijqNP0eYoqXBdgPuuo+ZPeupisWn2Jd4+0r924XgsQOCff3/
AJ1FzRKxDqGii6m3siiQ8F1XGfXI6YNWLfRbiRQMkcZI9fpTDluT2/h6Qy8gDPbtmtG38JeY480Z
5zSLUTZg8M28YwYxjAArXtdPt402qgHbpSaLWhma3o0Uqk7Nx9DWLaaVblgPs6qRyds2M/gRSQp9
zZOni2iWS2hlQ+kjYz9OMGrdjq89vIPPVhj+8M/lQyDq9P1WOYBlMZz1AOD+VdDaTiReOKulK0jO
tHmi0WDTlr0TyxRVhT8tJjIX+9SUxHXUV553BRQAVBcPhSBTSuxPY86+IGti0s5I7dsORy9fM3i6
8e8mfDO5P90ZrWWiJicNPpZZtxV/xrW0jQt4DOv6Vk2dEEdTY6BHuB25rpbPSo0QARjP0qTRI17W
wA/hFaMWmoQMgflQXYsDS142rU9tpqqenfNA7GgtihxkdKuRW6qMY/GkDZY8sY4Ap4hXbyB+VArk
EtuH4wPyrk/EGkOm+a3jw3suRQLc5i38SX9hJ9nnY+XnBUdPyNdFY6pa3KkkAE9l6f8AfJ/pSJT6
GhDmI+Zb4ZRycdv6ium0nUhKFydrelTsNnS2829RnrVgV6NKXNG55lWPLIM81Op+WrZkRMfmNNzT
A7GivPO4KKAEY4XNYWt3vkwPg4OK0giJdjw/xrqhm87Zs8tc7pX5A+leSajf6aHYJ50kn4AZpTep
rBWRm2Vobm4BXfyehPFdnpmnBFUY5rI2SN63tlToK0YI+KZpFF+3QdavwoKTLtoW0Toaswpk5pCb
LCxipAhoIuP2dKevHXoaYDylRyxhlwRQI4nxVoCXWZI1GfpXGtbSWjYPGP73+NIGupt6TqMsLruZ
ih4xnP5V09mQ+JLd8gn0xSYJnVaVdkook69K34zuUGunDS3Rx4qOzHVIp4rrOMY3NJQI7GivPO8K
KAILt9kZrz3xlebYiu8KCCWb0XvW0NFch6ysfO3jLVjfXLIn+pQkKorl7WxNxIPl71g2dUUdpo+l
pBGvHPet23iC8ihFosrxirkHQUFo0IF4FXI1O726CpKLacCrMJoJLYHAPpTwucHpSRJJ5e4AZI9x
UqpxzVpCuOC8cUpQUMRnXttuB4rjNdsYyeVwfXpmpGmcvcQyafMCFJjPY10eg34BUg4DcZP8jUO4
HaRq3lLNF+IHet7R7jz7c56rwa2wz9+xhiVeFy/T1PFegeaNPWigDsc0ZrzzvDNIaAM7VpNqdegr
xL4l6kywyRhseZ19lrdfAZL4jxYg3Fw20d63tJsdrDI5rm3Z3R0R0Mce1eKnQYAplIkWrMJ45oZS
NO3PHbNXIyfpSGWowSOasxLUiZdjFSqtNEMkUemKlAGKsRJjAppFAiORMjmsTVrNZEO4cfSoZSOD
1eJ7WXBUzQZ+7nkfSo7e2Ei+ZaMzxntjBX2NSU1Y6/wxqojiEFzkA8KTXYaUoWRyv3W5rSjpNHPX
+BmpSg8V6J5gUUAdhRXnneFFAGHrTfu5PpXzj8S70/aZtxzztXFbv4DKHxHI+H4GZiz9zxXXW8G3
GBXMjvLRXAx0oPGPSmMVeOnWrMTYpFI0bcg1fh54xmgovRcD3qxETSIZcRvzp+/BpEkqsBUqsM9K
q4Em4Gkxk0yRGXrVW6i8yFhkg+tJjRxGsWrxllkUMh9eK5uMz6bcebbnfG33kPcVkay2OntPKuo0
nhXI67c8qa7Lw3c+adjcEDGK1paSRhVV4s6A0or0jyRRQ1AHX0V553hRQBz+vNtt5z3xXzX8Qbdm
uic5YnOMdK3l8JnTXvlbwpYl+WySOgrp5YfLOOB9O1c62O7qQkc+9RsKChFPWp4DluOlSykaNruH
ArUgHShFNF2NT1qxGO3NBmyxGcE1N2560CFzjrUysO9JAPDDjFOVuKoQuSRTWouBkazbCa3cd8cV
wF7IISQccHBzUSWpV9C3o1x5b5GAjdQD1rs9DjC3kckbEhqKfxIzn8LOupRXqnkPccBSkUAzraK8
87wooA5rxMSI3HqK8B8bQl9Q8sffY5b/AAraXwkUviNrw9pH2W1ViMMRTdRjw4HpWNtDti9TPc4P
FQs2M5qdyyMHLcfjV63HTAoBGtap0wK0YxigpsuRDtVhVYd6GQydVwwIqdRnqKCR23I5pCMUW6gD
YNKuetAEise9KTxQBWuFyhrznxNZkXjFeN3I+tTIZg2OqmzmxNF0PO3vXp/g2+hukVl4zyPanTXv
JmVR+60dpThXpnlPceopWFAbnV0V553hSGgRynjC5FujOey14Ssp1HxNmTnc+a3kvcIpv37HoEYQ
QmMdVHSsnVbYJF5jVk0dsNzlruVIsl2wKxbjWrVHILjg1CRbZJb+ILHPzyhfStODWLQgFJFYd+el
UJM27HUIXxhga1Y5lLVLKLkMnoauxnPPrSEx7ShF+Y/n2qrc6xBbhizDAqkK1zJuvG9nbg8ZA681
ly/Ei052RO3uKAsZlx8QGd8xxvt9Aa1NH8dK7AXMcip64zigdkdrZX8F7EJLdwwNXMkrz1qRMRly
CK4TxmpidWI49felPYSOMmi80NIoOV6qRzXYeA5SskYPfirpfEjGr8LPWVHyD6U4CvQPL3ZItOYc
UDOoNFeed4Uhpks4H4iE/Z5MeleMeGULeLgjds10S+BGdL+Jc9OSBU2Huc5Nc74yvUtrcDBrJnZF
63PJdXvLy/lKWw46bvQVz82jXhkLO5Y+9ZlsYthcRnbIjY9R3q3awTRkEM3WmJI6C0ea3dGRsr1x
XY6TqW9FLHnjrUs0izpLK5DDjofSta3ckH09KRUkZuuTvFGdvPauE1Y3U6Mqbssf/rUxHPTaJPK2
ZmJPbBqzY6DCZh5xJC9s9aBJHU6dpemJjfEmfetJtI0+VPkUr/unFOxdiextHs33W07YHQHk11mk
Xb3KbZ1xIvcd6LEyWho4Nct41sTPYb16ipexCPPZN+wYGCvH1rrPAEJmvkPoc1VL4kZVvgZ6yFwK
cBXoHkkqinFaVyzo80GuE7WJRQSziPiGdthK5HQV4x4J/wBI8WPIewNdEvgRNL42emO/yj1UHNef
eNpRczbC+I17DvWT2OqJxc0sMK4TCisy41q0hfEkqj8aixdwTXNOlwvmqD9anS9tXH7uVG+hosO4
/wC0oOhrR0+6G4YNIEzsNEuCxAPNdjZruA4xxUmjINSjURksOlcbqFykbnjFA1sYGoassaknCqO5
rl7rxhGm7yBnBxuJq0rkSlYpw+NLlsfd5P8AerVsvHEqSBHwPVgcgVpyMyVXU3rXxcHYETAk+hru
/DWti6ZSTyOKzZqndHaxvvUGq2rQ+dYyqR24qWI8dvbr7LqDxyDAzXpvw6FvIxePGSM06Xxoyr/A
zviKFHNegeX1J41zUhXioGbuaSuM6wpCaBHG/EcA6HN/exxXjXw2jL67cv8A3Qa6H8CFR+NnoWpO
I4XI44rxLxrqjQzSEsQM1gdSPM9U1uR1YbmWIdXHf2rmpIb67YS28UrRlsLI3c/jW0VZGUpO5pW1
jfLNOjahawzwReYI5cjzMkDavHJ5/SrVv9uhtPtVxCPLBwzxnlT9KGghLU3tKvvPjHzbl7EGuisJ
GRxWLOg7nRXJEbDjmvSNK+aFSfSoZr0KutRkphc4NcRrdkVjL9aVio7Hk3iqS8ubhrWzUlsZY9kG
cZNc5D4aee5MclzJIFTzHAO0MfatqSOWu7bFS1srDUZEis0vIZoUxPvfcC+4/dx2xjr712XiTwXb
WmlQ6hol3cRhoFd4rlg3zY5wR0GelavQwjq7GD4etdVvSnk2wAB+9v8A8mvcfA2kXiRo0/UdcDis
ZnTTulqeoWqbUAJqWUb42X1FZlnjfjSwlGrr5S/eNdD4RkvLAAQ4yRyaUZcruVKl7TQ9I0G+mnzH
ckFwM8VuIK7ac3KF2eXiKapz5UWYxipNtMyNejNch0jSar3cjR27uoyQCRVRWom9DxTx54gu5fMi
lbKdMVjfCZPNlv5v9rFbVHpYqjGzbOn8SzFI9o715L4u0r7arYzk+lYdTqSujy7U/C0u4vHk+WwO
xuh9q3J9dgvbdVukMV1EwbDDgn04rZMwlHoZ+orZ6hfQ3RWVnQYCgZAq+8U0ln5NtBsV2yxYcfgK
JtW0CnB31LlroVwJ1nQLGDjeP7w+lb0dsFxjrWB0tHS6NuWPJ6A16ToUm63T3Gallr4S7cxiTjrX
PaxaF7dlVeSMUhxZ5jd+H7qCa4eF3DSE5x3zXN3Wk6jbyeaiFWUY6ZyPStYS5SalPmVipFbX0E4c
W0alvmPHJrag0rVvEE6LdljGpG2NRtQD+tW5XMI0uU9M8NeFo9PiQhecDIIrtrOMIoG3H4VlJm9t
C6CB06VPGM1IHLeItGS6uw+ORT7e3jsbQvj7gzUNam0JaWE+HN7NqOqX80n3FO1RXo8YzXdS+BHk
4z+KyzGPapcU2YIv7qQtiuaxvcaWqG4O6FwfSrS1JbPnrxoxkv7qIfejcitj4V2f2exumI+8+aKn
xHTT+G5d8Txlm4rjLxMsQwzWT3OiK0Mm6sEkVsAcjFc1d+FEmlGwEDPQVopaEuOpr6f4ZWNAu3tW
vHpAj5ZQcUFIWaDjGMVUMQ3cVDBmvbhY7QAV2nh+T/R1yeKhlrY31+b61FcQK6nIoJMi401WblRi
qr6PCw5UYq9y+YgOgWzNkRrx3xWjp+nx2v3FQcelAbmko9anQ4GBUNisPHWr1qMrQhS2K11HvmYV
hamcxSRZ5xRIqluS/DKAQQXZxyXrvo2FdlL4EeZjH+/ZbjNSZpswLNBrE1Gt7VE4ODVIlnh/j61F
j4lmeTGyUbq6LwdEqWbeX0YbhSqfEddP4Bddj4JIrhL5d8h7VjI6oLQqKNzelWre3yc4/ClFjaL6
wqBxxUUxwCKu5BmXRA6c+9ZjP83FSBoQuPs4BrsNBlUW659KmRrDY6G1lyQtW3Hy0lqQ1qVJnAbm
oy3b9KYJCqRj3o4zRctIlhjLHmpSuOBRbQOpLGpPFaES7UqkZzKN1KsEc87/AHUUmvPLTVGv72aQ
k7WJwKmRrQ3ud74Ltilgz4++2a6iNDXdS0gjyMU71my7GpqTbxSbMki3SViajTTHqkSeR/GeyZmg
nQHkEE1S+F+oPPavBL96I4/Cia1udVF+4dVrkW+Fq8+v4tjMDWUkdVJ6WM0cNV+F+MVmjUcZgqnP
1qpNNnkcVRLiZtxIS1UzzIF7mghlxUZpVQdq6nTVdAoAOKzkbQWhvwM6gMM1twOJYx3NOJE11Kt1
H1/pVVlwBkk+9NocXoOQ45FPj+fkUJFF2NSB700v/hTEty5ZpkjvVyUgcCq6GM9zC14/8Se6GcZQ
1574Xs5WkI2HBPHFQ1dm1KSSZ7Rotn9l0+KPHIHNacae1dy0Vjxaj5ptlhVp+2s2CJ9ppCKzuWNx
zSFc1SYrHNeNdIGpaYw25ZeRXmvheyk0jVpEdcLJ0q3ZxNKTa0O3vQHg/DNcHrsJDmsmjspnNzNt
fFIJ24GazOhC+azDmgZIOOKBsp3J2qSaZodubq58yQ4QAnmhGT3NO18pb7BORmu205LfYpyKVkWp
Oxr5gKYWoIZWgfGfloFq1qTPLubnGO1RPtxg4P0oBAkY/hBz6VNDDkZ6AU0W2WSdqkdKr9ZOaGSj
VtcLHmnOcgmmYvcz7mBLy3MbdD1q9ouiRK6bUAVeelOC1InPlidSsWMDFOCEdq3uefykqrinYqGy
rFvApMVka2DAowKAsMkRXQqwyDXn/iWyitNQ3qPl6itIvRoF8RXinW4tQ6HI6GuW8SIVBPalc6qe
5x9x97r3qruwTjrWZ0ksZ9TUmcDNAmZ9/wAoao63rR0+w22MLPtAzt6mghmfofiB76LdJBJBIp5D
d/oa7bSdWLIPnpDi9TM8TeKdas51XTbIyxd3J/pXS+E/EFxqNoFu7do5OmD60maHWrnZyDRkn/69
MlEyOR0xntVoNx+FUgYjPxg4FLCuWDZyKQr2RoRnP0qO+nEFpJITgAUzLqZnhu6+0rknOTXpOmwJ
Fbrt5yMmnHYyr6Oxb2ijaKLnPYMClwKQWK3n0hn+lachHOJ9pNNN0apQFzsY10a4v4hXQh0xpieQ
MA1XLZNjhK80cT8OdV+3Wl3A7ZZJCw+hrR1qLcjZ/CsbnfHRnFXseHJArOYYbrUs1uPhYbuatqFP
ByfSkMq3UIINYkto+87Tx6GkSxfsDbflGD7CtTw/pk4nzITtPIFMFudsukh4Rxz71paTpKwP5jcn
0qTRy0NORMDgVCqewoJTJgAoxjntTiTu7fWmFxAcnn1q3EPl+X8KZMi4gKqB1Peob/Tv7Us5bfeU
yOoq4R5nYxqT5I8xieH9J1DTbvyJELRg8ODwa9Ms5mSFV9BWiptbnNVrKdmif7Q1KLg96XIZc5Is
pNL5pqeUrmMtZs0jzV08phchaY00zH1p2ZNxjS1g+LdJOt6U9ssmxjyGp2urDjLlaZzng/wUPDqz
TSTmWeTrjpVjVk3Rvjr2rnqQ5dDvo1XUd2cTqSNk9OKxXGCeKxZ1DAxHTr2q5C/y8GokUhsz54qu
uCxzSQjQ0+FZblR2ro4bZYiMVQ0dBb7Qi5x0qzuG5QOh71LYErDufpSeWrHnimIXbjkUjLkH1Hem
gGxryc+tXI19KYmWegq9YLiLJ7mtqS945cS7QsWehqxA9dEjz4krPSxyZqbFFhGxUm6smjRM55Lk
HvSvNxXTY57kLT+9MNwKdhXGm5FIbkU7Bca1wMEVhaiuQcVhXWiZ14R6tHGanGBI2OtYkqEHjgVy
s9ErEeo6UBsHipKEZs5qpPdRxcbhx70NCSuybTNWihc5brW9Fq6vjMnFSdEIdDRi8RRKygZbHFbu
m6nb3RA3gMegNJhOm0jbXGOoxTuCc1Rz3FyoGKawz9KaAVcZqeMgCmIkB4FaUTbYwB6V00Fuzixb
0SFMuDU8Mlbs4UPeXHeiOXkUrDuXYnyKk3cVk0ap6HMxxketSMhrcwRC0dMMZFMQ3yzSeVQAeUaz
9Vj8uPd271nVV4m+GdpnHX67pCeKyLtBtNcR6xlk9RVeWTb3qRnO6trgttyIfm71z7ai8j7/AJmN
DNqUVa5Yi1AnjynHuBV+11YJhWWXcP8AZNSzqgmaEerSsf3NtIQP4mGKtRavdRgMIpVI9KjU0a7n
R6T43uYQI7qN2Tpkqciu503VVuQGAYZHQjFVc4alPlZrpKGAznpTwxOc9+lWjIlUACnM4XApiLNk
nmvnsK0NvpXZRVonmYqV52GsmanhXitTmFkSiJTSAvwrxUxXIrJ7miOfjf1pzNWxkRlqYWpgJupu
6gQbuahvIxPA6eo4pNXVioS5WmefakGhndH4INZs5DJXA10PaTurmLO21uKpSZqGMoXGnRzBiyjd
9Kx5rcQS428fSkjanLoaOliHGZFB56VswW+mtPufcBsGOAfmxz+tFkd8HpoaUx09FAtFY8DO71qb
Sms/Nb7RbecG6AEjFLS5c78t+p0djpVs9wsyQiJAdyr1rW+zqjErzSe559Sbk9S3C+MA1bjbgE1S
MSXzMVG0vNUI2tPKrAuCMnrVzNd0PhR49W/O2xrHmp4TxVMzQshpIzzQBehqesnuaI5VGzT2bitz
FEbNTC1ADS1JupgG6l3UAc14s04yR/aYRll+8BXCtLncDXFWjys9TCz5oW7GddH5qqNzWDOgQnC8
VSuo1kHzAGkPYopEY2+RWxV23Vzj5G/Kg3jWaNazhZuqNXS6TaKhB2c0jR1nJWOlhOxRxU4YkCgx
Y0OQatQyDbyaaFYe8uF4NY3iC9ltbVGj43NTIL3h7WzMihjzXVQXYYDdW9Cf2WcOJpfaRZ3g9KsQ
mupnCLIabGeaAL0LcVY3cVmzRHIxtUhetzEjZqjLUAIWpN1ArhupwagAfDKQ3Q1594v0c2bm6tx+
5Y8j+6ayrR5onThp8s7dzkZjuqAAmuBnqC7c0iwgtzSA0rWzjfGRW3ZadDu4AoNYo2rfS4v7orSh
05UA2r0pDbsTm29KRottBNyJ0wpJ9KhD7f6U0ikNWffIFBz60zVUW52ow4UcUN6EPcx44WsbgOmd
ua7TT5Bd24KHnFKnLlZFSN4koluLdueRWvp14swweG9DXoxldHlTjYtzGoo25qzEvwtUxas2jRPQ
5CNqkLVsYoYzUzdQA3dSFqBBmnqaBhuqhriCXTpVIzxUz+Fl03aSPI9QTypW2/dz0qKNw3SvOPZR
Mqin8VLKRcs3O4Cuk0w/MDjt1NBtHY6O2IIHY1pxgFaETIRwMkjtVSUEk4570MlFW5bap6dKzWm8
1tqH8aY+hp2FvGoGayNevVt7/ap4xzUvYjqTLtvLPcvJxSaVcyWsxTnFZlnT2t15xHmCtOBYwQy4
B9q7cPO+jPPxFO2qLEj5HWo42+aus4HpoX4W4FTF+KlotbHII9SFuK0MUNZqiLUDE3UbqBBupwag
Bc1DefPbyD/ZND2KjujyPWlKzuPesRZjHJXms9lMuw3StjnmphKDSLTJ7OfE3JrpbO4GQc9qlnRA
3LO82k5NbFvdADkjBoCSHyXIIIzgVQvdRigT7wzjgUzO1jHknlvG7qnp61etYFQDIpCZoqVijzXn
3iC8EmsOuaCGb/heR/s0ijkVv6fbxy3QMg5xmsnuX0Ldzut3+UYTPWk+2GJSe+M1pFtamcldalmx
1eO4XaThhWnC+TXqR2PHqL3maUJ4qRjxSEjj42qXdxVmaGs1MJoATfSbqBAG5p6mgAzTJTmNvpQU
tzzHXY83D/U1zF5FhjgV5r3Pa6FMsV5HWnLe7RhqBRdmTwagN2d2K2rPU1C5LAnPrUs6Iysbdrq6
f3gK0BrUKj/WClY05iM6xLOcQAj3NT29uznfKSzHuadzNu7NSBFjHNSm5VO9IRnajqoWMhTzXFtA
bvUfMduSeg702Qz0rS7FbTToQFwzjJqaGTFyfK5PQViyzUuFmuIdgGABya5u/vTaN5cnUHFUmLoZ
zyskwlgJweSK6zQdUEwVJeGr0aUrxPLxEfe0OrhPAqVjxWhznGRtUwatDK4jNxURbmkAm6jNABup
6tQAFqhupNtu59qUnZFwV5JHnWsHdIx96w5lz15rzT2uhRmt85xWbcxMnUGmZlB0bdxmrNvFIcfM
350mWjbs7YkDJY/jW5ZWW4jikWkdNp9mqYJFaJdEHHakUULu/VB1rLn1Ld/FgetMGYd/qWSQmSa0
/AemS32pfa7piLeLkg9z6UmQtz0W7uQ2cZx0A9BVzR7cAea6j2rPqX0L99KRat5A6Dk1wOoKZ52a
YfMORTYRLujiGWEq6/NWza2yKQVHNdOHerRy4laJo6TTnbbtb8KuM3Fdh5z3OJjbmpt3FaMxAtUZ
agBN1GaQBzTwaAAms3VbjERUGsa07RsdeFpuUuY4jUjljWTKK4j02RE4IpJYFk6imQkVl0xWarsO
mAEcUi0bNnZBR0rWtoguMCkUi21wI161mXuocEKaYXMS4u+pY/hVCSWSY4HT0pEmlouiSahdpEBl
mOceleiwWcNjClvHgJH97Hc1EmVFFi3Czy7mwIl/WtJbjP7uLgd/apQ2VNVvtsBhiPzdK5S4nAuR
nqOCaTGi9pcytPlU+XpmumtWII44rah8ZjiNIXRuWeNvvViQ/LXpJWPJbu7nCRvVkNxVsxBmqJmo
EPiXca0YLMuOlJsuKuPlsSi5IrNuG8s4HWs5VEkbwoOTKsk+FJY4rC1K53k1xTk5O7PSpwVNWRzt
4cms+WpKICtSLTETQj5q0YeBSGiys23pUguGxQMq3E59ayrm4x3yaAKiRtO2WPHcmhruKFxFajzZ
ScA44qRHoXhuMaLpxaUg6hcDLMf4F9KlhuDeXGASIl+8azZslYma68y48m1+7nFW5rtbRNhb5z1p
iMKbUg0zuW4A4rPgb7VdKXOMmpA7HRbMS7nUYiUda0lkQOBngVrS+JGdbWLRt2bAx5BqeQ/LXpnj
PQ4GJ+ashuK0MhWaoWcA0AaOmASMK7jRNPWYBmHyiuepO2x10qfcv6vYxCzYqoGK4HVYVTJrmb5l
c6oaM5TUJ8EgGsG4kLNUHT0M64OaqMMikSRsuKbnFMRLG3zVehOaGNE445NNlnVFpDMu6uie9Vo1
8z5mOAOST2pDK91cNN+5tsrH3PrW54a06KxT7fdrlh/q1Pc+tJ6IUdZGvHPLezMcnBOWbsPap5r3
ylFtbdT1xUWNWzU0/Zbwlgfmx8zGsHWtRHmMqE59aAMyNifvHPc1f0gtPdqkY5JosJHeNci2tktY
euPnNY+oXWZEVJNrZ9aun8SIq/CzodHuriIokhDIR1ronbKZr0o6o8ipoz//2Q==`;
var body3 = `
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAsICAoIBwsKCQoNDAsNERwSEQ8PESIZGhQcKSQrKigk
JyctMkA3LTA9MCcnOEw5PUNFSElIKzZPVU5GVEBHSEX/2wBDAQwNDREPESESEiFFLicuRUVFRUVF
RUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUX/wAARCASwBLADASIA
AhEBAxEB/8QAGwABAAIDAQEAAAAAAAAAAAAAAAEDAgQFBgf/xABDEAEAAgECBAMECQIDBgUFAQAA
AQIDBBEFEiExE0FRBiJhcRQjMkJSgZGhsWLBJDNyFSVTY3OSNEPR4fAHFjWCokT/xAAYAQEAAwEA
AAAAAAAAAAAAAAAAAQIDBP/EACARAQEBAQADAQEBAQEBAAAAAAABAhEDITFBEjJRIhP/2gAMAwEA
AhEDEQA/APqYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAKNTq8OkxzfNkisQC8eb1XtRNbzXT4q7eU2nu0MntRq/D8StMccvW29ZmdvgjsTyvZjxOLj
+s8WLxn8TFPXs6Oj9oct7c14rkxz22nrB2I49KOdTjelmszfmpMeUxv/AA28OqwZ4icWWtt/SUi4
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmdo3nsPNe0Pt
Fh09Z0+DNWL7+9O/7A3eJcZppsV5raI27esvH6jX5ddM25p79Ilo59VbUZOe2Tm/PeGvfPfT2iKR
PLv1+DO678XmW/a97U6TtOyzTbTF538/T9WjTNecm9a7126tqk3rSYxY5ta1plRZqZNXGjyZcPXl
mZmsx+qjBrsuO16xM7eXRt04JrdTltk5OWJnfaWf0a2lty5MdZnfzSn+WOHiOutFpjHa9e8bQ2fp
+alYy462pk7zXbuxjPesbRS0f6ZZV1ET1tErzXFLHo+A+1ddZf6NrI8PJHa1vN6iJi0bxMTHwfOa
zhzd61v1846utwniM6DUdb3nBaNrVmd9vjC/ZVePYirBqMWppz4rxaPgtEAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAItaK1m09ojcHnvarjM8P0vh49+a/eY8ng9D
h1fGM1rxjtGPfvbzdbjuTJxHX48cTPNltM/KsS9Dw7S49Jp6UpHaGe2vjz1y9J7LYK13vHWe7bj2
ex1tvM80ekuxW3RnW3Vm6P5jRx8H0+OYmMcb+bapo8GKPdpC6bQwtdHU8JpWkdJ/JweL6e23iU67
d4dubSqyVi9Zi0bwIs68XGp36TtEq7ZJmZmevzdbifCKWtbJinkt6eTgZPFw32t+sRurbWVzxs1y
Rv6T8V1NZNPtfq0seTm+Kevr+SZuxXjvaPiV8N4viycto9HseG6+uu08W6Rkj7UPmFck1tE1nlmP
Ld3eA8V8HVVi1pjq6Ma/pnqce/ERMTETHaUrKgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAADW19+TQ5p/p2bLS4v04Zmt5VjeQeJ4bjnLqsupv+Ka1+ERLv4reTmcNxcuC
vy3l0qdI2hlr66sT02ot0ZV7qqrInruzrVZLGSZ37JjqgYTG0K5lbaFVhDT1Ub456RPweY4hixWi
eSdpjvD1eWejz3FNHWYtkpvFo9EIseb3tS3SerOms22rfpPqZKzvvHSYUz70TExG6Gdbs2rljeJ/
Mx5L0vEzPaelnOi98c9J2bFNTFpit47+a+PVUvx9T9nOIfT+GV5p3yY/ds67wvsXqpxau+G09Lx+
r3TqrEAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADV4ljnLw3U0jvO
O0fs2lWqyUw6XLkyfYrWZkHldBEV09eveG3Fq1mI3jd4vPrOIaid8G9MP3Y38k6fNrt/rMk9Ou8s
tfXXn49rGWInuy8SO/k5Gl1E3rG/fzbOe94wTy99mbRvTrMOOvNfJWsesywniukrG/jU6fF43WYN
TmtEeJtEQ06aSmK2+bNtEd+qfSO17unF9Hmvy1y13XWyVmN4tExLxVK8PmNq5NrT58zawam+m/yc
0Xj8NpRYSvQZ7xEOdqI3rPozxayNRXe0ct/ON03jmrKB5nV4q1yTO20Obmv4c+cx8HoeI6WZpNoj
q83niYmYscU0r8aJ6T1n49zeJ+Meqm1drb9J+Kd5p136StGVem9l9TbHxLDFp7W7+sS+q1nesT6w
+PcAzVjiGHftzQ+v4f8AJpv6On8jH9ZgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAABp8VrW/C9TW0ztOO3b5Nxp8VmI4bn37TWYB8f1HFtTfUfR9FWJmsdZ9I7MtJxDX5s
d8ta1y0xzteaR2277rcuhycP12SceLxMeWNpjttHwlu8I0mfQ1y+D7k5YmJmY36T36Ka43z/AF1t
cI1ds+qxVj7/AEej19PCw9HJ4NoK4OIU5Y35YmZdzVTGebVZabx5jJS+Tmns81rNLm1Wrzc9rVw4
Yibbem72mXTTS0w0M3BvEta1bWrM95ie5EanY87wXgNOL6XPfxraXLhra/W28bR/dzYzarBqJxRe
bzE7Rt5vWU9n8mPHOGmS0Ypnea1naJb+k9ncNLR7u2y/WcxXO4TOoyUrN6zD0FaW5Y3hu49FiwUi
KxCvLMR0hlW0jn6ukWw3iXjOJzbDlneOj3GaN6zDzfFOH+LE7SRGo83XNSZ2lbG2/WfdlvaT2cy6
rNFInlrv1mfJ37cK4PwTTxOoidRm2+/2/KFuyMp47XB4LivXiunrH2b2iH2qn2K/J8x4fGDNxTSZ
9Nh8OviRvTyfT6xtWI+DeXs9MNZubypASqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAOZx6/LoOWPvWiHTcf2hiZ0e8fc2mf1E5+vP/AEeuSd7RC2uKtI6QjHfeINTfwtPf
Jvty9WPfbt/lucP03gxfJf7d/wBoReYpm97zaNeLb4Ims9Nt94auDjem1Wo5PFi1onylS+1o7l8V
bxvtupjDMdNkYtXS1+Stt+m63xImEJ4xjHER2ZxMUjeUTO3VRmydBbjLJqPi08mbeVOXJPq1sl5Q
Vbkz9+rRy35rxHqzmZlVEe/Ez5LRlW5iyfR6zffaIjq1OSNZps2a21rZInafSPJhxGMl9LStLRWM
lorM/A4dkrWbYfLZC2W/7K6eubX6b4RzT+W76K8b7G6X62cu3Sten59nsm3j+OXz3/0ANGIAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0OIYfpOHPijvNNo+fdvtXJO18k/
/OwPFYbz2ls3jx8VqW6xMdWPEdP9D4lkx/dt79flLLHbkxTPwY6nt2512ORTRzE2x4/dpE7cvkme
E4IrW3hRMxO8THRtU1FKWtvtvK2upx22rzRCtXkqzh2jtF7ZbT122b01ndnpuWuP3Z3+Ky20qDVv
fauzVy3mejZzNK8dVjqi87KLRLYtXruqvXzkQp7Qoid88R6rcl+WGlW0/Sa22mfhCZOq2x082ix6
jkm822pO8VrPdr4dNObVeDo8XW3uzMbzK+mvxT7szE27cvnu9j7PcNjSaXx8mOIzZevbrEeic5tN
+SZnpt8J4fHD9HXHO3PPW0x/DeBtJxx29vaAJQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAKNRim9Z5e89Nl4DzXtVh5babURHrSf7f3ec1+qnDorWrvvt5Pccb0n0zhmWk
Rvevv1+cPE2rGTFNZU26PFfxwa5dVkjelI2772nZnX6bbrEUq3o0d678u8wmuDL2ittvVjXdneeK
cGv4jpJ6U56+kS7+j118+GLXpakzHaWlp9NNY3tv+bbiYiNoQy1y30uyZJlrWmZnuym6q1iIJnop
yW2Te8bdWnnypQqzZOadokiIpSZntWN5lrxki19vNRxrUeBwnNNd+fJEY6/OejXLn3Xe/wDp9wyn
E8uo4lqqxblv7lJ26T6vpD5X7G8QycKzeBMbzMRM1/FH/wA/h9QwZ6ajDXLitvWzRgsAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAeL45w+dDrZvWv1OWd4+E+j2jX
12jx67TWw5Y6T2nzifU+rZ1y9eHwzDYxxEy18+DJodXfT5o96vafWPVbjyxDn1OOzHudbM0rt2UW
iI69mVtRXZq5tREb9VUoy2iIlRbJ0UX1VZ6btTLrI7V6yk62M2oisT1c7JmtkttVMUyZp6x0beDS
RWOvdKijDimvWd3G9pNRMfRcNfvZOb9Hpb0itJeP47k/3hgjaZnbaP1XxWW3T0movbNS0W645nbf
0nrMPpXs3xamoxdJiLbe/X1n8Uf3fKsOTw4jbaXo+EarJhtGTHMxeJ6xH7Sti9Zaj6x3HM4NxXFx
DS1mtoi8dJrv2l011QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AGjxLhODieOIye7kr9m8d4eM4to9RwjPXFa0ZIvG9bR0fQXmPbDFvTTZPOJmEWS/V8bs9R43NxLL
G8eFbePg1bajU5/s0l1ceKLx1hbjwRE9mOpx0y2uRTSZsm3PMw2aaKtIjo6kYo9EXpET0hVLXxYK
xC6MZvyx1lFs0RHfaPiCnU12pLyHGNDbUajBekWma2npWN3p8+opa20e9LSyZLxExTlpM+vdOdcZ
a9tPS8MyUvFrzWlI6727u1pYxYrbVmb7x+TQx6au3Nqcl7/0rcmW9axGnwZJj1novmxnZXV0fFp4
ZxLBPgTGK8xzXr5fOH0bFlpmxVyY7Rato3iYfNuG2x56Wrqa8s2jz+7Lu8O12bS6jkwzN6THNNI6
tvrN68Y4rxlx1vHa0bskAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAA4XtTTm0OKfTJ/aXdcL2pyRGjwU362yb7fkJz9eTxxyZJjyltRXzUZK7TFtl9Lbwy06YzrHwa+
fJFd/wCVt8m0bQ0eS2qzcm+1K/an+zNZFL5M1pjFXeI72ky48eGnPkvNp27+TPU6nHpMfLXaIjpE
erk5dRMxOfN1mPeisfshW1ne1a1577Y6x5R3U0zze31FOWI6ze0byU098kRlzbxM9qrMlPDpyRMR
Md5Vt/Ihp5898mWZm1pjftE91uCt7fCI7dWeHDEW3t723l6rslqxWZnasR+SYhFbzhnfxJ2jyeq9
lcGXWZcmW0zWKxHLaI7794eJx5fpfEKabT8t8l5isddo3l9S4VjrwrRUwzSJt3tav3pdOL6Y6dXD
j8HFWm+/KsU4NRXPvtWazHquWVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAa+fXYNP9u8b+kdZBsDkZOO135cWOZn4y5Wu4xqctbe9y19Kp4njt6vi+PDm8DFMWybbzPlV
5PiGtz67UxbNbeKTtWIjaIXYpnwuaftT5tXJT3vmi1pMsrU5qIrG1V1a+5DCa7b9GFbRr5J6Wnbt
Cu+Wmk0m8956z8ZWZNorbfzcbX5rZslazPux3hUt41NTntktObJ13+zX1bek01r4/HzVm0bxPXy/
+bNfDgjVa2uOY92kdfg6ufJOKvLXtttVVSqbcta2vM7zXtHpLQy5ZtMd+vWd+7Zy3mdJHXra3f0c
vUarw7zFY5rT2hH1Lavnrgx81p3U49Pk4nE5L35MO/StfNRXR5tXnrS8W67WvfyiPSPi7uLHFK1p
jrtSsbR5Lc4RzsXBaYreP4l45esRD2HD9fnw6evvWvO3Tfr0aGk0U55ra0TFInv6uzgrXFXlx0i0
77RPlC83Yj+JW7oddqr6vHzTTw9/f6dod+L1t9m0T8pcbFSmPHER3892W0zPuz+jSbVvidkcqmfP
Sel7bekrI4n4dZnPWIrHeYnZee2Wpy8dEaml4npNZblw5qzb8M9JbYgAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAABEzFYmZnaI7yCXL1XGa0jJXT0571nbee27DiXEprp8nhbxG20W8
5cbD0ikfnKO+urTPvjoZdXqctdsmTaPSvRpWmsdZ6yztfaGplvv3lWW1tyRlz1x0vkn7Vo5atTNe
Y0+1o79V2KsZsvX7Ne5mwxnyTNvsx2iGneM/rCdRSuOsTasTt5kRFtpjqmOH4t4nk7estiMNa97R
Hwhna0iuKTEdmGWa4672nZtRele1N59Zlq6vLOSsYorEc07qcW65euzRvtXvPZy52naZ7ujr6fXV
rWdukREK8+njHgmZmPc67bq6ivVWhxxgxZLztNrT1mZ/SP4VZs0zaOvfp84WUtNsXLvtv3699+rU
z7+Jtt5qURqMnPpctaR1rMSw4ZoK57eNk6xHaJRh97Ltt7lo5Z+L1HAPZvVauZ2nFTSzMTzeJEz8
to6xPfvsZntPZ9rXxabmxzefdrv0j1dXh/BcmstW1qxTHHasR3+b0GPhGl+kWmd64dNEVjf73T7X
y8vy+Ddx6O3iRakxTH5RXrMw1/lX+3Itw2MFIraN48qRHdZi0cUjmmPen9noox1iO0fNzdXEYrTt
stcmd9aX0bJ+HePmiKTitO8TMLZ1cVjrMfqpz6ys4pjfrPRWZ9rXXptUit6zO+23VyaRHEc05L1/
w9J9ys/en1ljqdVbwYw452tlnl3jyjzbmmiMeKtYjpEbLeTXPUU8ee/+qjJpsV5rbkrFqzE1tEbT
DpYNbW21Mnu29fKWna0KbqTdjXXjld0cvQ63ltGHNPSfs2n+HUbS9c2s2UASqAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAOVxPWe99HpP8ArmP4b+r1EabT3yT3iOkesvMVtN7za07zad5l
XV5GmM9vVfEstvDx0jtaVVMlq+UJ18b5cMRvPeSuK87bUt+i2Z3PtG7zXpjkzXt6R+TXyTMzvM7t
ydHqZ+zhv1+Cv/ZuqvPTHMfOYaTMil1a1K2vHSLTELq2v+KWzThGo84rH5rq8JzedqR+ZeI7WnOS
34pYTafWXR/2Pln/AMyrKOCWnvmiPyR6O1y9585lhWJvl557Q6eo4T4dYiMvW3b3UanhldHpJtGX
e09unmjsT7eb1l4trI2t0hsZfrdNO0bzy+nzU20/+NmkzO9esz+TZxWis9dttvPv+Tn21jjaW8zn
26bTG3mp1M/Wzv3t0jyWXiKZJmsTERaZhXXDbNl8WaztWenxZLstPp5pau8frDtVrNMM5cfTfpMf
3aunxxbes9d/R09Dp8ebJi09ptFr3jtt2WyrW9wy1Jx132mK+Xq9PotT0iIU19ntLtExa3T47T+q
6nBaYvsZstZ+cT/LeMnUi0TXffo1s2m8Ws2/OIMWk5Jib5L328rS2t94Sh5TV4ppklpW6PT6rh+P
NbebTHyas8E081mZy5P2W6OFhjxNTE/hr/LoRO0Kvo9dPqctKzMxEx1la5t3tdnjnMs4noievcrO
yZjeFF1OSnNV0OG62cn1GWffj7Mz5w05joovzY7xes7TE7w0xrjPeex6Ua+j1UarBFu1o6Wj0lsN
3JfQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACrU5o0+nvlt92P3BxuM6nxNRGCs+7Tv8
2hToxm1r3m9utrTvMsonqyt7XTmcja0u3O6FMfi5t/u0/lzdJM81p9O3zdvHTwsUR5+bfPqOfX1h
dqV+3O7bs1+T31oqmI3TEM4rvCdkDGIIhlFd2daboS0NXG2bD6bufxXU1vlmu/u4us/N0+L1tTSx
kr9qk7w89j1FNZMV3jxLzvaJ8mer+LSOZqK2xZotbvljfr/89U453rXt9lse081xZtNjx7TGKu0t
DHlrevSevaN5Y6+tJ8c7VRNMt63n3ub+6/R54rERMztDYy4a5omclYmfxKcenrjtHLvtPrCnVmdb
eFe3JXmjy6eS/DrMuLVYsta9Mdt++6qLxO+0dEc8UmInr18iUfReHcXrqccb9Z27Q61Lb13eJ9nc
1Z35rTvE9avY4bTkpG8xEfB05vYxqybc07R281naGMREdoT5JQqy9mply7Q3bV3iXG1eXw7TWSka
c258t7+tpT5/BjT7MfHqndz12Z+M4lMMKyziUJJiN1WSu9fku23RaOgKNJqbaTU1t9yelo+D0cTE
xEx1iXmM1Nt3W4PqvFweDaffx9vjDbGvxz+TP66QDRiAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAOJxzU73rp6z296zsZMkYsdr2naKxvLyObNOfNfJbvad1dXkaeOdpvsc2yuZVzfbfqybutwu
s5s8R92J3dvJb3tnO4HSMegtmt3nfZvYp8SZl0z45NfSK7onH1bNcfRFqnUKJr0Y7dVtq7prjEsK
0XVpEM6028mW20IHK41aPo3J6zs4ODhdcvPnvExFevNXpMOrxi/PlrTee7PLX6Pwa09uaNlKtHg9
dM3z5d7ReOu02nu0JzZMfblrv5R5uvrcdImZ26T1mYhxs1Os7RH93PZ7axuafNfLitvbaYU3yZYt
PXs9NwHhui1HBa5LVicsb81onrEuVqNNSuS8Y67dZ6xPZa59Il9uX41vEitImZme3q2Kxbxora0T
Md/ROSa4Ztkj7c9OafL5LuGYubmyX3iu/TfbdSfVnpvZLT/XZK233+Mbbva1xRXyiPk8pwbH4N6T
adq5a71n0tD1WDL4tPe6Xr0tDpz8YVnJHWEXYxbqlBedoef4tW0XraO09HdyztSZcbUz43C+ee9b
SVMaeOfqq7+jGckQ1Yz7+7v2RN/WXPXZPjci2+2yyJaVMuy+uSJlA2d+pNoVRbeDcSxyTE+TDDlt
pdRXLTynrHrDOyiyZeVFnY9TjvXJjres71tG8MnJ4Nqt4tp7T1jrV1nRL1x2cvABKAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAHJ49qfD09cNZ97JPX5PPw2uI6j6Vrsl/ux7tfk1mWr7dOM8iLdm
vfebREefRsWldw7SxqNbWbR7lPesrn3Vteo7dYjDpMGCvfbeXQ0uLlxRLRxROfUc34p6fCHYrXlr
EejqrjY8uzCYW7MZjdVKqK9VlaxCYrsnYExBMRMJRPZA8/xPHtmpP9W2xx76vhWOInvt/C7ike7N
vwzE9kcapGfhlevTaFbFo8RqJ5vy8/RoW09ek0msxHfp3dzNoLzp4zUmZpMbT8HJyYJi20X2n0lh
ZY1li/RaidBF4w2mK3jrHaFGp1lN+tptPp5IjBkid5mIp16TKu0abBPv33vPlM7z+iPdFNcWXU5I
tkrNce/b1W5db1nTaf3ax9q0fxDW1ebNk2phty1mOu09VOm8W19orEz23j1TwfSeERFuEYMddptW
d43dvBn21eKJ75KbW+cf/JcTgMxXTb3nbljz+TpcPmc2uyZO1KRtVtGVdi0bx07qJnllsRO6rNTe
N4XVamsy8mnvPwc3R2jPwe8TPbdlxXNOPSZfhWWpwO85OFzv57qrODkzeHntSe8Sn6Rv0a3EZ218
8nXekfr1a0ZLVnqx19dWb6demXybOO7lYMvNMdW9S/VVLo0us7tPHdtUtEwJiZU3jq2Jhham8CVG
PNODNTJXvWd3qcWSubFXJWd4tG8PK3pPd1OB6veLaa89Y61/u2xfxh5c/rsgNHOAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAANLimq+i6O0xPv392rdeZ4rq/pOqnlnelOkIt5F8Z7Wj27I2I6sb25YY
V1ImY3dbQ08LRc23vZp2j5OJG+XJWle9p2h6HHtbJXFT7OOIpX+7TxT31j5rycdTh+Dpz+XaG/sw
w18PHWseULN2trBE9UcrJKBhFU7JAQi0dEomegNDUYovM7x3jb5tO1ZvpbaTLtzRExWfWPJ08kbT
Ex5NXWYYyV5omYtHWJieyeDzuizfRs19Jn6TM7Ru1uMcJxZqTkw+5f4ebqa7SV1MR4tdrx2vEfy1
axqsNOTLjnLXytVXi3Xj8+nmsxTLM16d5npPyUzpekTtSK+U7vS6vQ/SYmK1vWPS1HOn2dvvvvE/
tDO5XlcO+LbfHSd/W3o6/BdDOXPTnj3Kz38rS6Wm4FNrRyRzTH3p6RH/AKvR8L4dXSzE3jmtHn5I
mbfqLV+m4dbLSsZInHjr3iI6zLpYaxS01rHuxHRHiT9mv6s67Vj1aqL6326MrWiYa+/Q54BxPaGe
XRZpj8MquB4+Xg8zPnB7SX30to379GxpK1xcHiKz5IS8xr8PLPixH2bftLTy05o6dHYyVjLhy0t1
izjZa3pMVv3iO/qz1G2L+NbSajbNyW7xLsY8kTDz+fJXFqKZN4iZnafi6WHL0iYlStI7OO+7axW2
crFl7dW9jvE9ULN+J3ZbdFGOy+AYWpEqN7afNXLj+1Wd23KrJVMvCzseh0+auow1yU7WhY4fCdV4
OadPefcvPuz6S7jol649Tl4AJVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAV581NPhtkvO0R+4NPi2
r8DB4dJ9+/7Q83Po2NTqLanNbLfvPaPSFDHV66sZ5ET0hRknyW2lTtMyouz0c8usx2n7s7vScKwx
zc1vu/y85p+maJh6Th+SOWeveXR4/wDLm8v+nX5mUWa9bbrInolmu5jdTNkxYFk2Isr3TuCzeGMz
+THdEyDDJO9Ja823rt2XWnya946pGvktDXta0ztWu/ybvLE9dkcoOf4GbJPWK1j49VmLh9JtE33v
Mevb9G7WsW8l1ccREISophiJ2jpDYpijbaOjOuOJ8ujOdqxsgVcsUjaETYvbaFFrgu5lVsm0yUtu
ryg43H5m+GIj1XcJzePoL4pnrWGtxmfchr8JvfHS1622if3QljzTTLes+qrNjrkiYtCzPMxnm095
YZJ6boS5teB49Tqscza97VtvWvlv8V/FOF34RrIxTM2xXjelp/eHoeA6XnzReY3ivX/0dfivDcfE
9HbDbaLx1pb0lOs+jO7K8Lis3cN+0NKcd9PmthzV5clJ2mF9J9GHHVL108dm1SznYr/Ft0tuhLb8
mNohFbMhLWy0mJ3rPXvDvcO1karBG8/WV6Wj+7kWrvDDBlvpdRGSnbzj1hpjX4z8mOx6UYYstc2O
uSk71tG7Ns5AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACZ2jeXneJ62dVl5KT9VTt8Z9W9xbWclPo+O
fft9qfSHEU1pv48ftYST23ZTDC/p0YtlVuvVjMbM5+LCZjYGWGdrTPxiHY4ffaf3cjTxz1v6xMS6
Olty2iXVj/Dk8n+ndrkhnGRo1v8AFdW3RCrZ5uiYsqrboncSu508yjmZRYQt50TfowYTbYGVrKrT
uTZjvukQnYhMIGVY2ZxPVWyrHVCWzXpVXkt3TE7Va+W4K7X3jv1auTNy3jdba0RZpamfroQN7Hk3
6wr1GTaN2OOJiu6Mu98NvgDi8Wy74d/yZ8PiPAiO2zU4nb6qIn1bugjfFE/ASp1ke9u15mbbRDZ1
Mb823kx0Ontn1OOkedoJCvT8I03gaKsz9q/WW+isRWsVjtHRKyrhe0XCfpWL6Vgr9fjjrEfeh5fF
feH0V5Dj3DPoOo+k4a/U5J6xH3ZZ7z3228evytOk7NvFbo0cdols47bSybt7HbddHVqUs2aW3Qnq
xVeu8LILR3SlZw3V/R8nhXn6u0/pLuPMXjeHT4Zruf6jLPvR9mZ8/g1xrvpz+TH7HUAaMAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAABRq9VXSYJyW79qx6yvmdo3l5viGs+maqYrO+OnSvx+KLeLZz2te1rZL2v
ed7WneZYWnZl5K72YV1xEyxmeqJljzIEWlVkszvbZp5soN3h2SJz3pP3odCnuWmPRxuERfJrZmtZ
mtY96fR28kbX3dXj/wAuTyf6bmK+9YX1s0cNtm3Sd4LFY2K23W1s16StiUJW7bp22RW3RluBuruz
mWEgrmCGWyNkoExKE1QlPmsqRDKeyBjaejWy2W3ttDUyz1QKslvehVqKTNosyyTvELabXptIJpaP
B39Ia2mz+JGpr51jdZefDx2hzuHZObNq58poJaGtjxJ2+LoaKP8ADRPo5+T3skx5OhpOmC0fBNQ0
5yTbn+bt8A0u9raiY6RHLVwY62mI6zMvaaHBGn0mPHt1iN5+aYVsACBXqMFNTgviyxvW0bSsAeE1
mkvw7V2w5Ote9besJx2er4rw2nEdNNekZa9aW9JeQjnxZLYskTW9Z2mJY7zz26fHrrdpbZsY7NGt
mxjvso1b9NmUwpx33XRO4K7VUTE1nmrvEx1bVo2VWiJE/XY4frY1WPlt0y17x6/FuPM0m+HJGTHO
1qu9pNVXVYt46Xj7VfRtnXXL5MfzexsALsgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHM4jxOMFJphmJv529Dq
ZLfjDjPEIx450+K3v2+1MeUOHSOWFc3nJkmZnf4yujpVlqunOeFpV2nctLCZUXRM7MJtsWlRkv3Q
ky5NmpWt9RnrixVm17TtEQnJabXisRMzPSIew9n+CRoccajURvqLx5/chfOest642OGcIpoOG2w7
ROW9d72+LQvXevyejcPUU5M+SvpLeOataraw2a0dLbLqTtK1G3Es4lVWWUSoldFtmcXUbpidgXzK
GEW3TuCUSncnsDFMMLSms9EC6J6FpVzbZE5ALy0809ZbFr9GtfrEoFMzuuwz0Ueey3HbaBLDXe7i
tMOfwWnP9I+NZbuttvhs1uBRtXPb4SDm3iIvf57N7Dbl0VrS5+XrltEd+Z1Jx7cNms9N4TURRw3T
+PrcO3WszEvZOD7P6aYiMlvu16S7y1QAIAABxOPcLnUY/pWCv1tI96I+9DtgmXl68Biy7/NtUu3+
O8HnFa2s0tfd75KR5fFyMWTdhrPHVnX9R0cd21S3Rzsdm1iuqs256wrmGcT0RYSx5d047X02SMmO
esd49YRE9WcdSXhZ2O1p89NRji9J+cei1xMc3wXi+KZj1j1dTTaqmor06WjvWW+ddcu8XK8BZmAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAMMmWmKu952UZ9XFZmuP3revlDTtzWnmvO8q3XGmfHb9ZanV3yxtWeWn7y4es
vPNtDqZJ6Ts5mppvdl/XXRMyfGvSNlu/RVvtOzLfoipLT1VTKbSpvfogRkvtDVyZOhkyvQcA4Dzz
XV6yvTvTHMfvK+c9U3rkW+zvA/D21urr789cdZ8vi9KDb45rejl8Rry6iJ/FV1HP4vXbBTJEfYt1
+UpiHM295bXsqrO9l8QkZ0lZEqqLeyBZHZLGvZkhIndADKJ3TMoqWQMZ6pjsxll2jsCLSrmU2lFY
36gieyu0LJk3jbsga0wdqzK20QpyztQGprL/AFMrOE05NLkt6qdVWZxNrSe5o9vWBLiUjnzXn0vL
q555dHt8HOwV928/1z/LpzXxbYccRvzTB+jucOwxh0dI22mY3ltIrHLWIjyjZKyoAAAAACJiJjaY
3iXleM8InR5J1GniZw2n3oj7s/8Ao9Wi9a3rNbRE1mNpifNFnVs65XhcWTdt47bnFuF24dm8TFEz
p7T0/pn0a+HJux1OOrOux08d1ndqY7tillVkzExLOk7yd4YxGwluViJhE45raL0na0dtlWO0+bZr
1TKi+2zptZGTamT3b/tLacvJjiY3XaTWdYxZZ6/dtPm1zrv1z78fPcbwC7EAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABhkyV
xUm152iAZWtFazNp2iGhm1Vss8uP3aevnKrNntqLdelI7VRHRnrX/HRjx/tZREVjZXeybW6KbWZt
pCZ6S08tN7Nmbb7zCrJtyoS5145bSx5mWafelr3tsKmS/o08uXyhlly7RPV2+AcBnPNdZrK+53pS
fP4ytnPVda4y4BwHxOXV6uvu96Unz+MvVxG0bQRG0bR2G0nHLb2gCUDX12LxtFmpHeazt82wT1gH
mMN4tWs+rcr2aEV8DU5sM/cvO3yb+O0csLUTSdrLphRE8tlkZI7Atr2ZMazDJVKTYSCawi7Ksq7z
1QERvLK3ZGPrKbyCrbdnMcsbeaa18/RhvvM7oGEwTG0JmYYTIML22a2e28xELM19oURPNO4lOem+
n3ZY5+prVnMc2GYU4/L4A0a15cNf6rz/AC6fC6+NxCPOuOu/5tHJTbHj+F5/l1+BYumXJMd9o3/d
MRXYASgAAAAAAABhlxUz4rY8lYtS0bTEvH8R4ffhmo6bzhtPu29Pg9mq1Gnx6rDbFmrzVsizq2df
zXkMWTeIbNL7tbXaHLwzUctvexWn3bmPL8WFnHVL326VZ91MfFVjvvVlz79kLrcf2m7j7bNHH3bl
J2SirLQoy4t1++7G0dBC/RanxI8PJPv18/WG241+alovSdrV6w6mDNGfFF4/OPSW2b1zeTPL1aAs
zAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAVZ9RXBTe3WZ7R6iZOpzZq4ac1p+UermZMl89+a/byj0Ra9815ted59PQ32hlrXXRjH
DpCLX6ML5NlNsm/ZRqstfdXzbsZt06sLZNvNB1Za8RDWyZdo7q8udq5Mu/mIMt4md2lmy7JzZuWJ
dHgfBL8RvGo1MTXTxPSPx/8AstJ1XWpIs4BwSdbeNVqq/URPu0n73/s9hEREbRG0QUpWlYrWIisR
tER5JbSccur2gCUAAAAPM8Sry8Uyz67fwuxbzVPGsE49XGbvF42V4M0TEL33ERnktsxpk3sumK2j
admFdPFZ33VS2Mdui2J3UU6LYlFSsN2O5NkCyJ6K7T1TEsbAsxdpReerKkTFGMxvYEz0rsqtbbpC
b2VT1QEzuwtbaGUxspuJU3neWdKoiu8rq12gCI92YatLcublnzbEz1aOptyZqTuDHLfxN6R0+t5X
qdJhjBp6UiPLeXl9NSMnEKxHa1+bb8nrlvxUAAAAAAAAAAABTqtNj1eC2LLXeto/R43VabJw/VTh
ydY+7b1h7ho8V4dXiGlmvbJXrS3xRZ1fGv5rzeHN02bEW3cys3xZJx5ImtqztMS3MeTeGFjqlb2O
8btql3NpbZtYsnSBLeiWfdTjtutid+ghherHS5p0+f3vsX6T8Fkw181d4lMvEWdnHaGnw/UeNh5L
T7+PpPxbjdyWcvAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAo1Oprgr63ntAmTqdRqK4K9etp7Q5d7Wy2m953lNrWyWm953mVd77R0
Za1104xxlN9lV8qnJl2a9s3xUXX2ybsJyRDWtl3YWydEC+2VRkzeW6q+T4tbJm+KRdfK1cmWZnlr
vNp7RC/R6HU8SycmCk7ed57Q9ZwvgOn4fEXtHi5/O9o7fJaZ6z1uRyOEezVstq6jiEbV71xevzer
rWtKxWsRFY6REeSRrJxz22gCUAAAAAANbX6aNVpL0npMRvWfSXlKamsRMVvXm+EvZXjmpaPWHzfL
oNRjzXicfWJ8phfPxFejx72x7xMzK+sXiNoiXlq+Pi6fWV/VfTNqfLJl/WTg9Pji8R70LqvMV1Gq
j/zcv6yz+lanzzZP1lWpelTET6S81Gp1P/Gyf90s412rjtnyfqql6asREdWM9+jz9eJ6yP8Az7uh
odZqMt458tpB1JvEViI3/RhzRt13/R1MNaziiZiJn5K9ZNceKZiIiQcu/WekT+iYrWI3lzdTrs+8
8uW0fJzcur1Np/zsn6g79phVaIeetqNR/wAXJ/3SwnUaj/i5P+6UD0ldonum161h5mNRqP8Ai5P1
lNtRqJjacuT9Qd22WN5aGeZyZd/KHJy59RHbLf8AVq31Gp/4uT9ZEvS8Lr/vSs2npzRtL1z53wK+
oza/HW2XJNd99pmX0Rb8VAAAAAAAAAAAAAAcHj/C5yV+l4I9+v24jzj1cLFk8nu5jeNpeW41wmdL
knU6ev1Vp96sfdn/ANFdTrXG+eq1q5F2LLtbZoY8m8d11bbSydErsYsm+zZrO/zcnBm226uhiyRK
EtrvCrJDOJTeu8A1MWX6Lqq5N/dnpb5O5ExMbx2cPNTeJb/DM/iYPDtPvY+nzhri/jDy5/W6AuwA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAa2p1UYo5adbz+xbxMlvqJ1OqjDHLXree0ejmzNrWm953tPmTPWbWneZ7yoy5YhjrXXTjH8s75N
mtkyxt0VZM2/m175N1V03yTKubMLXVXybeYLLX2VXy7eam+b0bOg4VquJW+rry4/O9uyZOq3UjVm
9r25axMzPaIdvhns1kzbZddM0p5Y47z8/R2+HcF03Doi1a8+Xzvbv+TotJnjDXkt+K8ODHp8cY8N
IpSO0RCwF2YAAAAAAAAACvUZYw6fJkntWN3k8dfHz2vLucdz8mkjFE9bz1+UOZosX1UzPm0nqI/W
MYo9FlcPNklfFGeH/NshLGun+Cz6PtHZtVZWlRLS+jxPkRpIn7rdoupHTdA5s6SI+7H6Mfo+32Y2
+To3neSIiZ7A0IjPXpXLePlMotGW3272t85datKzHZjbTVnsDj+FG/2Y/RlGP4R+jo20u7H6N1Ql
o+H8I/REY957R+jpfReiK6eOYHLtj2tttH6KrY/6Y/R2c+kjeJiFVtLG24hxpw7/AHY/RRkw9O37
O99Hrt1YX0tfOBLjcGp4XF8c+u8fs9c4dcVcGemSI61nd3IneN1orQAAAAAAAAAAAAABFqxes1tE
TE9JiUgPKcX4RbRXnNgiZwWnrH4XPi28PdXpW9JraImsxtMS8pxXhF9DecuGJtgmf+1TWW2N/la1
L7N7T5e3Vy6W3hsYcvLbqzbO9jvvCzvDR0+XeO7crO6FmGSvRThy/RtVXJ92elvk2rRvDUzU7pl4
izsd2J3jeBpcNz+Lg5LT7+Pp+Xk3W7js5eAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADs0NTrN96Yp6edkW8Wzm6+LNTq4pvTHO9vOfRoWtt
1mes95YWvs1s2fZldddOczLPLn2ju0MmebT3YZc2/mpm3qqllN1drsbZIhr3yzvtHf4AsvlYYseb
V5Yx4KTe0+UQ6nDvZ3UazbJqd8OKeu33peq0eh0+hxcmnxxWPOfOfm0mP+steT/ji8N9mKY9suum
L37+HHaPm9DSlaVitKxWsdohI0Y22gAgAAAAAAAAAABXnyRhw3yT92Nwef4xm8bVzET0rPJH5d12
CvLhho3rN9RWs9Z23n5y6O21YhrVYbdGOCfrrLPJRpv863zVS6FS09SvZj3lVZZRdPSqmnSWdrIE
ebOkK4ldTsgW1WKqd1oMZhEVZyRAImOjGI6rJ7IiATNd46qL02bHkiaxaoNGY2n4ImPgtyV2n0Vo
Gvlx7x2beiyTk08RPevSVUxux00+Fn2n7N+n5rRFb4AAAAAAAAAAAAAAACLVres1tETWekxKQHlu
L8InR2nPp43wz3j8P/s5dLveWrFqzW0bxPeJeV4xwmdFec+CJnDM9Y/CrY1xv8qvTZ+WYdbDk5oh
5zHk283U0eo3jaZZ2N5XYjrCnLSJhOK+8d1kxvCqzSwZvousrb7k9LfJ3nB1OLeJdLhufx9LEWn3
6e7LXN9Ofy5/W4AuxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAETaKxMzO0Qi9646Ta07RDmZ9VbPbaOlI7Qi3i+c3TPUaqcu9adKfy0722ZXvFa9
XO1OrjrESxt66ZJmcjPUanlidmhkzTZVfLN5VWvsC2b7R3U3yqrZZtO1esz2h2+F+zWTUcuXXTNM
feKR3n5+iZLVbqRzNJo9TxHLyaekz62ntD1fDOA6fQbZL7Zc/wCKY6R8odLBgxabFGPDSKUjyiFj
SZkYa3aALKAAAAAAAAAAAAAADQ4pl2pTFH3p3n5Q33E12Tn1eSfKscsLZ+orS00eJqbW+Lfnu1tF
XaJnZsz3WpCfsyp00fWSvmPdVYOmSUDd8kR3InoQosy7JmUX7MdwZ17ro7KKT1XRPRAsrO0rYndr
79V1ZBaQiJ6JgCSIJASwrO07MpV2nqBlrv1a1o2bf2qtfLXaQUTO0sb05o3jv3ZXhjS20xEphW5h
yeJjjf7UdJWNKLziyRePsz0lux1SgAQAAAAAAAAAAAAAADG9K5KTS8Rato2mJZAPIcU4ZbQZuekT
OC3afT4NXFkmlntc2GmoxWx5K71tG0vHa/RX0GpmlutJ61t6wrY2xr8dXS5uesN+tt4ef0eaa223
2dnHk3juyreM81OaFGiy/RtZET9jJ7s/2bdutd2jqKeic3iNTsd8a2h1H0jTVtP2o6W+bZbOO+gA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABje9cdJt
adohGTLXFTmvO0fy52bJfU23t0pHaqLeL5xdK9Rnvqb+cUjtCi94xxvK3JetKuHrdZvaa1ljb10y
cnIs1Wt3naJc++TmVWvMz1YWybfMGdsm3eWek0mo4jm8PT0mfW3lDf4V7P5tdMZdRviwfvZ6/TaX
DpMMYsFIpWPTzXmf+steT8jn8L4Dp+HxF77Zc/4pjpHydYGjC3oAAAAAAAAAAAAAAAAADG9opS1p
7RG7zszN6WtPe0zLua+3Joss/wBOzhzG2OsL5+IrY09dsSyYRijbHEMvOChb7KjF0yS2LQ169Mso
S24noyrPVXWejNVKbTuw3T3REdQWU6LYlVvsyiUDPfqupPRr79VuOQX1lZEqoZxIMksd0gT2VT0l
bPZVbuCaW8i8bwr32WxbcGnkjaZa9p2ndv5qbw5+aNugLItF6TEtvTX5sMb969HMpfazc0d9stqe
vVZDdAQAAAAAAAAAAAAAAAADV1+iprtPOO/2u9bektoB4TJTJpNRbHkja1Z6uto8viVht+0HDvpG
H6Tjj6zHHvbecONw7Ltfkmeqmo6Ma69DXbbZTkr1mGWO3RneOaGbZRoM30fVzSelMnT83aef1FZ7
x3h1tBqfpGnjmn369LNc3sc3kzy9bQCzIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAa+q1dNNXr7157VhGp1Xh70x+9f9ocy283m1p5rz3mVbrjXHjt91lz
5c9+fJ1nyjyhdM8lZlOOIiqrUXikd+kMreunnI5XEdX4dZiZcG+XmtNl/F83PeeWWHDOGanieSKY
q+5H2rz2hMzWd1Iqx1yajJXHhrNrW6REeb1nCPZumn2z62Ivl7xTyr/6uhwzhGn4Zj2xxzZJ+1kn
vLoNJnjHW7TbbsAszAAAAAAAAAAAAAAAAAAAAaPFrbaSK/itEOXt0rDf4xb/ACa/GZacRvaF58Q2
IjasQnzPIhCU92tMbZGzHmotG10C6nZkwpPRmipIllEbMIZIE7solgmJBnCyk9VMM6z1BtVllEqK
z0WRILYlluriWcSDJVbusV27gwInaSWM9ECyZ3hqamnSWxFmOSOaqRx725bNnSZNs9J+OynVY+WZ
YYr7TE+nVaIr0Ais81Yn1hKAAAAAAAAAAAAAAAAAABExvG09peU4nov9n66L0j6q/WPg9Y1OJaON
ZpL0+9HWs/EWzeVz9PbmrEtnyc3h9reHy26TWdnSr2YX6657ijLXpLX0+onSamL/AHJ6W+Tbv2aW
ekTv16JzeI1Ox6KJiYiY7Slz+E6jxdN4dp3vj6fl5Og2clnKACAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACZ2jeQRMxEbzO0Q08uqtkma4ulfO3r8lefUePMxWf
cjy9WvlzVxV6T1Z61/x0Y8f7Wc7Ur1lqVy+LqOWJ2hp6rXddon5rOF1tfmz5OkT0qzb8dWbxjp1c
biuuilJ5Z6r+IcQrixzEy8zl1E6rNt1tMztFY81sztU1eRucN4ffi2p5esRM72n0h7rS6XFo8FcO
CkVpX082nwXh3+z9FWLxHi36328vg6TZyW9ABAAAAAAAAAAAAAAAAAAAAAADj8Unm1tK/hqppHvw
y1k8/EMk+m0GOPeafiFpCZYwolnXspvHvLa9mF46gmnZmwozRUiUCBKYYsoBLOFbKAX0llEqqyzi
QXRLOJVRLOOwLIljZMEgrlhKyYYTAK5nZPN0RZjugUanHzVlz6xtLq361c+9eXItPpXX0dubTU+E
bL2lw2++O1fSW6m/VYAISAAAAAAAAAAAAAAAAAp1GbwcfTreelYEydcuMcRrM/L9nnlsV6wqpi2r
tv133mfWVkRyRtEdGFva7MzkYZNoamWN4bV4mYa9qztKIujhVppxGI8r1mJegeZpknBqKZY+7L0t
LRekWrO8TG8Ns/HJ5ZypAWZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAADS12fp4VJ6z9qVuq1HgUiI+3bpDl589cOKZmevqprXPTbx477rDJlrhr1nq4+s182tMRP
RqaziXiZJrWekNG17ZbxWJ336M5LXRbI3dLTJrs07RMY6fan1dHLrowY+X7MVjt6N3R6Kul0EbWm
s7bz8Z+LnabQX43r7Y53php/mXj+Dnv0f1JO1x/8ZxbUzj02O15mfLtD13AvZqnDds+pmMmo26el
XX0Wh0/D8EYtNjilY7+s/NstpOOTW7QBKgAAAAAAAAAAAAAAAAAAAAAADG88tLW9I3BwJtz6nNf1
vK/DHVqYJ3pzT5y3MPZeojOWMQylEKpTVjZnDCwkqzYQyRRICATCITAJZQxhMAshnEq4ZQC2srKq
qrIBZCWNZZgwswmFloVyCu0dFcx1WyrtCBhv5NTPHXds2U5o3hIz4ffbPt+KHUcTSW5c9Jme0u2v
VYAKpAAAAAAAAAAAAAAAAYZctcVOa35R6tLrltN795/YvknNqrfhpPLH92V5isd9mWq6fHjk6rn0
ZxG8KK5Jm/wbVZiYZtqrmkqL023bkxvCiY3lJHNyRG81mHS4Rn5sNsNp64+3yaWaNrzOzHBl+i6q
mT7s9J+S+ay8mex6EIneN47SNXKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAImYiJme0JafEs3h6fkidrZOn5eaLeJk7eOdm1Hi2vmtPTry/CHmOJcUvmvOPF1n09Pm
6HF9ZGm01qxO3R5vSY7XwzmzTy47zzTEd7en5Mfvt2/PURWdo3tvPrPlKymbktFqTtMTvHzbOLDG
f63JXbFX7FdnoODcDprZpq9TjiMMTvSn4vj8l5fxnrk91saPSa7i2hpOfbTVt5x1m0fLydzR6PDo
dPGHBXasd585n1lsRERG0dIF5OOe6tAEqgAAAAAAAAAAAAAAAAAAAAAAADX11+TRZrf0y2Gjxe22
gtH4piP3TPpXKwxtjhuYo9xq442iIblI2pC1RET2ILd9kxCqRjZmwlCSEohIJAQAAJZISDKGUd2M
MoBnVbVVCyAWVWeSuqyOwIlXZZKue4MJV2WWYT2QKbKL9YlfdRdIo35b7/Hd3KTzUrPrDh27uxpb
c2mpPwX/ABX9XAKpAAAAAAAAAAAAAACekTIp1eTwtJmv+GkyJn1oafeazbfpMzLR4jq/o8b823zX
6XNF8ERCvTcNpxLV5LauvPhx9Irv3lhztdtv8TtaWLicXrt03jzjzb2k1nid56ty3s/w+a7Uwzjn
1raejlarhmbhl/FpbxMO/fzj5p/ixSeXOvTtRfeI280ZI26tfDm3pWe63LaZx7qtGvniJ6tPLvOK
fOa9WzbJvTbza02jl3n5SSljscK1MajSxWZ96nSW88xw/VfQ9XMT9nfa3yemid43jtLeXsce88qQ
EqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADia3UTm1l4j7OP3Y/u
7Vp2rM+kPJW1PhYcmS0+9MzKm/jbwz31weMzbV8UppazPL9q0/BF4rk1GLDSNqxPWPhCnHmnNrtT
qPKteWPm6U6OdHaZvO+SaRNvhv12Ub/q3FhtrNVj0uKOt56z6R5y9zix1w4qY6RtWsREOJ7L6OKa
S2rvX6zNM7T6Vh3mmZyOfya7eACzIAAAAAAAAAAAAAAAAAAAAAAAAAAczjVvqMVfW/8AZ03I41bf
Lp6/OVs/UVrY47NyOzUxd4bUJpEbb3Z7IiOrKIVSjZhMLJYyhKIgmGUQSDESIEbJEgQmCITEAmGU
IiGUAyhZVhDOoM4Wx2VQtqBKuyyWEgqlhKyyuyBVaGtkbNmvk7A15l1eH2300R6TMORPSXT4ZO+O
8fFefEX63gEAAAAAAAAAAAAAAAq1WPxdLlp+Kkx+y1Fvsz8gjhaDauGK8sx07y3OE3m1tT6RaP4c
vU6yMNKUx73zT0ilY3l2eF6a+m0kRl/zbzz3+Ez5M8z26fJruW6wzYq5sV8d43raNpZjRzPPaTmx
5b6bJ9rHO3zb2WJ8GWPEscY9bgzxH2t62n19GWW0eHOzHU5XbjXZ1x8WTnz2iZ7S2M1IjH2+LX0V
KTqs8zO9ot0j8nUthi1J3UaOFMTfLFo6xMbS9BwHWTqdHOO8+/hnln5eTjYMFo1WTH5VnePzXcIm
2k4zlpPSmXy/hfF5eMfJns69OA2cgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAADG/2LfJ874rW845mubliY7bPoto5qzHrDz0+yePNF41OotaJ7RWNtpV1OtfHqZ715fhu
j8adNpcVfeyzE2/vLuanhOu1nEctIxTTFa/+ZPbZ3eHcF0vDbTfFE2yzG03t32+DokynXl9+leDB
TTYKYccbUpWIhYCzEAAAAAAAAAAAAAAAAAAAAAAAAAAAAcXjE/4zDH9M/wAu04XF5/3jj/0f3Wz9
RUYmzDWxS2I7FSyjuzY1ZKpRKEygEwiWUIkGIk2QJNhKQhMIhkCYZQxhlAMoZwwZwgWQshVCyATL
CWc9ldpBhZXLOVdpQK7NfJPRdaWvknoDVvPvOnwuel4+TlXn3nS4VPvXj4QtEV0wAAAAAAAAAAAA
AAAAAVV02CmTxK4qRf8AFFeq0AAAanEsfPpZmO9Ji0NDLfkwdOsulrumiyzHlVzJrz4Ovoy26vB8
cTBa9NffLtMY77Rv8Yegx5ImkKdJoY1HC81Y+3OSbVn0mGGkmbY45u6tnrrTOu2xGO0RxCd+nNVj
qKxTV1vH2pjaGtnyzXXYdo96ZmGXEMk15b7/AGZiVerWPTYckZcNbx5wzc7hGbnxXxzPWk7x8pdF
0S9jh1OXgAlUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAcPjEf4/FP9H93ccXjMf4vDP9Mx+62fqKrx+S+GvibEFSsqyYwlVK
ZYsmIMoRKYJQIPIEiQ2ATCUQygCGUIhMAyhnDCGUIFkLIV1ZxIMpVWWSrsCuyqyyyq09ECq8tfJK
66jJ2Bp5J6upwn7dv9Lk5J951uE/av8AJaIrqAAAAAAAAAAAAAAAAAAAAAAq1Mc2myxPnWf4cmtu
XT9fR0tffk0WSe28bfq5Wbamm3326MtunwfK6PCv/AxPraZ/dz9PO97/AOqf5dHhdZrw7Dv3mOb9
XOxRFM+avpe38mvkPHf/AFWlrKba7Tzt99ZxKkfR7euyNXMTrtPHfa0z+zPiM/UR8Zj+Wbdu8HpN
M2bfzrV13M4dO2pyR61dNvj44/J/oAWZgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADj8bj63BPzdhyeNx0wz8ZWz9RWri7Nmv
VrYu0NmqaRZHZlDGGSiwxZSgCEkCBCQSCQBMJRCYgEsoYx3Z17AlMIhlCBnDOGEM4AlhZZKq4KrK
7LLKrIFN2vdfZReAaObu6/CO9vk5OePR1uEd7fJeIrqAIAAAAAAAAAAAAAAAAAAAAGtxCk5NFliI
3mI32+XVyNTyZOHTee946PQKPoeDffw4777eW/yVs60xv+ZxOnr4Okx1t05KRv8Ao41Z5q3yed5m
XY1szXRZ5jvFJ/hxItP0aOSN9q7yrtr4f2tHFM5+KT16Yq/vK/iGSbXw4vO14UcPx5MGfNbPG18m
1oj4THRsTw7VanPXVYpi3gzMcnrvCnG11JOupwuN8+a3pEQ6jT4divjxWnJExa09pbjbM5HHu90A
JUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAHM41H1GOf6nTc/jEf4Ws+lls/UX45uGekNujTwdm5RNIthKIZKLDFlsiQIShIC
EgCUJ7AmGTGO7IDzZQhMSDJMMYZQgZwzhhDOATuqssmVdgVWVWWyqtCBTeVF19lF+wNLNG7q8I+9
8nLyupwnt+S8RXUAQAAAAAAAAAAAAAAAAAAAAAAItWL1mto3iY2lyrcLyUxzix2ia2nvPeK+jrCL
OrTVnxpanhuPPemSs8l6RtE7dJj0ldpNP9GwRSZ3neZmV4cR/Vs4AJQAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANHi1d9H
M+kt5ra+vPoskfDdOfqK4mn7Q3aNHBPZu0W0RdDOGFWcKLCJZeTGQQlCQSgASBsCYZQxhlAJTAmA
TsmAgGcM4YQyjsgRLC3VnaVcgwsrt3Z2V2QK7tbJ1bN5a9waeWO7p8Knt8nNyebpcK8vkvlFdQBA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAK9RXmwZI+ErEWjesx6wQeZwejeo0cccuW8
elpblJaaRGxVnCuss4ZrMvJEgCAASISCQIBlCYYpieoM0wx8k7gzIRueYM4Z79FcSy3QEsLJmWFp
BjaVVpZWlXMoGNmvkXXlr3kGtknu6XCf7OXkl1OEdl8orqgIAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAHmskcmtzV/rls0U62OXiWX4zErcc9GmkRfWVkSqqziWayxCPIANwBIhIJSxS
CRG6dwZwlhEs4BluMdzfqgZxLLdXuy3AmVdpZTKuZBjaVVpWWV2QlhZRdfZRcGpl7urwfrzfJy8r
rcH61vPyWitdMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHA4nHLxKZ9awnH2ZcY
jbW459aq8fZpfiI2IZwrqzhmsz3Ebm4JN0AMhCQSIASndiAziWUSriWcAyRujc80DM3RCfIETLCW
UsZEsJYSslXZAwlTddPZTkBp5e7r8Gj6rJPxhx8k9Xa4PG2C8/FaK10QAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAcfjcbZMFvnDWx9m5x2PqcNvS+zSxT7sNPxH62YZQwqzhRZO6UCB
KUAJTux3SDIRuAncQAmJZRLBMSgZ7iIAZRKd2DICUSlAljLCYWMLIFVukNfI2bNbIDTyT7zu8Ijb
Sz/qcG/2nf4T/wCE/wD2WnxWt4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHL9oL
+Hw2cm28VvEuPptfgyVj6yIn0no7/FtJfW8NzYMe3PaPd39d3iMug1WktNc2C9dvPbeP1aZ9xF+v
T471tHu2iflK2HkqWmvaZj5Surqc9Ps5bx+alTHqYHm68S1Vf/NmfnC2vGNTXvyT84Ql6A3cSvHM
sfaxVn5Ssrxyv3sM/lKB1xza8bwT3pePyWV4tpZ+/MfOEjfGrXiGlt2zV/PotrqcN/s5aT/+wLRj
FontMSlAlKEgndO6IAZQljDIEgeQljLCzOVdkCu/SGrkbF56NPNeKxMzMRHxENe0+89DwuNtHHzl
5PJr8NcnLW3Pbf7r1nCZm2gpae8zMrz4i/W6AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAETETG0xukB4HVaeMHEtRi26RedvkyjBSfX9W77QYvC4xz7dMlYlrU7M929dWJLFc6aPK0q
7YLxPS0S22FlP6q38Zac0yR92s/KVc3tHfFf8tpbcsLRvB/dR/8ALLVnU0r9uL1+dZI1mnmdvGpv
6TOy6ym+Oto2tWJ+cJ/tW+KLK5KW+zes/KU7tG+h01p64qx8Y6NXNo6Y+uPJlp8rLf0rfG7MXtHa
0x8pZxqs9e2a8f8A7Oj7HaTHn0+f6RWM23LETfr6vRW4PoL99NT8ui7F4+vEdXXtnt+fVbXjGsr/
AOZE/OsPS29nuH27YrV+VpeV9pdPXhOtw49NG9Mld55+vXcTPd42I47qo7xSfyWV9oM8d8VJ/VxM
d8l46xWF9cV7en6o/qLfxp2I9ob+eCv/AHMo9op89P8A/wBORGmyT5R+qfo2X8P7n9Q/jTsx7RR5
6ef+4/8AuHftg/8A6cWcOSO9J/WEbWr3pY7Efzp2Lcfv5YK/9zWy8d1E/ZpSv5Oba1/+Hb9lc+LP
bFt87I7E/wAabWbiurvEx4nL/pjZzc2bJkn372t85ZXx55/BX85lucC0vPxnTxlnnjm32mOiZqUu
LJ2p4TwnVavNWaYbRTfre0bQ99pcH0bT0xb78vmtiIiNojaErMwAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAHnfarF7umzRHaZrLjYrdIen9ocPi8JyTt1xzF4eUw23rCm3R4r6bMy
wt6kdTaWLdjswmNoZontsCm0K5XWjopnuDC0dGpqG5bs08/daKV672MjbSaif6oh6Z5f2LtvptRX
0tEvUN3Jfo8f7cYve0eX4zV7B5z20xc/C8eSPuZIRficfXlcPaG7ino08HWIbePpLF2NuiyOyrHK
3fZFSwuovHVfaVF4QK5YWTM9UT0EKry6Ps1Tn4zjn8NZn9nOtLseydObiWW34cf918fWfk+PYANn
KAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAq1WKM+ly4p+/WYeBxTNd6zG0xO0
vobw3FcP0bi2em20Tbmj5Srr418V9sa2Z7qKyzi07MXUylhaU7yjqhLCeiq3ddaFNxFYW7NLNG8t
zya+WO6Va9J7FW66mvwidnrXiPY3Ny8RyUn71Jj9Ht3RPjk19HK9pMHj8D1ER3rHN+jqqtTjjNps
uOe16zAifXzfTz7kNyndpYazS9qT0mszDdoxrsi6m8LazMq6zDOsq1ZEyrt1WWlXaUCqyq0rbKbi
Fdp6PReyFd8uqv8ACsfy83aXrPZHHto89/xX2/SP/dpj6y8vx6EBq5gAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAB5n2q03LfDqqx39y39npmlxbS/TOG5se29tuavzgWzeV4mtui2
O3RRSY2hdVhqO2MvI36iu9lUsrSrvDHn6spnmSiq5jooyV6tq1VV69RC32byTh43h8otMx+r6I+Z
aK/g8TwX7bXh9Mid4iW+fjl8n1ICWb57xLBOm4zqse20Tbmj8+qKdnS9q8PhcTw5tumSm0/OHMxz
0Za+uzx3sX1t0Zxurr1ZxvspWiZYWZbsbT0QK7KLrZVZJFaqt5vbezNOTg9J/FaZeJns93wCvLwb
T/GJn92uGHldIBowAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADuAPA67F9H4l
qMW20VvO3yRWW97T4fC4rXJHSMtI/WGhVlue3b473K2KzMML4+62tujG9pnozXaOSOVFMnVbmq1t
trJRW5E7wwvUxTvCyY6CHOt7moxz6Wh9PxTzYaT61h8x1MbZK/OH0zTf+Fxf6I/htj45vL9WgLMn
mvbPFvocGWO9L7fq85p5maw9d7VYvE4JkmPu2if3eW0+PasdFNOnxfF1Y2hlykRsmY+LJ0MZjZXa
eq2eyi8oQTO0KLdZWzPRjWu6VaqtHR73g0bcI0sf0Q8Nkq93wqNuFaWP+XDTDDytwBowAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAef9q8HNpcGaI60vtPyl56k9Iew49j8ThGe
PwxFv0l4zH2U26fDfTYiyJljvsjf4sm6vJ1hrXjq2MkqLdZEVbgbMx0auGdmzNt6iHN1Ub5af6of
TdPG2nxx6Vj+HzaaTm1+nx/iyVj930ysbViPRrj45vL9SAuyc7j1efguqj+jd4/T33rD3HEcPj8O
1GP8WOY/Z4TTT7sKadHhbcsZnaCJ3TPZk6VdrKbTutmP0U2nqgrGOsr8deiuI2X09EqKM1dt3uuG
f/jdN/06/wAPE546S9rwud+Gaaf+XH8NMMPK2wGjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAABrcRp4nDtRWPPHP8PCYusPoWSvNjtX1iYfPuWaXtX8MzCuvjfw32siu8ptXoxi
0wy5t4YulReqmazu2skbquURWFInddM7VYRGyL291KFnCcfj8e0le/Lbmn8n0N4b2Ur4nHLWmPsY
5e5a5+OXyXugBZmiY3iY9Xz7NjnTa3Ph/BeYj5PoTxftFg8Hjk2iOmWkW/Psrr418V5WrWd2faFc
V2jdnEMXWxntupmN7NiYU27iWML6dVMVnddjgVqMsdHr+CW5uE6f4Rt+7yuSsTDv+zWXn0WTHP3L
/tK+GHl+O0A1c4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8Dn93W56/wDM
t/L3z59qp24jn+OS38lnpr4r7ZxHQ2TEstt3PXUrt27K57rr1VT0BjKnJPRbMqMs7QlV2fYvHvrd
VknyrEfu9m8f7FZI8fVU85iJewbT45NfQBKo817W4eulzxHaZrL0rje09ItwqbfhtBVs3leai8RD
KLw1sduesL606dWFdsZT1jdhNeq6K9DlhCVUU6s4jZnt1YzAhnM71dH2bycmszY/K1d/0c6OzY4R
fwuK4p8rTstn6z8k7HrwGzkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHz3
Vxvr80/8y38voTwGpj/F5/8AqT/JfjTx/WVeyY6FPspc9dZPVXaOq2WEwIUTVRmjo2rNfLHRI3vZ
DJycXtX8dZh7t879nsnhcbwz23tt+r6I2nxyb+gCVBzuPY/E4PqI9K7ui19fTxNBnp60n+Aj5/pJ
3jZu1aOnnltMNussdfXbm+l3ZM9URHREdZVXTuT1Nk7boQiOkJw28PU47/htEp5eivJPLMTCZ9Vv
x7mJ3iJ9UqNHk8XR4b+tIXuhxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD
weqjbWZ4/wCZP8vePCaz/wDIaiP+Zb+UX408f0r9lOxWOifJhXWjfyYWllPRXYQxnrCrJHRd3YZI
6A1NJecHEsN/S0T+76bE7xE+r5dk93LW3pL6ZpMni6PDf8VIn9m2fjm8s9rgFmQxvHNS0esbMiew
PnHLyai9fS0w2aNfUTtrs3+uf5bGPqy068fF227KtSsdFlKqNGMV6myyY6sbdIQI8tlOWOi6Jhhk
j3RD0vA8nicMx9etZmHRcT2Zyb6XNT8N9/2dt0T449T2AJVAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAHhdfG3E9TH9cvdPEcXjk4zqI/q3L8aeP6xr2TsxpLOekMK6mFo6qpXSrm
OqBixvHSVmzC4OfqK7S9/wAByeLwbTW9K7fo8Fqo6Paeyl+fglI/Da0NcMPK7QC7AAB8313TiOf/
AKk/y2MHWrX4jG3E9R/1Lfyv0/aFNOrHxuU7LI7MMayGTVlHWUXhNe6Z6wIUsb9d1m20q7dkDpez
N9tRqKT5xEvRvKez9+Xis1/FSYerb5+OTyf6AFlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAB43j9eXjN/jWJ/Z7J5L2mry8Upb8VIF8f6aGOey2eynHvOy7bowrrYSxZSwQJ2YXZ
92N4BoanrEvVexmTm4blr+HJ/aHltRHSXofYm/1Wrp5RaJaYY+X49WA0c4AD51xONuKan/qW/lbp
+0MOLRtxbU/9SU4J7KadWPjep2WQrr2WRPRk1TvsndXMpiRCb9FNu0rbTuqvKBscCjfi9PhWZeue
V9n434rafTHL1TfPxy+T/QAszAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHmv
avHtfTZfnV6VxPajHzcNrf8ABeJFs/XnMcr4no18c+6vr2YadkY2YM57sEDLyY37Mo7MMnYGlqO0
vQ+xNfqNVb1tEfs87qZ2rL0/sVX/AHdnt65P7Q0wx8vx6UBo5wAHz/jUbcX1PT78qtO2vaCnJxjP
8Zif2amnnspp04+OjWejKJ6MKdmcMmyJn4m5ZHzEVPMwtJv0VZLbQDqezcb8RzT6Y/7vUPM+ytZt
n1OTyiIh6Ztn45N/6AFlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABocbxeLw
nUR5xXm/Rvq8+OMuDJjntaswEeBxT0bNZ6NatZpNqz3rO0rqsdO3PxlaWEMpY+aqWXkryT0ZT2V3
7A0dVPuy9f7G124NM/iyT/Z4zWT7sw957MYfB4Fp4/FE2/WWmGHldcBowAAeM9qKcvFeb8VIly9P
0nq7ntbTbVYL+tJj93CwT76unR4/jo0nozhhTsy3Y1sWljM9Ce7HyQIm3RRlttVbaWrnt0Sh6n2U
x8vD8mSfv3/h3XN4Bi8Lg2nj8Uc36y6TeOPXugCUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAPD8RxeBxXUU26Tbmj8+quro+02Lw+I4ssdslNvzhzazvDPbq8d7GW7Dfqz2VzG
0s2qd+iu/Zn5Ksk9BVztX1mI8930zh2LwOHabH+HHWP2fNYp4+vwYvxXiP3fUqxtWIjyjZtj45/L
faQFmQADzftfj3w6fJ6WmHmsP23rvaqnNwqLfhvEvIYZ+sV038bo0noy36MK9oZQxrdMyrlnMbMZ
QKrS1M07zEestq/RRjr4utwY/wAV4j91p9V18fQdJj8LR4ccfdpEfsuREbREJbuMAAAAAAAAAAAA
BAJAAAAEAJEAJQAJQAJEAJQAJQAJEACUJAQlAJEAJQAJQJAAAEAJEAJBAAAJAABAJEJAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwvanDzaPFmjvjv8A
tLztJ3h7HjGHx+FainnFeaPnHV4vFbeIU038VbHeGF+kso7Mb9mTdhKnLK3dRm7SIrHhGPxeP6Sv
9cT/AHfSnz72Zx+J7Q45/BWZ/Z9BbZ+OXyfQBZQABzeP4/E4NqI9Ii36S8Ng/wAx9C4jTxOH6ivr
jn+Hz3B/mQi/GvjdCnWNlsdI2V07LIlg6USrt2ZzZXMoFV+zPhGLxeOaavpbm/RVltEN72Yx+Jxm
b7dKUmf7L5+s9/HtRA2cqRACRACRACRACUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAACQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQCQQCRACRACRCQBCQBCQB
ACRACRACRACRACL1i9LVntMbPATTwdRkxT3pea/u+gPE8Xx+DxrPHlaYt+qNfGvjvtXXsi0dOrKk
dEXjZg6VMtbP2bMtXUdpEV0/Y2nNxbNf8OP+727xvsXH+N1U/wBEfy9k3nxyb+gCVQAGOWvNivX1
rMPnGGOXNNfOJ2fSZ6w+dZKeHxDPX8N7R+6L8a+L63KdoZ7q6zvEMpnowdKJ6ywmWUyqvIKM0vQ+
x+D6rU55+9aKx+TzWa36vbezmDwODYenW+95/Nphj5L6dQBo5wAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAEiAAAEoA
AAAAAAAAAAAAAEAkEAkRuAkQbgkQAkQAkQAkQAl5T2nx8nEMOT8dNv0l6pwfarHvpcGWPu32/WCr
YvK4mOem6b9mGKd4Z3idmFdka0y1c892zfpMtLPaNpEV6D2Kj/Eauf6YeweQ9ieuTVz8K/3evbT4
5NfQBKoAA8FxCvJxrUx/XMvevD8Zry8fz/Haf2RfjTx/6RSOnRMyypHu9kXjowrqVSrvPRnZVl6V
kK0775MsUjvadn0nT4ow6bFijtSsVfPuFYvpPGtNTy54mfy6vorXDm8l9pEC7JIgBIgBIgBIgBIg
BIgBIhIAgBIhIAgBIgBIIBIAAhIAhIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJAAAAAAAAAAAAAAA
AAAAAAAAABAJQkAEAAAAAAAAAAjc3BIjdG4Mkbo5kcwMjdhzHMDPc3V8xzAs3N1fMjmBZubq+Y5g
Wbm6vmOYFm5ur5jmBZubq+Y5gWbm6vmOYFm5ur5jmBZubq+Y5gWbm6vmTzAz3N2HMnmBlu5ftFTx
OEZJ/DMW/d0t2rxKni8N1FPWkiZ9eS08e7Cy8dGGn6UhZaJljXZGnmc3UT3dPP2cnUT78xCIV6j2
H/8A9c/6f7vXPI+w8bU1U+vL/d63du5NfUiDcVSIAS8b7RV5eOb/AIqRL2TyXtNX/e2KfXH/AHlF
+NPH/pr4+2xcxx0hFpY11K7R16KM32ZWz3UaidqSgrc9kcPicWyZJjfw6T+727y3sXh2xarN+K0V
h6lvPjj3e0ASqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJQAAAAAkQAkQAkAAAAAAAAAAAAAAA
EgAAAAAAAAAAAAAAAAAAAAAgAAABKDcAN0bgkY8xzAyRux5kcwM9zdXNkTcFm6OZXzMeYFvMibKu
ZHMC2bo51U2RuC2bom6rc3BZzom6sBZzI52ADPnOdggFnMc6skFnMc6rc3BbznOp3RzAv50c6nml
HMC/nOf4qOY5wX85zqOc5wbHOc7X5znBsc6edr85zg2ec52vzpi4NjmY5bROG+/bllVzsNTk5dLl
n0pP8BHmMHWNmzt0aum8obm08vVjfrtnxztR0mXHzTvaZdjVRMTLkZo6yiFen9iZ2pqY/wBP93rN
3kPY+/LfPX1rE/u9XzN3HfqzdO6vmTuIZ7m7Hc3Bnu8t7TR/vHBP9E/y9Pu837SV31umn+if5Rfi
/j/01MMb1hjkrtKzBG0bMsmOZY11tOYamr6Und0LUc7XT7u3rJPqL8er9lcPhcFpbzyWm39v7O00
+FYvA4Zpsc94xxu227jv1IAgAAAAAAAAABKAAAASgASgBIgBIgBIgBIhIAAAAAAAAAAAAAAAAAAC
UACUJAAAAAAAAAAAABIAAAAAAAAAAAAAAAAAAAAg3AEbomQZbo3YzLGbAz3RNlc3YzcFs2YzdVN2
M2Bdzom6nmNwW86JurTAMuY3REJ2BB1ZRVMVBhsbSsiqeUFXLucq3lTygp5TlXcpygp5TlXcpygp
5TlXcqOUFXKjlXcrGYBXysdlswiYBVMdUTCyY6sZBWxlnMMZgGLGZZSwkDdHMiWO4MuY5mEyjcFn
N1OdVzHMC3nTzqeY5gX85zqOZPMC+Lqdbk20eb/RKOZr8QybaK/XvtH7iZ9aGlp2luzT3fg19NHS
OjbmPcYX67XH1XSZ9XIzRvMuzrK7zLkZYmYnciunb9lZ5dTk+OP+71cXeP8AZnJ/ip2nf3J/l6iL
/Fu5L9bMWZczXi6YuIbEWTzKIuyiwLt3nuO25uI4a/hx7/rLuczg8TicvFLbfdpEK6+NPH/phhjo
stLGkctUWnoxrrU3j1cnWTzZq1jzl1clo5Zcu8c+txR63iP3Tn6pv4+g4o5cVI9IiGe7CJ2iE7t3
GyN2O6dwSINwSISAlAAlACRAAlAAlACRACRCQAAAAAAAAAASgASISAAAAAAAAAAAAACQAAAAAAAA
AAAAAASAAAAAAAAAAAAAAAAIAAAQCAJljuljsCJlhMs9mOwMJYys5TkBVsjZdyHICrZPKt5E8oK4
qmKrOVOwMIqyirPY2Bjyp2ZbAI2NmSARsbMgEbI2ZAMdjZICNkbMkSCNmOzJEgx2YyzljMAwlhKy
WEwCuWErJhhMArlhLOWEgxljMpljIImWMyTKJA3N0IBO5vux3NwZbnMx3NwZczT4jf3MdPW27a3a
fJOq1XNP2KdIRfi+J2trSYfcjeF+Wm1OicVeWIiN9kai8xjY12ORqultnI1Ecsujq79XP1FovWYI
rTgeq+j8QrWZ+3Mx+r2UXeC0WG2Ti2kiN5mL807eUREvbzbaejefHJv62Iv8WUXa0WTFhVtRdlF2
rz9WUXBtc7jR9dqc2T1ttHyhvZMvJitb0jdq6XHNcNenWVN3028U99WRj6Kb02be3Tq18/SN2Lpc
3UdN9nOmZrqKX/DaJ/d0svvTLRzV3jomK6+Pd1vvWJj0ZczT0mXxNJht60hfFnQ4qu3N1cWTEgs3
Tur5k7gz3N2O5uDM3Y7m4MtxBuCQASIASIASAAAAAAACRCQAAAAAAAAEoSAAAAAAAAAAAlAAlCQA
AAAAAAAAAAASAAAAAAAAAAAAIASgAAAEJAQJQCNkbMgGOyOVnsAw5TlZ7GwMOVPKy2NgY7GzIBGx
skA2AAAAAAAAAAQkBAEghEskAxYzDPZGwK5hjMLJhjMAqmGEwumrCagomFcw2JqqtUFEsLLrV82F
o7gqljKyYYTGwMZRKUSCAQAboJnaN5Bjkneu0d5W4ccViIiOzHFWbTzNumP1Zarr8eeRMbxDW1Mx
NO67NbkhzNVnmInqzaOZrL93JyZeV0M1++7S02jvxDWxhxx033tPpC8Z6rrezWjmZyazJG2/u03h
2vFibTHoqvamiwVwY+nLGzV0+SZ1Mx8G0/45tOhzJ5lXMc3UVXRdlF1HP+iYsDPLPPy49/tz1+Te
pSIr0ho6ak5Ms5J8o2q6NImOrHV7XX488ypzTtHXo0s9t6zG7c1G1qz6ubeZiZ3UatXJG3yauSO7
cvMTEx5tPLb3prPRMVr0HB8vicNxf0+7+kt+LOJwTJyY/Bnz3tH93X36N58cWvq6LSyiyndMSlC7
mZcymLJiwLosmJVRLKLAtiU7q4lMSCzc3YxJuDMRuAlKAEgAAAlAkAAAAAABKAEgAAAAAJAAAAAA
AAAAAAAEgAAAAAAAAAAAAAkAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAhIAAACAAAASgAAAAAAEAAAA
hGzJAImGMwzQDDZjNVuyNgUTVhNGxysZqDVmiu1G5NN2M4waM0+DCaN2cbGcQNGaMZq3JxMJxA1J
qx2bU4kU09slorWNwa20z02RXHbJbl26QvtFovbHWkxEdJt5y2MOHlr2U1W3jx+1hiw8vSO63lmI
XRTaEWmtY6snRHO1VpmJ+DjavpSZl2s8b7y4HFcnh0n0gha5ebJN55KRM2mdoiPN6fh+kpwXh0Wy
RHj5Otp/s5Ps1p62y31+em9aTMYt/OfVfxTiPjZ52naI7fBrI5t66xz5+a1rW7yx0eSL6iZjtEOX
qNbSletom3lENjh2fbHzbbWt3iVozruc+5ztWubf4M4ybpQ2Oboyrva0Vjza8WdDR4OkXt3n9ldX
kaePP9VtYqctYhdvt5oivTeCZ2YOxXk6ubqMfV0b9mrljfqlFcq88k7z2U5axeItDa1OPessuC8P
ya7XRWYnwqdbT/ZMilvIu4dpslNdixXja8Y5tt85djZdbDWnGOesRtXFtuw6T27No5Kx2OrKYQlC
ExKJgBnEpiyvdlEgsizKLKollFgWxLKJVRLKJBbEp3VxLKJBnuMWQJEbpBIAAAJAAAABIAAAAAAA
lAJAAAAAAAAAAAAAASAAAAAAAAAAAAAJAAAABAJABAlAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAA
AAABAJQAAAAgAABAAI2EoBGyJhkgGPKxmqxAKpownHC+YRMdN5BrTj67R3bOn01o7p01Iv71u89o
b9a7LfBTfS1vWI2jf12VfQPSW8KX2mas+NC2iv6xMNfJpMnLtEbuuxtMRCtzF55NR5rPps1N/ctP
y6uHreE6nXZ4pak48X3rT06fB7fNeI33cbX6mI32R/MWu7XF116aDSRhxbRERs8f499bkyZeeKae
kzE2mdon81/tfxDLGOunwbzlzbx08oaHBvZHJlx48mrvaa94pu04y617576rNGLRRM0397JEd/lu
9Dw/S3x4qxffo6mm4NjwUiKY4iI9Ib1dHFY6QIaNabbrYrLfrpJtaK1rMzPZb/s+05IpP59OyLeJ
k7eNfRaOc1ue32I7fGXYpi5Y77M8OGMeOKxHSFsU3Y29deZMzirl6dlVvhLatCjJHeYQv1rXnps1
8k9/VsW6qLVmZIi1rzitlvFKRvaZ2h6TSaenC9FFY+3brM+sqeG8Prp4+kZ+lvuxPkr1mqm95nfp
DXM459676a2q1dsV7XietvNno78+CJn1cjX6mOeIm0bR33dfRU5NJjidt9t5afjG/V6JZ7I2QMNh
nyo2BhsMuVG3wAhMSbbQRAMolnE+iuGUSCyJZRKuGUSCyJZK4llEgyZMYTuCUsYSCQASISAAAlCQ
AAAAAAEoASCASAAAAAAAAAAAAlACRACQAAAAAAAAAEgCEoASCAAAAAAAAAAAAAAAAAAAAAAABAAA
AAAAAAAISAIAAAAAAQAAACASgAAAQJAQAAhIDHZhln3do7z0WS18mWsajHjmes7pg3dNi5aRMNqO
yvDHTpPRaigHZhN4hHRlaVN59JY3zRENLUavaO+yq0iNVlitJ6vNcR1MVi0zO0era1/Ea0rPvbz5
PM5MWp45qvo2GZrhmfrsnpHpHzTCseEcM/2vrr8Q1Eb4qzy44nziPN63HpYiIiI7LNHoqabBTFii
IpSNohuVxrKtWMEejPwY9G1FFmHB4mWJn7MdfnIM9JpIx15to5pbUaas/a6rqViI7MxPxqX0UT1r
O3wVzpbR2hviP5i03Y5s6a879FNtHljydhExCv8AMTPJXBnRZbz0iG5ptFjwe/l96zctMVamTJtE
yTMibu1VrdTzRMR0j0ed4lr64MVpm0RERvMz5NvX62uOJ69XhOKX1HH9bHDtFvNYnfJeOy0Z2ojX
6jjnEq6fRUmccTvN/J9H0eKcOnx45neaxEbubwHgOHg+milI3vP2resu3Wu0JQmITsmISDHZHKz2
JgFc1RMLJhGwK9iIZ7MZgEdgmAEwyiWCdwWRLKJVxKYsC2JTuriWUSDNlEsIlMAySx3SCRCQSIAS
AAACRACQAAAAAAASIASAAAAAAAAAAAAAAACRACRACQASIAAAAAAAAAAAAAAAAAAAAAAAAQCUAAAA
AAAAAAIAAAAAAAAQAAAAAACBICBICAAEJAQJQCJcLjuS2ny6fPG/LWdpd1o8T0X07SXx/e7wCdJx
Wa0jmneHQpxPDMdZmJfNtZm49weZrh0/j4o7VtSZ2+Uw0/8A7o49k92vBLc/ntFohFW9PqGXimOI
6Tu1L8T3eCx6r2t1O3JwvHjifO99v7t/Bwf2l1PXU6rS6eJ8qUm8x+so5TsekzcSjbvs4mt4rzW5
K2mbT0itesy2cHsvbvqtbmyz5xERWP2jd1tJwrTaONsOKtZ8585+cnDrzmn4Rq+IZObUROHD32n7
Vv8A0ej0uhxaXFGPFSK1j0bkY4jyZRVZVXFGUVWbGwKsk8mObekNrSW3pWf1a2aYjHbm7bNnQ1id
PW0TvuDdhJEbQABMsLW2R0ZTMQrvfbz2YWzVhpanUxEd0dWkW5c8R5uXxDX1w4pnfr5Q19XxKuOJ
2neXltVqtVxbV/RdJ715+1bypANfiOu1HENV9C0MTfNeesx2rD1PAeBYuE6aKx72W3W9/WVnBuB4
eF4dqRzZbdb5J72l160WVK02ZxCYhOwI23TsnY2BGxsnYBjsiYZsZBjMMZZSgGEolMsQDdG6NwZ7
piVe6YkFsSziVMWZRILolMSriWUSCyJTuwhMSDMRCQSI3SAlACRCQAAEoAEoASAAAAAAAAACUACR
ACQAAAAAAAAAAAAASAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAABAAAAAAAAAAAAACBKAAAAAAAQ
JQAAAhICEbJAYTWJ7wx8KvpC0BV4ceieWGewDHlNmWwCNjZICNhIDmcZredBecdpiY69FXCOLW+i
UiZidukulmxxlx2paN4mNng+K4+I8Hy2yaTfl37TXetoCPfRxfp1qi3F48ofKMvtvxak8s6LDv61
rZji9rPaLUf5PC+bfttS0q8q3p9W/wBrRMdpUZuKdN99nzvFqPbTVz7nD8OKs+do2/mW3h4D7Xaq
ZnPrtNpqz35aRaYOHY9Zk4pNt9rR+rl6zi+OnS+WN57Rv1lXp/YrNaYtruL6zNPnGO3hxP6O5w/2
f0HDuun09Yv55Le9afznqcOvO4tBreMTHu30unnva0bWt8on+70nDuE4OHYYx4Kbesz3tPrMuhGO
IjpDOKrK9YVpsyiGUQnYGOyUgI2SlAIEmwMWMs9kTAMJYzDOYRMArmGErZhhMArlHmzmGMwDE3Ts
bAbs4swj5pgFkSziVcM4BZEsolXDKAZwyhjCYBkACQhIAAAAAAAJAAAAAAAAAAAAAAAAAAAShIAA
AAAAAAJAAAAAAAAAAAAAABAJEAAAAAAAAAAAAAAAIEoBKAAAAAAAAAAAAAAABAlAAAAAAAIAAAAA
BAkBAkBAkBAlACEgMZjdjbFW8bWrEx8YWANb6Fp+bfwab+vLDKMFK9qxH5L0bAr8OPRPKz2AY7J2
SbAjYZAI2E7AIEgIEgIEgMdkSy2NgY7MdlmyNoBXsxmFuyNgVTVjNV3KjlBRNTlXTVHKCrlIqt5T
lBhEMohlFerLlBjEMohMVTEARDKCITsAk2AEgAAAkAAAAAAAAAAAAAAAAAAAAAAAASAAAAAAAAD/
2Q==`;
// src/warmup.ts
async function warmupBitmap(instance) {
const b64toBlob = (base64, type = "application/octet-stream") => fetch(`data:${type};base64,${base64}`).then((res2) => res2.blob());
let blob;
let res;
switch (instance.config.warmup) {
case "face":
blob = await b64toBlob(face3);
break;
case "body":
case "full":
blob = await b64toBlob(body3);
break;
default:
blob = null;
}
if (blob) {
const bitmap = await createImageBitmap(blob);
res = await instance.detect(bitmap, instance.config);
bitmap.close();
}
return res;
}
async function warmupCanvas(instance) {
return new Promise((resolve) => {
let src;
switch (instance.config.warmup) {
case "face":
src = "data:image/jpeg;base64," + face3;
break;
case "full":
case "body":
src = "data:image/jpeg;base64," + body3;
break;
default:
src = null;
}
let img;
if (typeof Image !== "undefined")
img = new Image();
else if (env.Image)
img = new env.Image();
else
return;
img.onload = async () => {
const canvas3 = canvas(img.naturalWidth, img.naturalHeight);
if (!canvas3) {
log("Warmup: Canvas not found");
resolve(void 0);
} else {
const ctx = canvas3.getContext("2d");
if (ctx)
ctx.drawImage(img, 0, 0);
const tensor = await instance.image(canvas3);
const res = await instance.detect(tensor.tensor, instance.config);
resolve(res);
}
};
if (src)
img.src = src;
else
resolve(void 0);
});
}
async function warmupNode(instance) {
const atob2 = (str) => Buffer.from(str, "base64");
let img;
if (instance.config.warmup === "face")
img = atob2(face3);
else
img = atob2(body3);
let res;
if ("node" in tfjs_esm_exports) {
const data = (void 0).decodeJpeg(img);
const expanded = data.expandDims(0);
instance.tf.dispose(data);
res = await instance.detect(expanded, instance.config);
instance.tf.dispose(expanded);
} else {
if (instance.config.debug)
log("Warmup tfjs-node not loaded");
}
return res;
}
async function runInference(instance) {
let res;
if (typeof createImageBitmap === "function")
res = await warmupBitmap(instance);
else if (typeof Image !== "undefined" || env.Canvas !== void 0)
res = await warmupCanvas(instance);
else
res = await warmupNode(instance);
return res;
}
async function runCompile(allModels) {
const backendType = Mpe();
const webGLBackend = $A();
if (backendType !== "webgl" && backendType !== "humangl" || (!webGLBackend || !webGLBackend.checkCompileCompletion)) {
return;
}
K().set("ENGINE_COMPILE_ONLY", true);
const numTensorsStart = ds().state.numTensors;
const compiledModels = [];
for (const [modelName, model18] of Object.entries(allModels).filter(([key, val]) => key !== null && val !== null)) {
const shape = model18.inputs && model18.inputs[0] && model18.inputs[0].shape ? [...model18.inputs[0].shape] : [1, 64, 64, 3];
const dtype = model18.inputs && model18.inputs[0] && model18.inputs[0].dtype ? model18.inputs[0].dtype : "float32";
for (let dim = 0; dim < shape.length; dim++) {
if (shape[dim] === -1)
shape[dim] = dim === 0 ? 1 : 64;
}
const tensor = $t(shape, dtype);
try {
const res = model18.execute(tensor);
compiledModels.push(modelName);
if (Array.isArray(res))
res.forEach((t) => De(t));
else
De(res);
} catch (e) {
log("compile fail model:", modelName);
}
De(tensor);
}
const kernels = await webGLBackend.checkCompileCompletionAsync();
webGLBackend.getUniformLocations();
log("compile pass models:", compiledModels);
log("compile pass kernels:", kernels.length);
K().set("ENGINE_COMPILE_ONLY", false);
const numTensorsEnd = ds().state.numTensors;
if (numTensorsEnd - numTensorsStart > 0)
log("tensor leak:", numTensorsEnd - numTensorsStart);
}
async function warmup(instance, userConfig) {
const t02 = now();
instance.state = "warmup";
if (userConfig)
instance.config = mergeDeep(instance.config, userConfig);
if (!instance.config.warmup || instance.config.warmup.length === 0 || instance.config.warmup === "none") {
return { face: [], body: [], hand: [], gesture: [], object: [], performance: instance.performance, timestamp: now(), persons: [], error: null };
}
return new Promise(async (resolve) => {
await runCompile(instance.models);
const res = await runInference(instance);
const t12 = now();
if (instance.config.debug)
log("warmup", instance.config.warmup, Math.round(t12 - t02), "ms");
instance.emit("warmup");
resolve(res);
});
}
// src/human.ts
var _numTensors, _analyzeMemoryLeaks, _checkSanity, _sanity;
var Human = class {
constructor(userConfig) {
__publicField(this, "version");
__publicField(this, "config");
__publicField(this, "result");
__publicField(this, "state");
__publicField(this, "process");
__publicField(this, "tf");
__publicField(this, "env");
__publicField(this, "draw");
__publicField(this, "models");
__publicField(this, "events");
__publicField(this, "faceTriangulation");
__publicField(this, "faceUVMap");
__publicField(this, "performance");
__privateAdd(this, _numTensors, void 0);
__privateAdd(this, _analyzeMemoryLeaks, void 0);
__privateAdd(this, _checkSanity, void 0);
__publicField(this, "gl");
__publicField(this, "analyze", (...msg) => {
if (!__privateGet(this, _analyzeMemoryLeaks))
return;
const currentTensors = this.tf.engine().state.numTensors;
const previousTensors = __privateGet(this, _numTensors);
__privateSet(this, _numTensors, currentTensors);
const leaked = currentTensors - previousTensors;
if (leaked !== 0)
log(...msg, leaked);
});
__privateAdd(this, _sanity, (input) => {
if (!__privateGet(this, _checkSanity))
return null;
if (!input)
return "input is not defined";
if (this.env.node && !(input instanceof et))
return "input must be a tensor";
try {
this.tf.getBackend();
} catch (e) {
return "backend not loaded";
}
return null;
});
__publicField(this, "similarity", similarity);
__publicField(this, "distance", distance);
__publicField(this, "match", match2);
__publicField(this, "emit", (event) => {
var _a2;
if (this.events && this.events.dispatchEvent)
(_a2 = this.events) == null ? void 0 : _a2.dispatchEvent(new Event(event));
});
var _a2;
this.env = env;
const tfVersion = (((_a2 = Ghe) == null ? void 0 : _a2.tfjs) || Gpe).replace(/-(.*)/, "");
config.wasmPath = `https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${tfVersion}/dist/`;
config.modelBasePath = env.browser ? "../models/" : "file://models/";
config.backend = env.browser ? "humangl" : "tensorflow";
this.version = version;
Object.defineProperty(this, "version", { value: version });
this.config = JSON.parse(JSON.stringify(config));
Object.seal(this.config);
this.config.cacheModels = typeof indexedDB !== "undefined";
if (userConfig)
this.config = mergeDeep(this.config, userConfig);
setModelLoadOptions(this.config);
this.tf = tfjs_esm_exports;
this.state = "idle";
__privateSet(this, _numTensors, 0);
__privateSet(this, _analyzeMemoryLeaks, false);
__privateSet(this, _checkSanity, false);
this.performance = {};
this.events = typeof EventTarget !== "undefined" ? new EventTarget() : void 0;
this.models = new Models();
this.draw = {
options: options3,
canvas: (input, output) => canvas2(input, output),
face: (output, result, options4) => face(output, result, options4),
body: (output, result, options4) => body(output, result, options4),
hand: (output, result, options4) => hand(output, result, options4),
gesture: (output, result, options4) => gesture(output, result, options4),
object: (output, result, options4) => object(output, result, options4),
person: (output, result, options4) => person(output, result, options4),
all: (output, result, options4) => all(output, result, options4)
};
this.result = { face: [], body: [], hand: [], gesture: [], object: [], performance: {}, timestamp: 0, persons: [], error: null };
this.process = { tensor: null, canvas: null };
this.faceTriangulation = triangulation;
this.faceUVMap = uvmap;
this.gl = config2;
this.emit("create");
}
reset() {
const currentBackend = this.config.backend;
this.config = JSON.parse(JSON.stringify(config));
this.config.backend = currentBackend;
}
validate(userConfig) {
return validate(config, userConfig || this.config);
}
now() {
return now();
}
image(input, getTensor = true) {
return process2(input, this.config, getTensor);
}
async segmentation(input, background) {
return process5(input, background, this.config);
}
enhance(input) {
return enhance(input);
}
compare(firstImageTensor, secondImageTensor) {
return compare(this.config, firstImageTensor, secondImageTensor);
}
async init() {
await check(this, true);
await this.tf.ready();
}
async load(userConfig) {
this.state = "load";
const timeStamp = now();
const count2 = Object.values(this.models).filter((model18) => model18).length;
if (userConfig)
this.config = mergeDeep(this.config, userConfig);
if (this.env.initial) {
if (this.config.debug)
log(`version: ${this.version}`);
if (this.config.debug)
log(`tfjs version: ${this.tf.version["tfjs-core"]}`);
if (!await check(this))
log("error: backend check failed");
await Lpe();
if (this.env.browser) {
if (this.config.debug)
log("configuration:", this.config);
if (this.config.debug)
log("environment:", this.env);
if (this.config.debug)
log("tf flags:", this.tf.ENV["flags"]);
}
}
await load19(this);
if (this.env.initial && this.config.debug)
log("tf engine state:", this.tf.engine().state.numBytes, "bytes", this.tf.engine().state.numTensors, "tensors");
this.env.initial = false;
const loaded = Object.values(this.models).filter((model18) => model18).length;
if (loaded !== count2) {
await validate2(this);
this.emit("load");
}
const current = Math.trunc(now() - timeStamp);
if (current > (this.performance.loadModels || 0))
this.performance.loadModels = this.env.perfadd ? (this.performance.loadModels || 0) + current : current;
}
next(result = this.result) {
return calc2(result, this.config);
}
async warmup(userConfig) {
const t02 = now();
const res = await warmup(this, userConfig);
const t12 = now();
this.performance.warmup = Math.trunc(t12 - t02);
return res;
}
async profile(input, userConfig) {
const profile = await this.tf.profile(() => this.detect(input, userConfig));
const kernels = {};
for (const kernel of profile.kernels) {
if (kernels[kernel.name])
kernels[kernel.name] += kernel.kernelTimeMs;
else
kernels[kernel.name] = kernel.kernelTimeMs;
}
const kernelArr = [];
Object.entries(kernels).forEach((key) => kernelArr.push({ name: key[0], ms: key[1] }));
kernelArr.sort((a, b) => b.ms - a.ms);
kernelArr.length = 20;
const res = {};
for (const kernel of kernelArr)
res[kernel.name] = kernel.ms;
return res;
}
async detect(input, userConfig) {
this.state = "detect";
return new Promise(async (resolve) => {
var _a2, _b2, _c, _d2, _e2, _f, _g2, _h, _i2, _j2, _k2, _l2, _m2, _n2, _o, _p2, _q2, _r2, _s2, _t2, _u2, _v2;
this.state = "config";
let timeStamp;
this.config = mergeDeep(this.config, userConfig);
this.state = "check";
const error = __privateGet(this, _sanity).call(this, input);
if (error) {
log(error, input);
this.emit("error");
resolve({ face: [], body: [], hand: [], gesture: [], object: [], performance: this.performance, timestamp: now(), persons: [], error });
}
const timeStart = now();
await check(this);
await this.load();
timeStamp = now();
this.state = "image";
const img = await process2(input, this.config);
this.process = img;
this.performance.inputProcess = this.env.perfadd ? (this.performance.inputProcess || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
this.analyze("Get Image:");
if (!img.tensor) {
if (this.config.debug)
log("could not convert input to tensor");
this.emit("error");
resolve({ face: [], body: [], hand: [], gesture: [], object: [], performance: this.performance, timestamp: now(), persons: [], error: "could not convert input to tensor" });
return;
}
this.emit("image");
timeStamp = now();
this.config.skipAllowed = await skip(this.config, img.tensor);
if (!this.performance.totalFrames)
this.performance.totalFrames = 0;
if (!this.performance.cachedFrames)
this.performance.cachedFrames = 0;
this.performance.totalFrames++;
if (this.config.skipAllowed)
this.performance.cachedFrames++;
this.performance.cacheCheck = this.env.perfadd ? (this.performance.cacheCheck || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
this.analyze("Check Changed:");
let faceRes = [];
let bodyRes = [];
let handRes = [];
let objectRes = [];
this.state = "detect:face";
if (this.config.async) {
faceRes = this.config.face.enabled ? detectFace(this, img.tensor) : [];
if (this.performance.face)
delete this.performance.face;
} else {
timeStamp = now();
faceRes = this.config.face.enabled ? await detectFace(this, img.tensor) : [];
this.performance.face = this.env.perfadd ? (this.performance.face || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
}
if (this.config.async && (this.config.body.maxDetected === -1 || this.config.hand.maxDetected === -1))
faceRes = await faceRes;
this.analyze("Start Body:");
this.state = "detect:body";
const bodyConfig = this.config.body.maxDetected === -1 ? mergeDeep(this.config, { body: { maxDetected: this.config.face.enabled ? 1 * faceRes.length : 1 } }) : this.config;
if (this.config.async) {
if ((_a2 = this.config.body.modelPath) == null ? void 0 : _a2.includes("posenet"))
bodyRes = this.config.body.enabled ? predict17(img.tensor, bodyConfig) : [];
else if ((_b2 = this.config.body.modelPath) == null ? void 0 : _b2.includes("blazepose"))
bodyRes = this.config.body.enabled ? predict5(img.tensor, bodyConfig) : [];
else if ((_c = this.config.body.modelPath) == null ? void 0 : _c.includes("efficientpose"))
bodyRes = this.config.body.enabled ? predict7(img.tensor, bodyConfig) : [];
else if ((_d2 = this.config.body.modelPath) == null ? void 0 : _d2.includes("movenet"))
bodyRes = this.config.body.enabled ? predict15(img.tensor, bodyConfig) : [];
if (this.performance.body)
delete this.performance.body;
} else {
timeStamp = now();
if ((_e2 = this.config.body.modelPath) == null ? void 0 : _e2.includes("posenet"))
bodyRes = this.config.body.enabled ? await predict17(img.tensor, bodyConfig) : [];
else if ((_f = this.config.body.modelPath) == null ? void 0 : _f.includes("blazepose"))
bodyRes = this.config.body.enabled ? await predict5(img.tensor, bodyConfig) : [];
else if ((_g2 = this.config.body.modelPath) == null ? void 0 : _g2.includes("efficientpose"))
bodyRes = this.config.body.enabled ? await predict7(img.tensor, bodyConfig) : [];
else if ((_h = this.config.body.modelPath) == null ? void 0 : _h.includes("movenet"))
bodyRes = this.config.body.enabled ? await predict15(img.tensor, bodyConfig) : [];
this.performance.body = this.env.perfadd ? (this.performance.body || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
}
this.analyze("End Body:");
this.analyze("Start Hand:");
this.state = "detect:hand";
const handConfig = this.config.hand.maxDetected === -1 ? mergeDeep(this.config, { hand: { maxDetected: this.config.face.enabled ? 2 * faceRes.length : 1 } }) : this.config;
if (this.config.async) {
if ((_j2 = (_i2 = this.config.hand.detector) == null ? void 0 : _i2.modelPath) == null ? void 0 : _j2.includes("handdetect"))
handRes = this.config.hand.enabled ? predict12(img.tensor, handConfig) : [];
else if ((_l2 = (_k2 = this.config.hand.detector) == null ? void 0 : _k2.modelPath) == null ? void 0 : _l2.includes("handtrack"))
handRes = this.config.hand.enabled ? predict13(img.tensor, handConfig) : [];
if (this.performance.hand)
delete this.performance.hand;
} else {
timeStamp = now();
if ((_n2 = (_m2 = this.config.hand.detector) == null ? void 0 : _m2.modelPath) == null ? void 0 : _n2.includes("handdetect"))
handRes = this.config.hand.enabled ? await predict12(img.tensor, handConfig) : [];
else if ((_p2 = (_o = this.config.hand.detector) == null ? void 0 : _o.modelPath) == null ? void 0 : _p2.includes("handtrack"))
handRes = this.config.hand.enabled ? await predict13(img.tensor, handConfig) : [];
this.performance.hand = this.env.perfadd ? (this.performance.hand || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
}
this.analyze("End Hand:");
this.analyze("Start Object:");
this.state = "detect:object";
if (this.config.async) {
if ((_q2 = this.config.object.modelPath) == null ? void 0 : _q2.includes("nanodet"))
objectRes = this.config.object.enabled ? predict16(img.tensor, this.config) : [];
else if ((_r2 = this.config.object.modelPath) == null ? void 0 : _r2.includes("centernet"))
objectRes = this.config.object.enabled ? predict6(img.tensor, this.config) : [];
if (this.performance.object)
delete this.performance.object;
} else {
timeStamp = now();
if ((_s2 = this.config.object.modelPath) == null ? void 0 : _s2.includes("nanodet"))
objectRes = this.config.object.enabled ? await predict16(img.tensor, this.config) : [];
else if ((_t2 = this.config.object.modelPath) == null ? void 0 : _t2.includes("centernet"))
objectRes = this.config.object.enabled ? await predict6(img.tensor, this.config) : [];
this.performance.object = this.env.perfadd ? (this.performance.object || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
}
this.analyze("End Object:");
this.state = "detect:await";
if (this.config.async)
[faceRes, bodyRes, handRes, objectRes] = await Promise.all([faceRes, bodyRes, handRes, objectRes]);
this.state = "detect:gesture";
let gestureRes = [];
if (this.config.gesture.enabled) {
timeStamp = now();
gestureRes = [...face2(faceRes), ...body2(bodyRes), ...hand2(handRes), ...iris(faceRes)];
if (!this.config.async)
this.performance.gesture = this.env.perfadd ? (this.performance.gesture || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
else if (this.performance.gesture)
delete this.performance.gesture;
}
this.performance.total = this.env.perfadd ? (this.performance.total || 0) + Math.trunc(now() - timeStart) : Math.trunc(now() - timeStart);
const shape = ((_v2 = (_u2 = this.process) == null ? void 0 : _u2.tensor) == null ? void 0 : _v2.shape) || [];
this.result = {
face: faceRes,
body: bodyRes,
hand: handRes,
gesture: gestureRes,
object: objectRes,
performance: this.performance,
canvas: this.process.canvas,
timestamp: Date.now(),
error: null,
get persons() {
return join2(faceRes, bodyRes, handRes, gestureRes, shape);
}
};
De(img.tensor);
this.emit("detect");
this.state = "idle";
resolve(this.result);
});
}
};
_numTensors = new WeakMap();
_analyzeMemoryLeaks = new WeakMap();
_checkSanity = new WeakMap();
_sanity = new WeakMap();
export {
Human,
Human as default,
config as defaults,
draw_exports as draw,
env,
match_exports as match,
models_exports as models
};
/**
* @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.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @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.
* =============================================================================
*/
/**
* @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.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use backend file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT 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 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.
* =============================================================================
*/
/**
* @license
* Copyright 2021 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @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.
* =============================================================================
*/
/**
* @license
* Copyright 2022 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2022 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2022 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2022 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Human main module
* @default Human Library
* @summary <https://github.com/vladmandic/human>
* @author <https://github.com/vladmandic>
* @copyright <https://github.com/vladmandic>
* @license MIT
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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. */
//# sourceMappingURL=human.esm.js.map